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

// Function to get color codes with their details
function getColorCodes($conn) {
    $sql = "SELECT DISTINCT 
                mcp.id,
                mcp.code_color,
                mcp.deskripsi,
                b.nama_buyer,
                b.kode_buyer,
                mcp.lemari,
                mcp.status,
                COUNT(csi.id) as total_items
            FROM master_color_panel_surabaya mcp
            LEFT JOIN buyers_surabaya b ON mcp.buyer_id = b.id
            LEFT JOIN color_stock_items_surabaya csi ON mcp.id = csi.color_id
            GROUP BY mcp.id
            ORDER BY mcp.code_color";
    
    $result = $conn->query($sql);
    return $result->fetch_all(MYSQLI_ASSOC);
}

// Function to get stock items by color
function getStockItemsByColor($conn, $color_id) {
    $sql = "SELECT 
                csi.*,
                cc.component_name,
                mcp.code_color,
                b.nama_buyer,
                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
            FROM color_stock_items_surabaya csi
            JOIN color_components_surabaya cc ON csi.component_id = cc.id
            JOIN master_color_panel_surabaya mcp ON csi.color_id = mcp.id
            JOIN buyers_surabaya b ON mcp.buyer_id = b.id
            WHERE csi.color_id = ?
            ORDER BY csi.kode_barang";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $color_id);
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

// Function to get all stock items for search
function getAllStockItems($conn) {
    $sql = "SELECT 
                csi.*,
                cc.component_name,
                mcp.code_color,
                mcp.id as color_panel_id,
                b.nama_buyer,
                b.kode_buyer,
                mcp.lemari,
                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
            FROM color_stock_items_surabaya csi
            JOIN color_components_surabaya cc ON csi.component_id = cc.id
            JOIN master_color_panel_surabaya mcp ON csi.color_id = mcp.id
            JOIN buyers_surabaya b ON mcp.buyer_id = b.id
            ORDER BY mcp.code_color, csi.kode_barang";
    
    $result = $conn->query($sql);
    return $result->fetch_all(MYSQLI_ASSOC);
}

// Function to get borrowed item details
function getBorrowedItemDetails($conn, $kode_barang) {
    $sql = "SELECT 
                csi.*,
                cc.component_name,
                mcp.code_color,
                b.nama_buyer,
                bu.nama_borrower,
                bu.lokasi_posisi,
                st.reservation_number,
                st.tanggal_transaksi,
                st.tanggal_pengembalian,
                ti.lokasi_tujuan,
                ti.status_waktu,
                ti.catatan
            FROM color_stock_items_surabaya csi
            JOIN color_components_surabaya cc ON csi.component_id = cc.id
            JOIN master_color_panel_surabaya mcp ON csi.color_id = mcp.id
            JOIN buyers_surabaya b ON mcp.buyer_id = b.id
            JOIN transaction_items_surabaya ti ON csi.id = ti.stock_item_id
            JOIN stock_transactions_surabaya st ON ti.transaction_id = st.id
            JOIN borrower_users_surabaya bu ON st.borrower_id = bu.id
            WHERE csi.kode_barang = ? AND ti.dikembalikan = 0
            ORDER BY ti.id DESC LIMIT 1";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $kode_barang);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

// Function to get ongoing transactions
function getOngoingTransactions($conn) {
    $sql = "SELECT DISTINCT 
                st.reservation_number,
                st.tanggal_transaksi,
                st.tanggal_pengembalian,
                bu.nama_borrower,
                COUNT(ti.id) as total_items
            FROM stock_transactions_surabaya st
            JOIN borrower_users_surabaya bu ON st.borrower_id = bu.id
            JOIN transaction_items_surabaya ti ON st.id = ti.transaction_id
            JOIN color_stock_items_surabaya csi ON ti.stock_item_id = csi.id
            WHERE ti.dikembalikan = 0 AND csi.status = 'Dipinjam'
            GROUP BY st.id
            ORDER BY st.tanggal_transaksi DESC";
    
    $result = $conn->query($sql);
    return $result->fetch_all(MYSQLI_ASSOC);
}

// Function to get total borrowed items
function getTotalBorrowedItems($conn) {
    $sql = "SELECT COUNT(*) as total
            FROM color_stock_items_surabaya csi
            JOIN transaction_items_surabaya ti ON csi.id = ti.stock_item_id
            WHERE csi.status = 'Dipinjam' AND ti.dikembalikan = 0";
    
    $result = $conn->query($sql);
    return $result->fetch_assoc()['total'];
}

// Function to get overdue transactions
function getOverdueTransactions($conn) {
    $sql = "SELECT DISTINCT 
                st.reservation_number,
                st.tanggal_pengembalian,
                bu.nama_borrower,
                COUNT(ti.id) as total_items,
                TIMESTAMPDIFF(MINUTE, DATE_ADD(st.tanggal_pengembalian, INTERVAL 15 MINUTE), NOW()) as minutes_overdue
            FROM stock_transactions_surabaya st
            JOIN borrower_users_surabaya bu ON st.borrower_id = bu.id
            JOIN transaction_items_surabaya ti ON st.id = ti.transaction_id
            JOIN color_stock_items_surabaya csi ON ti.stock_item_id = csi.id
            WHERE ti.dikembalikan = 0 
            AND csi.status = 'Dipinjam'
            AND NOW() > DATE_ADD(st.tanggal_pengembalian, INTERVAL 15 MINUTE)
            GROUP BY st.id
            ORDER BY st.tanggal_pengembalian ASC";
    
    $result = $conn->query($sql);
    return $result->fetch_all(MYSQLI_ASSOC);
}

// Function to get buyers_surabaya for filter
function getbuyers_surabaya($conn) {
    $sql = "SELECT * FROM buyers_surabaya ORDER BY nama_buyer";
    $result = $conn->query($sql);
    return $result->fetch_all(MYSQLI_ASSOC);
}

// Function to get components for filter
function getComponents($conn) {
    $sql = "SELECT * FROM color_components_surabaya ORDER BY component_name";
    $result = $conn->query($sql);
    return $result->fetch_all(MYSQLI_ASSOC);
}

// Get data
$colorCodes = getColorCodes($conn);
$allStockItems = getAllStockItems($conn);
$ongoingTransactions = getOngoingTransactions($conn);
$totalBorrowedItems = getTotalBorrowedItems($conn);
$overdueTransactions = getOverdueTransactions($conn);
$buyers_surabaya = getbuyers_surabaya($conn);
$components = getComponents($conn);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Color Room Monitor</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .highlight-search {
            background-color: #fef08a !important;
            color: #000 !important;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        .modal.show {
            display: block;
        }
        .modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            padding: 20px;
            border-radius: 10px;
            width: 90%;
            max-width: 600px;
            max-height: 80vh;
            overflow-y: auto;
        }
        .status-dipinjam {
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .status-dipinjam:hover {
            transform: scale(1.05);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <!-- Header -->
    <header class="bg-green-600 text-white shadow-lg">
        <div class="container mx-auto px-4 py-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-4">
                    <img src="images/logo.png" alt="Logo" class="h-12 w-auto">
                    <div>
                        <h1 class="text-2xl font-bold">Color Room Monitor</h1>
                        <p class="text-green-100">Real-time Stock Monitoring System</p>
                    </div>
                </div>
                <div class="text-right">
                    <div class="text-sm text-green-100">Last Update</div>
                    <div class="text-lg font-semibold" id="currentTime"></div>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="container mx-auto px-4 py-6">
        <!-- Search Bar -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <div class="flex flex-col md:flex-row gap-4">
                <div class="flex-1">
                    <label class="block text-gray-700 text-sm font-bold mb-2">
                        <i class="fas fa-search mr-2"></i>Search by Code Barang or Color Code
                    </label>
                    <input type="text" id="searchInput" placeholder="Type CP.0001 or 483..." 
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500">
                </div>
                <div class="flex gap-2">
                    <button onclick="clearSearch()" class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition duration-300">
                        <i class="fas fa-times mr-2"></i>Clear
                    </button>
                </div>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
            <!-- Total On Going -->
            <div class="bg-white rounded-lg shadow-md p-6 cursor-pointer hover:shadow-lg transition duration-300" onclick="showOngoingModal()">
                <div class="flex items-center justify-between">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-700">Total On Going</h3>
                        <p class="text-3xl font-bold text-blue-600"><?= count($ongoingTransactions) ?></p>
                        <p class="text-sm text-gray-500">Active Reservations</p>
                    </div>
                    <div class="bg-blue-100 p-3 rounded-full">
                        <i class="fas fa-clock text-blue-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <!-- Total Dipinjam -->
            <div class="bg-white rounded-lg shadow-md p-6 cursor-pointer hover:shadow-lg transition duration-300" onclick="showBorrowedModal()">
                <div class="flex items-center justify-between">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-700">Total Dipinjam</h3>
                        <p class="text-3xl font-bold text-orange-600"><?= $totalBorrowedItems ?></p>
                        <p class="text-sm text-gray-500">Borrowed Items</p>
                    </div>
                    <div class="bg-orange-100 p-3 rounded-full">
                        <i class="fas fa-hand-holding text-orange-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <!-- Total Overdue -->
            <div class="bg-white rounded-lg shadow-md p-6 cursor-pointer hover:shadow-lg transition duration-300" onclick="showOverdueModal()">
                <div class="flex items-center justify-between">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-700">Total Overdue</h3>
                        <p class="text-3xl font-bold text-red-600"><?= count($overdueTransactions) ?></p>
                        <p class="text-sm text-gray-500">Overdue Items</p>
                    </div>
                    <div class="bg-red-100 p-3 rounded-full">
                        <i class="fas fa-exclamation-triangle text-red-600 text-2xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <h3 class="text-lg font-semibold text-gray-700 mb-4">
                <i class="fas fa-filter mr-2"></i>Filters
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Buyer</label>
                    <select id="buyerFilter" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500">
                        <option value="">All buyers_surabaya</option>
                        <?php foreach ($buyers_surabaya as $buyer): ?>
                            <option value="<?= $buyer['id'] ?>"><?= $buyer['nama_buyer'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Color Code</label>
                    <select id="colorFilter" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500">
                        <option value="">All Colors</option>
                    </select>
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Component</label>
                    <select id="componentFilter" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500">
                        <option value="">All Components</option>
                        <?php foreach ($components as $component): ?>
                            <option value="<?= $component['id'] ?>"><?= $component['component_name'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">Status</label>
                    <select id="statusFilter" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-green-500">
                        <option value="">All Status</option>
                        <option value="Tersedia">Tersedia</option>
                        <option value="Dipinjam">Dipinjam</option>
                        <option value="Rusak">Rusak</option>
                        <option value="Expired">Expired</option>
                        <option value="Hilang">Hilang</option>
                    </select>
                </div>
            </div>
            <div class="mt-4">
                <button onclick="applyFilters()" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition duration-300">
                    <i class="fas fa-filter mr-2"></i>Apply Filters
                </button>
                <button onclick="clearFilters()" class="px-6 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition duration-300 ml-2">
                    <i class="fas fa-times mr-2"></i>Clear Filters
                </button>
            </div>
        </div>

        <!-- Color Codes Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6" id="colorGrid">
            <?php foreach ($colorCodes as $color): ?>
                <div class="bg-white rounded-lg shadow-md p-6 cursor-pointer hover:shadow-lg transition duration-300 color-card" 
                     data-color-id="<?= $color['id'] ?>"
                     data-buyer-id="<?= $color['kode_buyer'] ?>"
                     onclick="showColorDetails(<?= $color['id'] ?>, '<?= $color['code_color'] ?>')">
                    <div class="flex items-center justify-between mb-4">
                        <div class="text-2xl font-bold text-green-600"><?= $color['code_color'] ?></div>
                        <div class="bg-green-100 px-2 py-1 rounded text-xs font-semibold text-green-800">
                            Rack <?= $color['lemari'] ?>
                        </div>
                    </div>
                    <div class="text-gray-600 mb-2"><?= $color['deskripsi'] ?></div>
                    <div class="flex items-center justify-between">
                        <div class="text-sm text-gray-500"><?= $color['nama_buyer'] ?></div>
                        <div class="bg-gray-100 px-2 py-1 rounded text-xs">
                            <?= $color['total_items'] ?> items
                        </div>
                    </div>
                    <div class="mt-2">
                        <span class="inline-block px-2 py-1 rounded text-xs font-semibold 
                            <?= $color['status'] == 'Hijau' ? 'bg-green-100 text-green-800' : 
                                ($color['status'] == 'Kuning' ? 'bg-yellow-100 text-yellow-800' : 'bg-red-100 text-red-800') ?>">
                            <?= $color['status'] ?>
                        </span>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Modals -->
    <!-- Color Details Modal -->
    <div id="colorDetailsModal" class="modal">
        <div class="modal-content">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-gray-800" id="colorModalTitle"></h2>
                <span class="close cursor-pointer text-gray-500 hover:text-gray-700 text-2xl" onclick="closeModal('colorDetailsModal')">&times;</span>
            </div>
            <div id="colorModalContent"></div>
        </div>
    </div>

    <!-- Borrowed Item Details Modal -->
    <div id="borrowedDetailsModal" class="modal">
        <div class="modal-content">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-gray-800">Borrowed Item Details</h2>
                <span class="close cursor-pointer text-gray-500 hover:text-gray-700 text-2xl" onclick="closeModal('borrowedDetailsModal')">&times;</span>
            </div>
            <div id="borrowedModalContent"></div>
        </div>
    </div>

    <!-- Ongoing Transactions Modal -->
    <div id="ongoingModal" class="modal">
        <div class="modal-content">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-gray-800">Ongoing Transactions</h2>
                <span class="close cursor-pointer text-gray-500 hover:text-gray-700 text-2xl" onclick="closeModal('ongoingModal')">&times;</span>
            </div>
            <div class="max-h-96 overflow-y-auto">
                <?php foreach ($ongoingTransactions as $transaction): ?>
                    <div class="border-b border-gray-200 pb-3 mb-3">
                        <div class="flex justify-between items-center">
                            <div>
                                <div class="font-semibold text-blue-600"><?= $transaction['reservation_number'] ?></div>
                                <div class="text-sm text-gray-600"><?= $transaction['nama_borrower'] ?></div>
                                <div class="text-xs text-gray-500">
                                    Due: <?= date('d/m/Y H:i', strtotime($transaction['tanggal_pengembalian'])) ?>
                                </div>
                            </div>
                            <div class="bg-blue-100 px-2 py-1 rounded text-xs font-semibold text-blue-800">
                                <?= $transaction['total_items'] ?> items
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Borrowed Items Modal -->
    <div id="borrowedModal" class="modal">
        <div class="modal-content">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-gray-800">Borrowed Items</h2>
                <span class="close cursor-pointer text-gray-500 hover:text-gray-700 text-2xl" onclick="closeModal('borrowedModal')">&times;</span>
            </div>
            <div id="borrowedItemsList"></div>
        </div>
    </div>

    <!-- Overdue Modal -->
    <div id="overdueModal" class="modal">
        <div class="modal-content">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-gray-800">Overdue Transactions</h2>
                <span class="close cursor-pointer text-gray-500 hover:text-gray-700 text-2xl" onclick="closeModal('overdueModal')">&times;</span>
            </div>
            <div class="max-h-96 overflow-y-auto">
                <?php foreach ($overdueTransactions as $transaction): ?>
                    <div class="border-b border-gray-200 pb-3 mb-3">
                        <div class="flex justify-between items-center">
                            <div>
                                <div class="font-semibold text-red-600"><?= $transaction['reservation_number'] ?></div>
                                <div class="text-sm text-gray-600"><?= $transaction['nama_borrower'] ?></div>
                                <div class="text-xs text-red-500">
                                    Overdue by <?= $transaction['minutes_overdue'] ?> minutes
                                </div>
                                <div class="text-xs text-gray-500">
                                    Due: <?= date('d/m/Y H:i', strtotime($transaction['tanggal_pengembalian'])) ?>
                                </div>
                            </div>
                            <div class="bg-red-100 px-2 py-1 rounded text-xs font-semibold text-red-800">
                                <?= $transaction['total_items'] ?> items
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <script>
        // Store all stock items data
        const allStockItems = <?= json_encode($allStockItems) ?>;
        const colorCodes = <?= json_encode($colorCodes) ?>;
        
        // Update current time
        function updateTime() {
            const now = new Date();
            document.getElementById('currentTime').textContent = now.toLocaleString('id-ID');
        }
        setInterval(updateTime, 1000);
        updateTime();

        // Search functionality
        document.getElementById('searchInput').addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase().trim();
            
            if (searchTerm === '') {
                showAllColors();
                return;
            }

            // Search by kode_barang or color_code
            const matchedItems = allStockItems.filter(item => 
                item.kode_barang.toLowerCase().includes(searchTerm) ||
                item.code_color.toLowerCase().includes(searchTerm)
            );

            if (matchedItems.length > 0) {
                if (matchedItems[0].kode_barang.toLowerCase() === searchTerm) {
                    // Exact match for kode_barang - show only this item
                    showSingleItem(matchedItems[0]);
                } else if (matchedItems[0].code_color.toLowerCase() === searchTerm) {
                    // Exact match for color_code - show color panel
                    showColorWithHighlight(matchedItems[0].color_panel_id, searchTerm);
                } else {
                    // Partial match - filter results
                    filterResults(matchedItems);
                }
            } else {
                hideAllColors();
            }
        });

        function showAllColors() {
            document.querySelectorAll('.color-card').forEach(card => {
                card.style.display = 'block';
                card.classList.remove('highlight-search');
            });
        }

        function hideAllColors() {
            document.querySelectorAll('.color-card').forEach(card => {
                card.style.display = 'none';
            });
        }

        function showColorWithHighlight(colorId, searchTerm) {
            hideAllColors();
            const targetCard = document.querySelector(`[data-color-id="${colorId}"]`);
            if (targetCard) {
                targetCard.style.display = 'block';
                targetCard.classList.add('highlight-search');
                targetCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        }

        function showSingleItem(item) {
            hideAllColors();
            // Show the color panel that contains this item
            const targetCard = document.querySelector(`[data-color-id="${item.color_panel_id}"]`);
            if (targetCard) {
                targetCard.style.display = 'block';
                targetCard.classList.add('highlight-search');
                targetCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
                
                // Automatically open the color details to show the specific item
                setTimeout(() => {
                    showColorDetails(item.color_panel_id, item.code_color, item.kode_barang);
                }, 500);
            }
        }

        function filterResults(matchedItems) {
            hideAllColors();
            const uniqueColorIds = [...new Set(matchedItems.map(item => item.color_panel_id))];
            
            uniqueColorIds.forEach(colorId => {
                const targetCard = document.querySelector(`[data-color-id="${colorId}"]`);
                if (targetCard) {
                    targetCard.style.display = 'block';
                    targetCard.classList.add('highlight-search');
                }
            });
        }

        function clearSearch() {
            document.getElementById('searchInput').value = '';
            showAllColors();
        }

        // Modal functions
        function showModal(modalId) {
            document.getElementById(modalId).classList.add('show');
        }

        function closeModal(modalId) {
            document.getElementById(modalId).classList.remove('show');
        }

        // Color details modal
        function showColorDetails(colorId, colorCode, highlightItem = null) {
            showModal('colorDetailsModal');
            document.getElementById('colorModalTitle').textContent = `Color Code: ${colorCode}`;
            
            // Load color details via AJAX
            fetch('color_details.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `color_id=${colorId}&highlight_item=${highlightItem || ''}`
            })
            .then(response => response.text())
            .then(data => {
                document.getElementById('colorModalContent').innerHTML = data;
            });
        }

        // Borrowed item details modal
        function showBorrowedDetails(kodeBarang) {
            showModal('borrowedDetailsModal');
            
            // Load borrowed details via AJAX
            fetch('borrowed_details.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `kode_barang=${kodeBarang}`
            })
            .then(response => response.text())
            .then(data => {
                document.getElementById('borrowedModalContent').innerHTML = data;
            });
        }

        // Statistics modals
        function showOngoingModal() {
            showModal('ongoingModal');
        }

        function showBorrowedModal() {
            showModal('borrowedModal');
            
            // Load borrowed items list
            const borrowedItems = allStockItems.filter(item => item.status === 'Dipinjam');
            let html = '<div class="max-h-96 overflow-y-auto">';
            
            borrowedItems.forEach(item => {
                html += `
                    <div class="border-b border-gray-200 pb-3 mb-3 cursor-pointer hover:bg-gray-50 p-2 rounded" 
                         onclick="showBorrowedDetails('${item.kode_barang}')">
                        <div class="flex justify-between items-center">
                            <div>
                                <div class="font-semibold text-orange-600">${item.kode_barang}</div>
                                <div class="text-sm text-gray-600">${item.code_color} - ${item.component_name}</div>
                                <div class="text-xs text-gray-500">Rack: ${item.rack_no || 'N/A'}</div>
                                ${item.reservation_number ? `<div class="text-xs text-blue-500">Reservation: ${item.reservation_number}</div>` : ''}
                            </div>
                            <div class="bg-orange-100 px-2 py-1 rounded text-xs font-semibold text-orange-800">
                                Dipinjam
                            </div>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            document.getElementById('borrowedItemsList').innerHTML = html;
        }

        function showOverdueModal() {
            showModal('overdueModal');
        }

        // Filter functions
        function applyFilters() {
            const buyerId = document.getElementById('buyerFilter').value;
            const colorId = document.getElementById('colorFilter').value;
            const componentId = document.getElementById('componentFilter').value;
            const status = document.getElementById('statusFilter').value;

            console.log('Applying filters:', { buyerId, colorId, componentId, status });
            // Implementation will be in the next part
        }

        function clearFilters() {
            document.getElementById('buyerFilter').value = '';
            document.getElementById('colorFilter').value = '';
            document.getElementById('componentFilter').value = '';
            document.getElementById('statusFilter').value = '';
            showAllColors();
        }

        // Close modals when clicking outside
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.classList.remove('show');
            }
        }

        // Initialize filters
        document.getElementById('buyerFilter').addEventListener('change', function() {
            const buyerId = this.value;
            const colorFilter = document.getElementById('colorFilter');
            
            // Clear color filter
            colorFilter.innerHTML = '<option value="">All Colors</option>';
            
            if (buyerId) {
                // Filter colors by buyer
                const filteredColors = colorCodes.filter(color => color.kode_buyer == buyerId);
                filteredColors.forEach(color => {
                    colorFilter.innerHTML += `<option value="${color.id}">${color.code_color}</option>`;
                });
            } else {
                // Show all colors
                colorCodes.forEach(color => {
                    colorFilter.innerHTML += `<option value="${color.id}">${color.code_color}</option>`;
                });
            }
        });

        // Initialize color filter with all colors
        document.addEventListener('DOMContentLoaded', function() {
            const colorFilter = document.getElementById('colorFilter');
            colorCodes.forEach(color => {
                colorFilter.innerHTML += `<option value="${color.id}">${color.code_color}</option>`;
            });
        });
    </script>
</body>
</html>