<?php
require_once "config/connection.php";

if (!isset($_POST['color_id'])) {
    echo "Invalid request";
    exit;
}

$color_id = intval($_POST['color_id']);
$highlight_item = $_POST['highlight_item'] ?? '';

// Get color panel information
$sql = "SELECT 
            mcp.*,
            b.nama_buyer,
            b.kode_buyer,
            c.nama_collection_surabaya
        FROM master_color_panel_surabaya mcp
        JOIN buyers_surabaya b ON mcp.buyer_id = b.id
        JOIN collection_surabayas c ON mcp.collection_surabaya_id = c.id
        WHERE mcp.id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $color_id);
$stmt->execute();
$colorInfo = $stmt->get_result()->fetch_assoc();

if (!$colorInfo) {
    echo "Color not found";
    exit;
}

// Get stock items for this color
$sql = "SELECT 
            csi.*,
            cc.component_name,
            CASE 
                WHEN csi.status = 'Dipinjam' THEN 
                    (SELECT st.reservation_number 
                     FROM transaction_items_surabaya ti 
                     JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id 
                     WHERE ti.stock_item_id = csi.id 
                     AND ti.dikembalikan = 0 
                     ORDER BY ti.id DESC LIMIT 1)
                ELSE NULL
            END as reservation_number,
            CASE 
                WHEN csi.status = 'Dipinjam' THEN 
                    (SELECT bu.nama_borrower 
                     FROM transaction_items_surabaya ti 
                     JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id 
                     JOIN borrower_users_surabaya bu ON st.borrower_id = bu.id
                     WHERE ti.stock_item_id = csi.id 
                     AND ti.dikembalikan = 0 
                     ORDER BY ti.id DESC LIMIT 1)
                ELSE NULL
            END as borrower_name,
            CASE 
                WHEN csi.status = 'Dipinjam' THEN 
                    (SELECT st.tanggal_pengembalian 
                     FROM transaction_items_surabaya ti 
                     JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id 
                     WHERE ti.stock_item_id = csi.id 
                     AND ti.dikembalikan = 0 
                     ORDER BY ti.id DESC LIMIT 1)
                ELSE NULL
            END as due_date,
            CASE 
                WHEN csi.status = 'Dipinjam' THEN 
                    (SELECT ti.status_waktu 
                     FROM transaction_items_surabaya ti 
                     JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id 
                     WHERE ti.stock_item_id = csi.id 
                     AND ti.dikembalikan = 0 
                     ORDER BY ti.id DESC LIMIT 1)
                ELSE NULL
            END as time_status
        FROM color_stock_items_surabaya csi
        JOIN color_components_surabaya cc ON csi.component_id = cc.id
        WHERE csi.color_id = ?
        ORDER BY cc.component_name, csi.stock_number";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $color_id);
$stmt->execute();
$stockItems = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Group items by component
$groupedItems = [];
foreach ($stockItems as $item) {
    $groupedItems[$item['component_name']][] = $item;
}

function getStatusBadgeClass($status) {
    switch ($status) {
        case 'Tersedia':
            return 'bg-green-100 text-green-800';
        case 'Dipinjam':
            return 'bg-orange-100 text-orange-800';
        case 'Rusak':
            return 'bg-red-100 text-red-800';
        case 'Expired':
            return 'bg-purple-100 text-purple-800';
        case 'Hilang':
            return 'bg-gray-100 text-gray-800';
        default:
            return 'bg-gray-100 text-gray-800';
    }
}

function getTimeStatusBadge($timeStatus, $dueDate) {
    if ($timeStatus === 'overdue') {
        return '<span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-red-100 text-red-800 ml-2">OVERDUE</span>';
    } elseif ($timeStatus === 'tepat') {
        return '<span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-green-100 text-green-800 ml-2">ON TIME</span>';
    } elseif ($dueDate) {
        // Check if currently overdue
        $now = new DateTime();
        $due = new DateTime($dueDate);
        $due->add(new DateInterval('PT15M')); // Add 15 minutes tolerance
        
        if ($now > $due) {
            return '<span class="inline-block px-2 py-1 rounded text-xs font-semibold bg-red-100 text-red-800 ml-2">OVERDUE</span>';
        }
    }
    return '';
}
?>

<!-- Color Panel Information -->
<div class="bg-gray-50 rounded-lg p-4 mb-6">
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
            <h3 class="text-lg font-semibold text-gray-800 mb-2">Color Information</h3>
            <div class="space-y-2 text-sm">
                <div><span class="font-medium">Code:</span> <?= htmlspecialchars($colorInfo['code_color']) ?></div>
                <div><span class="font-medium">Description:</span> <?= htmlspecialchars($colorInfo['deskripsi']) ?></div>
                <div><span class="font-medium">Buyer:</span> <?= htmlspecialchars($colorInfo['nama_buyer']) ?> (<?= htmlspecialchars($colorInfo['kode_buyer']) ?>)</div>
                <div><span class="font-medium">collection_surabaya:</span> <?= htmlspecialchars($colorInfo['nama_collection_surabaya']) ?></div>
            </div>
        </div>
        <div>
            <h3 class="text-lg font-semibold text-gray-800 mb-2">Physical Location</h3>
            <div class="space-y-2 text-sm">
                <div><span class="font-medium">Rack:</span> <?= htmlspecialchars($colorInfo['lemari']) ?></div>
                <div><span class="font-medium">Status:</span> 
                    <span class="inline-block px-2 py-1 rounded text-xs font-semibold 
                        <?= $colorInfo['status'] == 'Hijau' ? 'bg-green-100 text-green-800' : 
                            ($colorInfo['status'] == 'Kuning' ? 'bg-yellow-100 text-yellow-800' : 'bg-red-100 text-red-800') ?>">
                        <?= htmlspecialchars($colorInfo['status']) ?>
                    </span>
                </div>
                <div><span class="font-medium">Total Items:</span> <?= count($stockItems) ?></div>
            </div>
        </div>
    </div>
