<?php
// Start session
session_start();

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

// Redirect if not admin
if (!is_logged_in() || !is_user_type('admin')) {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized access']);
    exit();
}

// Get color ID from POST request
$color_id = isset($_POST['color_id']) ? intval($_POST['color_id']) : 0;

if (!$color_id) {
    echo json_encode([]);
    exit();
}

// Query to get components for the specified color
// Updated to use the new database structure
$query = "
    SELECT DISTINCT
        cc.id, cc.component_name
    FROM 
        color_components_semarang cc
    INNER JOIN 
        color_stock_items_semarang csi ON cc.id = csi.component_id
    WHERE 
        csi.color_id = ?
    ORDER BY 
        cc.component_name
";

$stmt = $conn->prepare($query);
$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);
?>