<?php
// Start session
session_start();

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

// Redirect if not admin - using functions from connection.php
if (!is_logged_in() || !is_user_type('admin')) {
    http_response_code(403);
    echo "Unauthorized access";
    exit();
}

// Get filter parameters
$buyer_id = isset($_POST['buyer']) ? intval($_POST['buyer']) : null;
$color_id = isset($_POST['color']) ? intval($_POST['color']) : null;
$component_id = isset($_POST['component']) ? intval($_POST['component']) : null;
$status = isset($_POST['status']) ? $_POST['status'] : null;

// Initialize counters at the top level
$total_colors = 0;
$total_components = 0;

// Base query for master color panel with buyer and collection_surabaya info
$query = "
    SELECT 
        mcp.id AS color_id,
        mcp.code_color,
        mcp.deskripsi,
        mcp.kode_warna_hex,
        mcp.lemari,
        mcp.status as color_status,
        mcp.keterangan_warna,
        b.nama_buyer,
        b.kode_buyer,
        c.nama_collection_surabaya
    FROM 
        master_color_panel_surabaya mcp
    INNER JOIN 
        buyers_surabaya b ON mcp.buyer_id = b.id
    INNER JOIN 
        collection_surabayas c ON mcp.collection_surabaya_id = c.id
";

// Add where clause based on filters
$where_clauses = [];
$params = [];
$param_types = "";

if ($buyer_id) {
    $where_clauses[] = "mcp.buyer_id = ?";
    $params[] = $buyer_id;
    $param_types .= "i";
}

if ($color_id) {
    $where_clauses[] = "mcp.id = ?";
    $params[] = $color_id;
    $param_types .= "i";
}

// Add where clause if any filters are set
if (!empty($where_clauses)) {
    $query .= " WHERE " . implode(" AND ", $where_clauses);
}

// Add order by
$query .= " ORDER BY b.nama_buyer, mcp.code_color";

// Prepare and execute the query
$stmt = $conn->prepare($query);

if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();

// Display results in grid format
?>

