<?php
session_start();
require_once "../config/connection.php";

// Check if user is logged in as IT
if (!is_logged_in() || !is_user_type('it')) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

header('Content-Type: application/json');

try {
    // Get filter parameters
    $buyer_id = isset($_GET['buyer_id']) ? intval($_GET['buyer_id']) : 0;
    $search_color = isset($_GET['search_color']) ? trim($_GET['search_color']) : '';
    
    // Build base query
    $where_conditions = [];
    $params = [];
    
    if ($buyer_id > 0) {
        $where_conditions[] = "mcp.buyer_id = ?";
        $params[] = $buyer_id;
    }
    
    if (!empty($search_color)) {
        $where_conditions[] = "mcp.code_color LIKE ?";
        $params[] = "%$search_color%";
    }
    
    $where_clause = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";
    
    // Query to get color panels with buyer info
    $query = "
        SELECT 
            mcp.id,
            mcp.code_color,
            mcp.deskripsi,
            mcp.lemari,
            mcp.status,
            mcp.kode_warna_hex,
            mcp.keterangan_warna,
            b.nama_buyer,
            b.kode_buyer,
            c.nama_collection
        FROM master_color_panel mcp
        JOIN buyers b ON mcp.buyer_id = b.id
        JOIN collections c ON mcp.collection_id = c.id
        $where_clause
        ORDER BY b.nama_buyer, mcp.code_color
    ";
    
    $stmt = $conn->prepare($query);
    if (!empty($params)) {
        $stmt->bind_param(str_repeat('s', count($params)), ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    
    $html = '';
    
    if ($result->num_rows == 0) {
        $html = '<div class="bg-white rounded-lg shadow-md p-8 text-center text-gray-600">
                    <i class="fas fa-inbox text-4xl mb-4"></i>
                    <p>Tidak ada color panel yang ditemukan</p>
                 </div>';
    } else {
        while ($row = $result->fetch_assoc()) {
            $color_id = $row['id'];
            
            // Get components for this color
            $components_query = "
                SELECT 
                    cpc.id as panel_comp_id,
                    cpc.quantity as required_quantity,
                    cpc.available_quantity,
                    cc.id as component_id,
                    cc.component_name,
                    cc.description
                FROM color_panel_components cpc
                JOIN color_components cc ON cpc.component_id = cc.id
                WHERE cpc.color_id = ?
                ORDER BY cc.component_name
            ";
            
            $comp_stmt = $conn->prepare($components_query);
            $comp_stmt->bind_param('i', $color_id);
            $comp_stmt->execute();
            $comp_result = $comp_stmt->get_result();
            
            // Status badge color
            $status_class = '';
            switch ($row['status']) {
                case 'Hijau':
                    $status_class = 'bg-green-100 text-green-800';
                    break;
                case 'Kuning':
                    $status_class = 'bg-yellow-100 text-yellow-800';
                    break;
                case 'Merah':
                    $status_class = 'bg-red-100 text-red-800';
                    break;
            }
            
            $html .= '
            <div class="bg-white rounded-lg shadow-md mb-6">
                <div class="p-6 border-b border-gray-200">
                    <div class="flex justify-between items-start">
                        <div class="flex-1">
                            <div class="flex items-center space-x-3 mb-2">
                                <h3 class="text-xl font-bold text-gray-800">' . htmlspecialchars($row['code_color']) . '</h3>
                                <span class="px-2 py-1 ' . $status_class . ' text-xs font-medium rounded-full">' . $row['status'] . '</span>
                                <span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs font-medium rounded-full">Lemari ' . htmlspecialchars($row['lemari']) . '</span>
                            </div>
                            <p class="text-gray-600 mb-2">' . htmlspecialchars($row['deskripsi']) . '</p>
                            <div class="text-sm text-gray-500">
                                <span class="font-medium">Buyer:</span> ' . htmlspecialchars($row['nama_buyer'] . ' (' . $row['kode_buyer'] . ')') . ' | 
                                <span class="font-medium">Collection:</span> ' . htmlspecialchars($row['nama_collection']) . '
                            </div>
                            ' . (!empty($row['keterangan_warna']) ? '<p class="text-sm text-gray-500 mt-1">' . htmlspecialchars($row['keterangan_warna']) . '</p>' : '') . '
                        </div>
                        <div class="ml-4">
                            <button onclick="showAddComponentModal(' . $color_id . ', \'' . htmlspecialchars($row['code_color']) . '\')" 
                                    class="px-3 py-1 bg-green-600 text-white text-sm rounded-md hover:bg-green-700 transition-colors">
                                <i class="fas fa-plus mr-1"></i>Tambah Component
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="p-6">
                    <h4 class="text-lg font-semibold text-gray-800 mb-4">Components & Stock</h4>';
            
            if ($comp_result->num_rows == 0) {
                $html .= '<p class="text-gray-500 text-center py-4">Belum ada component untuk color panel ini</p>';
            } else {
                $html .= '<div class="space-y-4">';
                
                while ($comp = $comp_result->fetch_assoc()) {
                    // Get stock items for this component
                    $stock_query = "
                        SELECT 
                            id,
                            kode_barang,
                            stock_number,
                            status,
                            lokasi,
                            rack_no,
                            tanggal_pembuatan,
                            tanggal_kedaluwarsa,
                            keterangan
                        FROM color_stock_items
                        WHERE color_id = ? AND component_id = ?
                        ORDER BY stock_number
                    ";
                    
                    $stock_stmt = $conn->prepare($stock_query);
                    $stock_stmt->bind_param('ii', $color_id, $comp['component_id']);
                    $stock_stmt->execute();
                    $stock_result = $stock_stmt->get_result();
                    
                    // Count stock by status
                    $total_stock = $stock_result->num_rows;
                    $available_count = 0;
                    $borrowed_count = 0;
                    $other_count = 0;
                    
                    $stock_items = [];
                    while ($stock = $stock_result->fetch_assoc()) {
                        $stock_items[] = $stock;
                        if ($stock['status'] == 'Tersedia') {
                            $available_count++;
                        } elseif ($stock['status'] == 'Dipinjam') {
                            $borrowed_count++;
                        } else {
                            $other_count++;
                        }
                    }
                    
                    $html .= '
                    <div class="border border-gray-200 rounded-lg p-4">
                        <div class="flex justify-between items-start mb-3">
                            <div class="flex-1">
                                <h5 class="font-semibold text-gray-800">' . htmlspecialchars($comp['component_name']) . '</h5>
                                ' . (!empty($comp['description']) ? '<p class="text-sm text-gray-500">' . htmlspecialchars($comp['description']) . '</p>' : '') . '
                                <div class="flex items-center space-x-4 mt-2 text-sm">
                                    <span class="text-gray-600">Required: <span class="font-medium">' . $comp['required_quantity'] . '</span></span>
                                    <span class="text-green-600">Tersedia: <span class="font-medium">' . $available_count . '</span></span>
                                    <span class="text-blue-600">Dipinjam: <span class="font-medium">' . $borrowed_count . '</span></span>
                                    <span class="text-gray-600">Total: <span class="font-medium">' . $total_stock . '</span></span>
                                </div>
                            </div>
                            <div class="ml-4 space-x-2">
                                <button onclick="showAddStockModal(' . $color_id . ', ' . $comp['component_id'] . ', \'' . htmlspecialchars($comp['component_name']) . '\')" 
                                        class="px-3 py-1 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 transition-colors">
                                    <i class="fas fa-plus mr-1"></i>Tambah Stock
                                </button>
                            </div>
                        </div>';
                    
                    if (empty($stock_items)) {
                        $html .= '<p class="text-gray-500 text-center py-2">Belum ada stock untuk component ini</p>';
                    } else {
                        $html .= '
                        <div class="overflow-x-auto">
                            <table class="min-w-full text-sm">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th class="px-3 py-2 text-left font-medium text-gray-700">Kode Barang</th>
                                        <th class="px-3 py-2 text-left font-medium text-gray-700">Stock #</th>
                                        <th class="px-3 py-2 text-left font-medium text-gray-700">Status</th>
                                        <th class="px-3 py-2 text-left font-medium text-gray-700">Lokasi</th>
                                        <th class="px-3 py-2 text-left font-medium text-gray-700">Rack</th>
                                        <th class="px-3 py-2 text-left font-medium text-gray-700">Tgl Buat</th>
                                        <th class="px-3 py-2 text-left font-medium text-gray-700">Tgl Expire</th>
                                        <th class="px-3 py-2 text-left font-medium text-gray-700">Action</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">';
                        
                        foreach ($stock_items as $stock) {
                            // Status badge
                            $status_badge = '';
                            switch ($stock['status']) {
                                case 'Tersedia':
                                    $status_badge = '<span class="px-2 py-1 bg-green-100 text-green-800 text-xs font-medium rounded-full">' . $stock['status'] . '</span>';
                                    break;
                                case 'Dipinjam':
                                    $status_badge = '<span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs font-medium rounded-full">' . $stock['status'] . '</span>';
                                    break;
                                case 'Rusak':
                                    $status_badge = '<span class="px-2 py-1 bg-red-100 text-red-800 text-xs font-medium rounded-full">' . $stock['status'] . '</span>';
                                    break;
                                case 'Expired':
                                    $status_badge = '<span class="px-2 py-1 bg-yellow-100 text-yellow-800 text-xs font-medium rounded-full">' . $stock['status'] . '</span>';
                                    break;
                                default:
                                    $status_badge = '<span class="px-2 py-1 bg-gray-100 text-gray-800 text-xs font-medium rounded-full">' . $stock['status'] . '</span>';
                            }
                            
                            // Delete button (only for Tersedia status)
                            $delete_button = '';
                            if ($stock['status'] == 'Tersedia') {
                                $delete_button = '<button onclick="deleteStockItem(' . $stock['id'] . ', \'' . htmlspecialchars($stock['kode_barang']) . '\')" 
                                                         class="px-2 py-1 bg-red-600 text-white text-xs rounded hover:bg-red-700 transition-colors">
                                                    <i class="fas fa-trash"></i>
                                                  </button>';
                            } else {
                                $delete_button = '<span class="text-gray-400 text-xs">Tidak bisa dihapus</span>';
                            }
                            
                            $html .= '
                            <tr>
                                <td class="px-3 py-2 text-gray-900">' . htmlspecialchars($stock['kode_barang']) . '</td>
                                <td class="px-3 py-2 text-gray-900">' . $stock['stock_number'] . '</td>
                                <td class="px-3 py-2">' . $status_badge . '</td>
                                <td class="px-3 py-2 text-gray-900">' . htmlspecialchars($stock['lokasi']) . '</td>
                                <td class="px-3 py-2 text-gray-900">' . htmlspecialchars($stock['rack_no'] ?? '-') . '</td>
                                <td class="px-3 py-2 text-gray-900">' . ($stock['tanggal_pembuatan'] ? date('d/m/Y', strtotime($stock['tanggal_pembuatan'])) : '-') . '</td>
                                <td class="px-3 py-2 text-gray-900">' . ($stock['tanggal_kedaluwarsa'] ? date('d/m/Y', strtotime($stock['tanggal_kedaluwarsa'])) : '-') . '</td>
                                <td class="px-3 py-2">' . $delete_button . '</td>
                            </tr>';
                        }
                        
                        $html .= '
                                </tbody>
                            </table>
                        </div>';
                    }
                    
                    $html .= '</div>';
                }
                
                $html .= '</div>';
            }
            
            $html .= '
                </div>
            </div>';
        }
    }
    
    echo json_encode([
        'success' => true,
        'html' => $html
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}