<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Redirect if not borrower user
if (!is_logged_in() || !is_user_type('borrower')) {
    header('HTTP/1.1 403 Forbidden');
    echo json_encode(['error' => 'Unauthorized access']);
    exit();
}

// Validate input
if (!isset($_GET['color_id']) || empty($_GET['color_id'])) {
    header('HTTP/1.1 400 Bad Request');
    echo json_encode(['error' => 'Color ID is required']);
    exit();
}

$color_id = intval($_GET['color_id']);

// Fetch components for the selected color code
$stmt = $conn->prepare("
    SELECT csi.id, csi.kode_barang, cc.component_name, csi.status, csi.lokasi, csi.rack_no, csi.keterangan
    FROM color_stock_items csi
    JOIN color_components cc ON csi.component_id = cc.id
    WHERE csi.color_id = ?
    ORDER BY csi.rack_no ASC
");
$stmt->bind_param("i", $color_id);
$stmt->execute();
$result = $stmt->get_result();

$components = [];
while ($row = $result->fetch_assoc()) {
    $components[] = $row;
}

$stmt->close();

// Return components as JSON
header('Content-Type: application/json');
echo json_encode($components);
?>