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

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

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

try {
    // Get color codes for the selected buyer with enhanced stock information
    $query = "
        SELECT 
            mcp.id,
            mcp.code_color,
            mcp.deskripsi,
            mcp.lemari,
            mcp.status as color_status,
            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,
            COUNT(DISTINCT cc.id) as total_components
        FROM master_color_panel mcp
        LEFT JOIN color_stock_items csi ON mcp.id = csi.color_id
        LEFT JOIN color_components cc ON csi.component_id = cc.id
        WHERE mcp.buyer_id = ?
        GROUP BY mcp.id, mcp.code_color, mcp.deskripsi, mcp.lemari, mcp.status
        ORDER BY mcp.code_color
    ";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $buyer_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $colors = [];
    while ($row = $result->fetch_assoc()) {
        $colors[] = [
            'id' => $row['id'],
            'code_color' => $row['code_color'],
            'deskripsi' => $row['deskripsi'],
            'lemari' => $row['lemari'],
            'color_status' => $row['color_status'],
            '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'],
            'total_components' => (int)$row['total_components']
        ];
    }
    
    echo json_encode($colors);
    
} catch (Exception $e) {
    error_log("Error in get_color_codes.php: " . $e->getMessage());
    echo json_encode([]);
}

$conn->close();
?>