<?php
require_once "config/connection.php";
header('Content-Type: application/json');

$color_id = isset($_POST['color_id']) ? (int)$_POST['color_id'] : 0;

if ($color_id <= 0) {
    echo json_encode([]);
    exit;
}

try {
    // Get components for the selected color with stock information
    $query = "
        SELECT DISTINCT
            cc.id,
            cc.component_name,
            cc.description,
            COUNT(csi.id) as total_items,
            COUNT(CASE WHEN csi.status = 'Tersedia' THEN 1 END) as tersedia_count,
            COUNT(CASE WHEN csi.status = 'Dipinjam' THEN 1 END) as dipinjam_count,
            COUNT(CASE WHEN csi.status = 'Rusak' THEN 1 END) as rusak_count,
            COUNT(CASE WHEN csi.status = 'Expired' THEN 1 END) as expired_count,
            COUNT(CASE WHEN csi.status = 'Renew' THEN 1 END) as renew_count,
            COUNT(CASE WHEN csi.status = 'Hilang' THEN 1 END) as hilang_count
        FROM color_stock_items csi
        INNER JOIN color_components cc ON csi.component_id = cc.id
        WHERE csi.color_id = ?
        GROUP BY cc.id, cc.component_name, cc.description
        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[] = [
            'id' => $row['id'],
            'component_name' => $row['component_name'],
            'description' => $row['description'],
            'total_items' => (int)$row['total_items'],
            'tersedia_count' => (int)$row['tersedia_count'],
            'dipinjam_count' => (int)$row['dipinjam_count'],
            'rusak_count' => (int)$row['rusak_count'],
            'expired_count' => (int)$row['expired_count'],
            'renew_count' => (int)$row['renew_count'],
            'hilang_count' => (int)$row['hilang_count']
        ];
    }
    
    echo json_encode($components);
    
} catch (Exception $e) {
    error_log("Error in get_color_components_pages.php: " . $e->getMessage());
    echo json_encode([]);
}

$conn->close();
?>