</div>

<!-- Stock Items by Component -->
<div class="space-y-4">
    <?php foreach ($groupedItems as $componentName => $items): ?>
        <div class="border border-gray-200 rounded-lg">
            <div class="bg-gray-100 px-4 py-3 border-b border-gray-200">
                <h4 class="font-semibold text-gray-800">
                    <?= htmlspecialchars($componentName) ?>
                    <span class="text-sm font-normal text-gray-600">(<?= count($items) ?> items)</span>
                </h4>
            </div>
            <div class="p-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <?php foreach ($items as $item): ?>
                        <?php 
                        $isHighlighted = ($highlight_item && $item['kode_barang'] === $highlight_item);
                        $cardClass = $isHighlighted ? 'border-yellow-400 bg-yellow-50' : 'border-gray-200';
                        $clickable = $item['status'] === 'Dipinjam' ? 'cursor-pointer hover:shadow-md' : '';
                        $onclick = $item['status'] === 'Dipinjam' ? "onclick=\"showBorrowedDetails('{$item['kode_barang']}')\"" : '';
                        ?>
                        <div class="border-2 <?= $cardClass ?> rounded-lg p-3 transition duration-200 <?= $clickable ?>" <?= $onclick ?>>
                            <div class="flex justify-between items-start mb-2">
                                <div class="font-semibold text-gray-800"><?= htmlspecialchars($item['kode_barang']) ?></div>
                                <span class="inline-block px-2 py-1 rounded text-xs font-semibold <?= getStatusBadgeClass($item['status']) ?>">
                                    <?= htmlspecialchars($item['status']) ?>
                                </span>
                            </div>
                            
                            <div class="text-sm text-gray-600 space-y-1">
                                <div><span class="font-medium">Stock #:</span> <?= $item['stock_number'] ?></div>
                                <div><span class="font-medium">Rack:</span> <?= htmlspecialchars($item['rack_no'] ?? 'N/A') ?></div>
                                <div><span class="font-medium">Location:</span> <?= htmlspecialchars($item['lokasi']) ?></div>
                                
                                <?php if ($item['tanggal_pembuatan']): ?>
                                    <div><span class="font-medium">Made:</span> <?= date('d/m/Y', strtotime($item['tanggal_pembuatan'])) ?></div>
                                <?php endif; ?>
                                
                                <?php if ($item['tanggal_kedaluwarsa']): ?>
                                    <div><span class="font-medium">Expires:</span> <?= date('d/m/Y', strtotime($item['tanggal_kedaluwarsa'])) ?></div>
                                <?php endif; ?>
                                
                                <?php if ($item['status'] === 'Dipinjam'): ?>
                                    <div class="border-t border-gray-200 pt-2 mt-2">
                                        <?php if ($item['borrower_name']): ?>
                                            <div><span class="font-medium">Borrower:</span> <?= htmlspecialchars($item['borrower_name']) ?></div>
                                        <?php endif; ?>
                                        
                                        <?php if ($item['reservation_number']): ?>
                                            <div><span class="font-medium">Reservation:</span> <?= htmlspecialchars($item['reservation_number']) ?></div>
                                        <?php endif; ?>
                                        
                                        <?php if ($item['due_date']): ?>
                                            <div class="flex items-center">
                                                <span class="font-medium">Due:</span> 
                                                <span class="ml-1"><?= date('d/m/Y H:i', strtotime($item['due_date'])) ?></span>
                                                <?= getTimeStatusBadge($item['time_status'], $item['due_date']) ?>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <div class="text-xs text-blue-600 mt-1">
                                            <i class="fas fa-info-circle mr-1"></i>Click for more details
                                        </div>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($item['keterangan']): ?>
                                    <div class="text-xs text-gray-500 italic">
                                        <?= htmlspecialchars($item['keterangan']) ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<?php if (empty($groupedItems)): ?>
    <div class="text-center py-8">
        <div class="text-gray-500">
            <i class="fas fa-box-open text-4xl mb-4"></i>
            <p class="text-lg">No items found for this color code</p>
        </div>
    </div>
<?php endif; ?>

<script>
// Function to show borrowed details (this will call the main page function)
function showBorrowedDetails(kodeBarang) {
    // Close current modal
    parent.closeModal('colorDetailsModal');
    // Show borrowed details modal
    setTimeout(() => {
        parent.showBorrowedDetails(kodeBarang);
    }, 300);
}
</script>

<style>
.highlight-item {
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0%, 100% {
        opacity: 1;
    }
    50% {
        opacity: 0.7;
    }
}
</style>