<div class="grid grid-cols-1 gap-6">
    <?php 
    if ($result->num_rows == 0): 
    ?>
        <div class="bg-yellow-100 text-yellow-800 p-4 rounded-md">
            <p class="text-center font-medium">Tidak ada data yang sesuai dengan filter yang dipilih.</p>
        </div>
    <?php 
    else: 
        while ($color = $result->fetch_assoc()): 
            // If component filter is applied, check if this color has any matching components
            if ($component_id) {
                $check_query = "
                    SELECT COUNT(*) as count
                    FROM color_stock_items_surabaya csi
                    WHERE csi.color_id = ? AND csi.component_id = ?
                ";
                $check_stmt = $conn->prepare($check_query);
                $check_stmt->bind_param("ii", $color['color_id'], $component_id);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result()->fetch_assoc();
                $check_stmt->close();
                
                if ($check_result['count'] == 0) {
                    continue; // Skip this color if it has no matching components
                }
            }
            
            // If status filter is applied, check if this color has any components with matching status
            if ($status) {
                $status_check_query = "
                    SELECT COUNT(*) as count
                    FROM color_stock_items_surabaya csi
                    WHERE csi.color_id = ? AND csi.status = ?
                ";
                $status_check_stmt = $conn->prepare($status_check_query);
                $status_check_stmt->bind_param("is", $color['color_id'], $status);
                $status_check_stmt->execute();
                $status_check_result = $status_check_stmt->get_result()->fetch_assoc();
                $status_check_stmt->close();
                
                if ($status_check_result['count'] == 0) {
                    continue; // Skip this color if it has no components with matching status
                }
            }
            
            $total_colors++;
    ?>
        <div class="color-item border border-gray-200 rounded-lg overflow-hidden shadow-lg">
            <!-- Color Header -->
            <div class="flex items-center justify-between p-4 border-b border-gray-200" style="background: linear-gradient(135deg, <?php echo htmlspecialchars($color['kode_warna_hex']); ?>20, <?php echo htmlspecialchars($color['kode_warna_hex']); ?>10);">
                <div class="flex items-center">
                    <div class="flex-shrink-0 w-10 h-10 rounded-full mr-4 border-2 border-white shadow-lg" style="background-color: <?php echo htmlspecialchars($color['kode_warna_hex']); ?>;"></div>
                    <div class="flex-grow">
                        <h4 class="font-bold text-lg text-gray-800">
                            <?php echo htmlspecialchars($color['kode_buyer'] . ' ' . $color['code_color']); ?>
                        </h4>
                        <p class="text-sm text-gray-600 mb-1">
                            <?php echo htmlspecialchars($color['deskripsi']); ?> - 
                            <?php echo htmlspecialchars($color['nama_collection_surabaya']); ?>
                        </p>
                        <?php if ($color['keterangan_warna']): ?>
                        <p class="text-xs text-gray-500">
                            <i class="fas fa-info-circle mr-1"></i><?php echo htmlspecialchars($color['keterangan_warna']); ?>
                        </p>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="flex flex-col items-end space-y-2">
                    <!-- Color Status Badge -->
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium
                        <?php 
                        switch ($color['color_status']) {
                            case 'Hijau': echo 'bg-green-100 text-green-800'; break;
                            case 'Kuning': echo 'bg-yellow-100 text-yellow-800'; break;
                            case 'Merah': echo 'bg-red-100 text-red-800'; break;
                            default: echo 'bg-gray-100 text-gray-800';
                        }
                        ?>">
                        <i class="fas fa-circle mr-1 text-xs"></i>
                        <?php echo htmlspecialchars($color['color_status']); ?>
                    </span>
                    
                    <!-- Lemari Badge -->
                    <?php if ($color['lemari']): ?>
                    <span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-blue-100 text-blue-800">
                        <i class="fas fa-archive mr-1"></i>Lemari <?php echo htmlspecialchars($color['lemari']); ?>
                    </span>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Component Table -->
            <div class="p-4">
                <h5 class="font-semibold text-gray-700 mb-3 flex items-center">
                    <i class="fas fa-layer-group mr-2 text-blue-500"></i>
                    Komponen & Stock Items
                </h5>
                
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Component</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kode Barang</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Rack No</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Lokasi</th>
                                <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal Expired</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php
                            // Get components for this color - Updated query for new structure
                            $comp_query = "
                                SELECT 
                                    cc.id AS component_id,
                                    cc.component_name,
                                    csi.id as stock_id,
                                    csi.kode_barang,
                                    csi.stock_number,
                                    csi.rack_no,
                                    csi.status,
                                    csi.lokasi,
                                    csi.tanggal_pembuatan,
                                    csi.tanggal_kedaluwarsa,
                                    csi.keterangan
                                FROM 
                                    color_stock_items_surabaya csi
                                INNER JOIN 
                                    color_components_surabaya cc ON csi.component_id = cc.id
                                WHERE 
                                    csi.color_id = ?
                            ";
                            
                            // If component filter is set, we only show matching components
                            if ($component_id) {
                                $comp_query .= " AND cc.id = ?";
                            }
                            
                            // If status filter is set, we only show matching status components
                            if ($status) {
                                $comp_query .= " AND csi.status = ?";
                            }
                            
                            // Add ORDER BY for better organization
                            $comp_query .= " ORDER BY cc.component_name, csi.stock_number";
                            
                            $comp_stmt = $conn->prepare($comp_query);
                            
                            if ($component_id && $status) {
                                $comp_stmt->bind_param("iis", $color['color_id'], $component_id, $status);
                            } else if ($component_id) {
                                $comp_stmt->bind_param("ii", $color['color_id'], $component_id);
                            } else if ($status) {
                                $comp_stmt->bind_param("is", $color['color_id'], $status);
                            } else {
                                $comp_stmt->bind_param("i", $color['color_id']);
                            }
                            
                            $comp_stmt->execute();
                            $comp_result = $comp_stmt->get_result();
                            
                            $component_count = 0;
                            
                            while ($component = $comp_result->fetch_assoc()):
                                $component_count++;
                                $total_components++;
                                
                                // Check if item is near expiry or expired
                                $expiry_class = '';
                                $expiry_text = '';
                                
                                if ($component['tanggal_kedaluwarsa']) {
                                    $expiry_date = new DateTime($component['tanggal_kedaluwarsa']);
                                    $today = new DateTime();
                                    $interval = $today->diff($expiry_date);
                                    $days_remaining = $interval->format('%R%a');
                                    
                                    if ($days_remaining < 0) {
                                        $expiry_class = 'bg-red-50 border-l-4 border-red-400';
                                        $expiry_text = 'Expired';
                                    } elseif ($days_remaining <= 30) {
                                        $expiry_class = 'bg-yellow-50 border-l-4 border-yellow-400';
                                        $expiry_text = $days_remaining . ' hari lagi';
                                    }
                                }
                            ?>
                                <tr class="component-row hover:bg-gray-50 <?php echo $expiry_class; ?>">
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <div class="flex items-center">
                                            <div class="flex-shrink-0 h-8 w-8">
                                                <div class="h-8 w-8 rounded-full bg-blue-100 flex items-center justify-center">
                                                    <i class="fas fa-puzzle-piece text-blue-600 text-sm"></i>
                                                </div>
                                            </div>
                                            <div class="ml-3">
                                                <div class="text-sm font-medium text-gray-900">
                                                    <?php echo htmlspecialchars($component['component_name']); ?>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <span class="bg-gray-100 text-gray-800 px-3 py-1 rounded-md font-mono text-sm font-semibold">
                                            <?php echo htmlspecialchars($component['kode_barang']); ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                                        <span class="bg-indigo-100 text-indigo-800 px-2 py-1 rounded-md text-xs font-medium">
                                            <?php echo htmlspecialchars($component['rack_no']); ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                                            <?php 
                                            switch ($component['status']) {
                                                case 'Tersedia': echo 'bg-green-100 text-green-800'; break;
                                                case 'Dipinjam': echo 'bg-blue-100 text-blue-800'; break;
                                                case 'Rusak': echo 'bg-red-100 text-red-800'; break;
                                                case 'Expired': echo 'bg-gray-100 text-gray-800'; break;
                                                case 'Renew': echo 'bg-purple-100 text-purple-800'; break;
                                                case 'Hilang': echo 'bg-yellow-100 text-yellow-800'; break;
                                                default: echo 'bg-gray-100 text-gray-800';
                                            }
                                            ?>">
                                            <?php 
                                            switch ($component['status']) {
                                                case 'Tersedia': echo '<i class="fas fa-check-circle mr-1"></i>'; break;
                                                case 'Dipinjam': echo '<i class="fas fa-hand-holding mr-1"></i>'; break;
                                                case 'Rusak': echo '<i class="fas fa-exclamation-triangle mr-1"></i>'; break;
                                                case 'Expired': echo '<i class="fas fa-clock mr-1"></i>'; break;
                                                case 'Renew': echo '<i class="fas fa-refresh mr-1"></i>'; break;
                                                case 'Hilang': echo '<i class="fas fa-question-circle mr-1"></i>'; break;
                                                default: echo '<i class="fas fa-circle mr-1"></i>';
                                            }
                                            echo htmlspecialchars($component['status']);
                                            ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-gray-100 text-gray-800">
                                            <i class="fas fa-map-marker-alt mr-1"></i>
                                            <?php echo htmlspecialchars($component['lokasi']); ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap text-sm">
                                        <?php 
                                        if ($component['tanggal_kedaluwarsa']) {
                                            echo '<div class="text-gray-900">' . date('d M Y', strtotime($component['tanggal_kedaluwarsa'])) . '</div>';
                                            
                                            if ($expiry_text) {
                                                $text_class = $days_remaining < 0 ? 'text-red-600' : 'text-yellow-600';
                                                echo '<div class="' . $text_class . ' text-xs font-medium">(' . $expiry_text . ')</div>';
                                            }
                                        } else {
                                            echo '<span class="text-gray-400">-</span>';
                                        }
                                        ?>
                                    </td>
                                </tr>
                            <?php 
                            endwhile; 
                            $comp_stmt->close();
                            ?>
                            
                            <?php if ($component_count === 0): ?>
                                <tr>
                                    <td colspan="6" class="px-4 py-8 text-sm text-gray-500 text-center">
                                        <div class="flex flex-col items-center">
                                            <i class="fas fa-box-open text-gray-400 text-2xl mb-2"></i>
                                            <span>Tidak ada komponen yang sesuai dengan filter</span>
                                        </div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Component Summary -->
                <?php if ($component_count > 0): ?>
                <div class="mt-4 bg-gray-50 rounded-lg p-3">
                    <div class="flex items-center justify-between text-sm">
                        <span class="font-medium text-gray-600">
                            <i class="fas fa-layer-group mr-1"></i>
                            Total Komponen: <?php echo $component_count; ?>
                        </span>
                        <div class="flex space-x-2">
                            <?php
                            // Get status counts for this color
                            $status_query = "
                                SELECT status, COUNT(*) as count 
                                FROM color_stock_items_surabaya 
                                WHERE color_id = ? 
                                GROUP BY status
                            ";
                            $status_stmt = $conn->prepare($status_query);
                            $status_stmt->bind_param("i", $color['color_id']);
                            $status_stmt->execute();
                            $status_result = $status_stmt->get_result();
                            
                            while ($status_row = $status_result->fetch_assoc()):
                                $badge_class = '';
                                switch ($status_row['status']) {
                                    case 'Tersedia': $badge_class = 'bg-green-100 text-green-700'; break;
                                    case 'Dipinjam': $badge_class = 'bg-blue-100 text-blue-700'; break;
                                    case 'Rusak': $badge_class = 'bg-red-100 text-red-700'; break;
                                    default: $badge_class = 'bg-gray-100 text-gray-700';
                                }
                            ?>
                                <span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium <?php echo $badge_class; ?>">
                                    <?php echo htmlspecialchars($status_row['status']); ?>: <?php echo $status_row['count']; ?>
                                </span>
                            <?php 
                            endwhile;
                            $status_stmt->close();
                            ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    <?php 
        endwhile; 
    endif;
    ?>
</div>

<!-- Summary Statistics -->
<div class="mt-6 bg-gradient-to-r from-blue-50 to-indigo-50 p-6 rounded-lg border border-blue-200">
    <div class="flex justify-between items-center">
        <div class="flex items-center space-x-6">
            <div class="flex items-center">
                <div class="flex-shrink-0 h-10 w-10 bg-blue-500 rounded-full flex items-center justify-center">
                    <i class="fas fa-palette text-white"></i>
                </div>
                <div class="ml-3">
                    <div class="text-lg font-semibold text-blue-900"><?php echo $total_colors; ?></div>
                    <div class="text-sm text-blue-700">Total Warna</div>
                </div>
            </div>
            
            <div class="flex items-center">
                <div class="flex-shrink-0 h-10 w-10 bg-indigo-500 rounded-full flex items-center justify-center">
                    <i class="fas fa-layer-group text-white"></i>
                </div>
                <div class="ml-3">
                    <div class="text-lg font-semibold text-indigo-900"><?php echo $total_components; ?></div>
                    <div class="text-sm text-indigo-700">Total Komponen</div>
                </div>
            </div>
        </div>
        
        <div class="text-right">
            <div class="text-xs text-gray-500">Last updated</div>
            <div class="text-sm font-medium text-gray-700"><?php echo date('d M Y, H:i'); ?></div>
        </div>
    </div>
</div>

<?php
// Show message if component filter is applied but no matching colors found
if (($component_id || $status) && $total_colors == 0): 
?>
<div class="mt-4 bg-yellow-100 border border-yellow-400 text-yellow-800 p-4 rounded-md">
    <div class="flex items-center">
        <i class="fas fa-exclamation-triangle mr-2"></i>
        <p class="font-medium">Tidak ada warna yang memiliki komponen yang sesuai dengan filter yang dipilih.</p>
    </div>
</div>
<?php endif; ?>