<?php
// No authentication required - Public dashboard for monitoring
require_once "config/connection.php";

// Set timezone
date_default_timezone_set('Asia/Jakarta');

// Set page title
$page_title = "Dashboard Monitoring Peminjaman Color";

// Get current datetime
$current_datetime = new DateTime('now', new DateTimeZone('Asia/Jakarta'));

// Get statistics
// 1. Total items yang pernah dipinjam (hanya Copy Panel)
$total_pernah_dipinjam_stmt = $conn->prepare("
    SELECT COUNT(*) as total 
    FROM color_stock_items 
    WHERE pernah_dipinjam = 1 
    AND item_type = 'copy_panel'
");
$total_pernah_dipinjam_stmt->execute();
$total_pernah_dipinjam = $total_pernah_dipinjam_stmt->get_result()->fetch_assoc()['total'];
$total_pernah_dipinjam_stmt->close();

// 2. Total sedang dipinjam (hanya Copy Panel)
$total_sedang_dipinjam_stmt = $conn->prepare("
    SELECT COUNT(*) as total 
    FROM color_stock_items 
    WHERE status = 'Dipinjam' 
    AND item_type = 'copy_panel'
");
$total_sedang_dipinjam_stmt->execute();
$total_sedang_dipinjam = $total_sedang_dipinjam_stmt->get_result()->fetch_assoc()['total'];
$total_sedang_dipinjam_stmt->close();

// 3. Total dalam masa kritis (sisa < 10 hari dari kedaluwarsa) - Copy Panel only
$critical_items_stmt = $conn->prepare("
    SELECT COUNT(*) as total 
    FROM color_stock_items 
    WHERE pernah_dipinjam = 1 
    AND item_type = 'copy_panel'
    AND DATEDIFF(tanggal_kedaluwarsa, NOW()) <= 10
    AND DATEDIFF(tanggal_kedaluwarsa, NOW()) >= 0
");
$critical_items_stmt->execute();
$total_critical = $critical_items_stmt->get_result()->fetch_assoc()['total'];
$critical_items_stmt->close();

// 4. Total sudah expired (Copy Panel only)
$expired_items_stmt = $conn->prepare("
    SELECT COUNT(*) as total 
    FROM color_stock_items 
    WHERE pernah_dipinjam = 1 
    AND item_type = 'copy_panel'
    AND tanggal_kedaluwarsa < NOW()
");
$expired_items_stmt->execute();
$total_expired = $expired_items_stmt->get_result()->fetch_assoc()['total'];
$expired_items_stmt->close();

// 5. Total aman (masih > 10 hari)
$total_aman = $total_pernah_dipinjam - $total_critical - $total_expired;

// Get total master colors for reference
$total_master_colors_stmt = $conn->prepare("SELECT COUNT(*) as total FROM master_color");
$total_master_colors_stmt->execute();
$total_master_colors = $total_master_colors_stmt->get_result()->fetch_assoc()['total'];
$total_master_colors_stmt->close();

// Get total panels
$total_panels_stmt = $conn->prepare("SELECT COUNT(*) as total FROM master_color_panel");
$total_panels_stmt->execute();
$total_panels = $total_panels_stmt->get_result()->fetch_assoc()['total'];
$total_panels_stmt->close();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
        
        .animate-fade-in {
            animation: fadeIn 0.5s ease-in;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .glass-effect {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }
        
        .gradient-bg {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .status-indicator {
            animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: .5; }
        }
        
        /* Tab Styles */
        .tab-btn {
            transition: all 0.3s ease;
        }
        
        .tab-btn.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
            animation: fadeIn 0.4s ease-in;
        }
        
        /* Custom Scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 10px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: #555;
        }
    </style>
</head>
<body class="bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 min-h-screen">
    
    <!-- Header -->
    <header class="gradient-bg text-white shadow-2xl sticky top-0 z-50">
        <div class="container mx-auto px-4 py-6">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-4">
                    <div class="bg-white bg-opacity-20 p-3 rounded-full backdrop-blur-sm">
                        <i class="fas fa-chart-line text-3xl"></i>
                    </div>
                    <div>
                        <h1 class="text-3xl font-bold">Dashboard Monitoring</h1>
                        <p class="text-sm text-indigo-100">Peminjaman Copy Panel - Real-time Analytics</p>
                    </div>
                </div>
                <div class="text-right">
                    <p class="text-sm text-indigo-100">Last Update</p>
                    <p class="text-lg font-semibold" id="current-time">
                        <?php echo $current_datetime->format('d M Y, H:i:s'); ?>
                    </p>
                </div>
            </div>
        </div>
    </header>

    <div class="container mx-auto px-4 py-8">
        
        <!-- Info Banner -->
        <div class="glass-effect rounded-2xl shadow-xl p-4 border border-blue-200 mb-6 animate-fade-in">
            <div class="flex items-center space-x-3">
                <i class="fas fa-info-circle text-blue-600 text-2xl"></i>
                <div class="flex-1">
                    <p class="text-sm font-semibold text-gray-800">
                        <span class="text-blue-600">Master Colors:</span> <?php echo $total_master_colors; ?> warna | 
                        <span class="text-green-600">Panels:</span> <?php echo $total_panels; ?> panels | 
                        <span class="text-purple-600">Copy Panels:</span> Hanya copy panel yang dapat dipinjam
                    </p>
                </div>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8 animate-fade-in">
            
            <!-- Total Pernah Dipinjam -->
            <div class="glass-effect rounded-2xl shadow-xl p-6 border border-gray-200 transform hover:scale-105 transition-transform duration-300">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-semibold text-gray-600 uppercase tracking-wide">Copy Panel Dipinjam</p>
                        <h3 class="text-4xl font-bold text-indigo-600 mt-2"><?php echo $total_pernah_dipinjam; ?></h3>
                        <p class="text-xs text-gray-500 mt-1">Total Items</p>
                    </div>
                    <div class="bg-indigo-100 p-4 rounded-full">
                        <i class="fas fa-history text-3xl text-indigo-600"></i>
                    </div>
                </div>
            </div>

            <!-- Sedang Dipinjam -->
            <div class="glass-effect rounded-2xl shadow-xl p-6 border border-gray-200 transform hover:scale-105 transition-transform duration-300">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-semibold text-gray-600 uppercase tracking-wide">Sedang Dipinjam</p>
                        <h3 class="text-4xl font-bold text-blue-600 mt-2"><?php echo $total_sedang_dipinjam; ?></h3>
                        <p class="text-xs text-gray-500 mt-1">Active Items</p>
                    </div>
                    <div class="bg-blue-100 p-4 rounded-full">
                        <i class="fas fa-hand-holding text-3xl text-blue-600"></i>
                    </div>
                </div>
                <div class="mt-3 flex items-center">
                    <div class="status-indicator w-2 h-2 bg-blue-500 rounded-full mr-2"></div>
                    <span class="text-xs text-gray-600">Live Status</span>
                </div>
            </div>

            <!-- Masa Kritis -->
            <div class="glass-effect rounded-2xl shadow-xl p-6 border border-gray-200 transform hover:scale-105 transition-transform duration-300">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-semibold text-gray-600 uppercase tracking-wide">Masa Kritis</p>
                        <h3 class="text-4xl font-bold text-orange-600 mt-2"><?php echo $total_critical; ?></h3>
                        <p class="text-xs text-gray-500 mt-1">≤ 10 Hari</p>
                    </div>
                    <div class="bg-orange-100 p-4 rounded-full">
                        <i class="fas fa-exclamation-triangle text-3xl text-orange-600"></i>
                    </div>
                </div>
                <div class="mt-3">
                    <div class="w-full bg-gray-200 rounded-full h-2">
                        <div class="bg-orange-500 h-2 rounded-full" style="width: <?php echo $total_pernah_dipinjam > 0 ? ($total_critical / $total_pernah_dipinjam * 100) : 0; ?>%"></div>
                    </div>
                </div>
            </div>

            <!-- Expired -->
            <div class="glass-effect rounded-2xl shadow-xl p-6 border border-gray-200 transform hover:scale-105 transition-transform duration-300">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-semibold text-gray-600 uppercase tracking-wide">Sudah Expired</p>
                        <h3 class="text-4xl font-bold text-red-600 mt-2"><?php echo $total_expired; ?></h3>
                        <p class="text-xs text-gray-500 mt-1">Items</p>
                    </div>
                    <div class="bg-red-100 p-4 rounded-full">
                        <i class="fas fa-times-circle text-3xl text-red-600"></i>
                    </div>
                </div>
            </div>

        </div>

        <!-- Tab Navigation -->
        <div class="glass-effect rounded-2xl shadow-xl border border-gray-200 mb-8 animate-fade-in">
            <div class="flex border-b border-gray-200">
                <button onclick="switchTab('table')" id="tab-table" class="tab-btn active flex-1 px-6 py-4 text-sm font-semibold uppercase tracking-wide focus:outline-none">
                    <i class="fas fa-table mr-2"></i>
                    Data Table
                </button>
                <button onclick="switchTab('diagram')" id="tab-diagram" class="tab-btn flex-1 px-6 py-4 text-sm font-semibold text-gray-600 uppercase tracking-wide focus:outline-none">
                    <i class="fas fa-chart-pie mr-2"></i>
                    Diagram
                </button>
            </div>
        </div>

        <!-- Tab Content: Data Table -->
        <div id="content-table" class="tab-content active">
            
            <!-- Filter & Search -->
            <div class="glass-effect rounded-2xl shadow-xl p-6 border border-gray-200 mb-8 animate-fade-in">
                <div class="flex flex-col md:flex-row gap-4 items-end">
                    <div class="flex-1">
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-filter mr-2"></i>Filter Status
                        </label>
                        <select id="filter-status" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500">
                            <option value="all">Semua Status</option>
                            <option value="aman">Aman (> 10 hari)</option>
                            <option value="kritis">Kritis (≤ 10 hari)</option>
                            <option value="expired">Expired</option>
                            <option value="dipinjam">Sedang Dipinjam</option>
                        </select>
                    </div>
                    <div class="flex-1">
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-search mr-2"></i>Cari Kode Barang / Peminjam
                        </label>
                        <input type="text" id="search-input" placeholder="Ketik untuk mencari..." class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500">
                    </div>
                    <div>
                        <button onclick="refreshData()" class="px-6 py-3 bg-gradient-to-r from-indigo-600 to-purple-600 text-white font-semibold rounded-lg hover:from-indigo-700 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all shadow-lg">
                            <i class="fas fa-sync-alt mr-2"></i>Refresh
                        </button>
                    </div>
                </div>
            </div>

            <!-- Data Table -->
            <div class="glass-effect rounded-2xl shadow-xl border border-gray-200 animate-fade-in">
                <div class="p-6 border-b border-gray-200">
                    <h3 class="text-2xl font-bold text-gray-800 flex items-center">
                        <i class="fas fa-table mr-3 text-indigo-600"></i>
                        Detail Peminjaman Copy Panel
                    </h3>
                    <p class="text-sm text-gray-600 mt-1">
                        Data real-time copy panel yang dipinjam dengan masa aktif 90 hari. 
                        <span class="font-semibold text-purple-600">Master Color tidak dapat dipinjam.</span>
                    </p>
                </div>
                
                <div class="p-6">
                    <div id="loading" class="text-center py-12 hidden">
                        <div class="inline-block animate-spin rounded-full h-16 w-16 border-b-4 border-indigo-600"></div>
                        <p class="mt-4 text-gray-600 font-medium">Memuat data...</p>
                    </div>

                    <div id="table-container" class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200" id="data-table">
                            <thead class="bg-gradient-to-r from-indigo-50 to-purple-50">
                                <tr>
                                    <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">No Reservasi</th>
                                    <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Nama Peminjam</th>
                                    <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Rack No</th>
                                    <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Kode Barang</th>
                                    <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Panel Code</th>
                                    <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Master Color</th>
                                    <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Components</th>
                                    <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Expired Date</th>
                                    <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Sisa Waktu</th>
                                </tr>
                            </thead>
                            <tbody id="table-body" class="bg-white divide-y divide-gray-200">
                                <!-- Will be filled by JavaScript -->
                            </tbody>
                        </table>
                    </div>

                    <div id="no-data" class="text-center py-12 hidden">
                        <i class="fas fa-inbox text-6xl text-gray-300 mb-4"></i>
                        <p class="text-gray-500 font-medium">Tidak ada data yang sesuai dengan filter</p>
                    </div>
                </div>
            </div>

        </div>

        <!-- Tab Content: Diagram -->
        <div id="content-diagram" class="tab-content">
            
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 animate-fade-in">
                
                <!-- Pie Chart - Status Distribution -->
                <div class="glass-effect rounded-2xl shadow-xl p-6 border border-gray-200">
                    <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                        <i class="fas fa-chart-pie mr-3 text-indigo-600"></i>
                        Distribusi Status Copy Panel
                    </h3>
                    <div class="relative" style="height: 400px;">
                        <canvas id="statusChart"></canvas>
                    </div>
                </div>

                <!-- Bar Chart - Top Borrowers -->
                <div class="glass-effect rounded-2xl shadow-xl p-6 border border-gray-200">
                    <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                        <i class="fas fa-chart-bar mr-3 text-purple-600"></i>
                        Top 5 Peminjam Terbanyak
                    </h3>
                    <div class="relative" style="height: 400px;">
                        <canvas id="borrowersChart"></canvas>
                    </div>
                </div>

                <!-- Line Chart - Trend Peminjaman -->
                <div class="glass-effect rounded-2xl shadow-xl p-6 border border-gray-200 lg:col-span-2">
                    <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                        <i class="fas fa-chart-line mr-3 text-green-600"></i>
                        Ringkasan Status per Component
                    </h3>
                    <div class="relative" style="height: 400px;">
                        <canvas id="componentChart"></canvas>
                    </div>
                </div>

            </div>

        </div>

    </div>

    <!-- Footer -->
    <footer class="mt-12 py-6 text-center text-gray-600 text-sm">
        <p>&copy; <?php echo date('Y'); ?> Dashboard Monitoring Peminjaman Copy Panel. All rights reserved.</p>
        <p class="mt-1">Auto-refresh every 30 seconds</p>
    </footer>

    <script>
        // Global variables
        let allData = [];
        let currentTab = 'table';
        let statusChart, borrowersChart, componentChart;

        // Switch tab
        function switchTab(tab) {
            currentTab = tab;
            
            // Update tab buttons
            document.getElementById('tab-table').classList.remove('active');
            document.getElementById('tab-diagram').classList.remove('active');
            document.getElementById('tab-' + tab).classList.add('active');
            
            // Update tab content
            document.getElementById('content-table').classList.remove('active');
            document.getElementById('content-diagram').classList.remove('active');
            document.getElementById('content-' + tab).classList.add('active');
            
            // Load charts if switching to diagram tab
            if (tab === 'diagram' && allData.length > 0) {
                setTimeout(() => {
                    updateCharts(calculateStats(allData));
                }, 100);
            }
        }

        // Format date
        function formatDate(dateString) {
            if (!dateString) return '-';
            const date = new Date(dateString);
            const months = ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];
            return `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`;
        }

        // Calculate statistics from data
        function calculateStats(items) {
            const stats = {
                aman: 0,
                kritis: 0,
                expired: 0,
                dipinjam: 0,
                top_borrowers: [],
                by_component: {}
            };
            
            const borrower_counts = {};
            
            items.forEach(item => {
                // Status counts
                if (item.sisa_hari < 0) {
                    stats.expired++;
                } else if (item.sisa_hari <= 10) {
                    stats.kritis++;
                } else {
                    stats.aman++;
                }
                
                if (item.status === 'Dipinjam') {
                    stats.dipinjam++;
                }
                
                // Borrower counts
                if (item.peminjam) {
                    borrower_counts[item.peminjam] = (borrower_counts[item.peminjam] || 0) + 1;
                }
                
                // Component counts
                if (item.component_name) {
                    if (!stats.by_component[item.component_name]) {
                        stats.by_component[item.component_name] = { aman: 0, kritis: 0, expired: 0 };
                    }
                    
                    if (item.sisa_hari < 0) {
                        stats.by_component[item.component_name].expired++;
                    } else if (item.sisa_hari <= 10) {
                        stats.by_component[item.component_name].kritis++;
                    } else {
                        stats.by_component[item.component_name].aman++;
                    }
                }
            });
            
            // Get top 5 borrowers
            const sorted = Object.entries(borrower_counts).sort((a, b) => b[1] - a[1]);
            stats.top_borrowers = sorted.slice(0, 5).map(([name, count]) => ({ name, count }));
            
            return stats;
        }

        // Load data
        function loadData() {
            document.getElementById('loading').classList.remove('hidden');
            document.getElementById('table-container').classList.add('hidden');
            document.getElementById('no-data').classList.add('hidden');

            fetch('get_monitoring_data2.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        allData = data.items;
                        renderTable(allData);
                        
                        if (currentTab === 'diagram') {
                            updateCharts(calculateStats(allData));
                        }
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                })
                .finally(() => {
                    document.getElementById('loading').classList.add('hidden');
                });
        }

        // Render table
        function renderTable(items) {
            const tbody = document.getElementById('table-body');
            tbody.innerHTML = '';
        
            if (items.length === 0) {
                document.getElementById('table-container').classList.add('hidden');
                document.getElementById('no-data').classList.remove('hidden');
                return;
            }
        
            document.getElementById('table-container').classList.remove('hidden');
            document.getElementById('no-data').classList.add('hidden');
        
            items.forEach((item, index) => {
                const row = document.createElement('tr');
                row.className = index % 2 === 0 ? 'bg-white hover:bg-indigo-50' : 'bg-gray-50 hover:bg-indigo-50';
                row.classList.add('transition-colors');
        
                // Sisa waktu with color coding
                let sisaWaktuHtml = '';
                if (item.sisa_hari < 0) {
                    sisaWaktuHtml = `<span class="px-3 py-1 inline-flex text-xs leading-5 font-bold rounded-full bg-red-100 text-red-800">EXPIRED</span>`;
                } else if (item.sisa_hari <= 10) {
                    sisaWaktuHtml = `<span class="px-3 py-1 inline-flex text-xs leading-5 font-bold rounded-full bg-orange-100 text-orange-800">${item.sisa_hari} hari</span>`;
                } else {
                    sisaWaktuHtml = `<span class="px-3 py-1 inline-flex text-xs leading-5 font-bold rounded-full bg-green-100 text-green-800">${item.sisa_hari} hari</span>`;
                }
        
                // Rack No with badge style
                const rackHtml = item.rack_no 
                    ? `<span class="px-2 py-1 inline-flex text-xs font-semibold rounded bg-blue-100 text-blue-800">${item.rack_no}</span>` 
                    : `<span class="text-gray-400 text-xs">-</span>`;
                
                // Master Color badge
                const masterColorHtml = item.master_code
                    ? `<span class="px-2 py-1 inline-flex text-xs font-bold rounded bg-purple-100 text-purple-800">${item.master_code}</span>`
                    : `<span class="text-gray-400 text-xs">-</span>`;
        
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700 font-medium">${item.reservation_number || '-'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-800 font-semibold">${item.peminjam || '-'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm">${rackHtml}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-bold text-indigo-600">${item.kode_barang}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-semibold text-green-600">${item.panel_code}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm">${masterColorHtml}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">${item.component_name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">${formatDate(item.tanggal_kedaluwarsa)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm">${sisaWaktuHtml}</td>
                `;
                tbody.appendChild(row);
            });
        }

        // Update charts
        function updateCharts(stats) {
            // Status Chart
            const statusCtx = document.getElementById('statusChart').getContext('2d');
            
            if (statusChart) statusChart.destroy();
            
            statusChart = new Chart(statusCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Aman (> 10 hari)', 'Kritis (≤ 10 hari)', 'Expired', 'Sedang Dipinjam'],
                    datasets: [{
                        data: [stats.aman, stats.kritis, stats.expired, stats.dipinjam],
                        backgroundColor: [
                            'rgb(34, 197, 94)',
                            'rgb(249, 115, 22)',
                            'rgb(239, 68, 68)',
                            'rgb(59, 130, 246)'
                        ],
                        borderWidth: 3,
                        borderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                font: {
                                    size: 13,
                                    family: 'Inter',
                                    weight: '500'
                                }
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.parsed || 0;
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((value / total) * 100).toFixed(1);
                                    return `${label}: ${value} items (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });

            // Borrowers Chart
            const borrowersCtx = document.getElementById('borrowersChart').getContext('2d');
            
            if (borrowersChart) borrowersChart.destroy();
            
            borrowersChart = new Chart(borrowersCtx, {
                type: 'bar',
                data: {
                    labels: stats.top_borrowers.map(b => b.name),
                    datasets: [{
                        label: 'Jumlah Peminjaman',
                        data: stats.top_borrowers.map(b => b.count),
                        backgroundColor: 'rgba(139, 92, 246, 0.8)',
                        borderColor: 'rgb(139, 92, 246)',
                        borderWidth: 2,
                        borderRadius: 8
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1,
                                font: {
                                    family: 'Inter'
                                }
                            },
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            }
                        },
                        x: {
                            ticks: {
                                font: {
                                    family: 'Inter',
                                    weight: '500'
                                }
                            },
                            grid: {
                                display: false
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `Total: ${context.parsed.y} items`;
                                }
                            }
                        }
                    }
                }
            });

            // Component Chart
            const componentCtx = document.getElementById('componentChart').getContext('2d');
            
            if (componentChart) componentChart.destroy();
            
            const componentLabels = Object.keys(stats.by_component);
            const amanData = componentLabels.map(comp => stats.by_component[comp].aman);
            const kritisData = componentLabels.map(comp => stats.by_component[comp].kritis);
            const expiredData = componentLabels.map(comp => stats.by_component[comp].expired);
            
            componentChart = new Chart(componentCtx, {
                type: 'bar',
                data: {
                    labels: componentLabels,
                    datasets: [
                        {
                            label: 'Aman',
                            data: amanData,
                            backgroundColor: 'rgba(34, 197, 94, 0.8)',
                            borderColor: 'rgb(34, 197, 94)',
                            borderWidth: 2
                        },
                        {
                            label: 'Kritis',
                            data: kritisData,
                            backgroundColor: 'rgba(249, 115, 22, 0.8)',
                            borderColor: 'rgb(249, 115, 22)',
                            borderWidth: 2
                        },
                        {
                            label: 'Expired',
                            data: expiredData,
                            backgroundColor: 'rgba(239, 68, 68, 0.8)',
                            borderColor: 'rgb(239, 68, 68)',
                            borderWidth: 2
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        x: {
                            stacked: true,
                            ticks: {
                                font: {
                                    family: 'Inter',
                                    size: 11
                                }
                            },
                            grid: {
                                display: false
                            }
                        },
                        y: {
                            stacked: true,
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1,
                                font: {
                                    family: 'Inter'
                                }
                            },
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                padding: 15,
                                font: {
                                    size: 13,
                                    family: 'Inter',
                                    weight: '500'
                                },
                                usePointStyle: true,
                                pointStyle: 'circle'
                            }
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false
                        }
                    }
                }
            });
        }

        // Filter and search
        document.getElementById('filter-status').addEventListener('change', applyFilters);
        document.getElementById('search-input').addEventListener('input', applyFilters);

        function applyFilters() {
            const filterStatus = document.getElementById('filter-status').value;
            const searchTerm = document.getElementById('search-input').value.toLowerCase();

            let filtered = allData;

            // Apply status filter
            if (filterStatus !== 'all') {
                filtered = filtered.filter(item => {
                    if (filterStatus === 'aman') return item.sisa_hari > 10;
                    if (filterStatus === 'kritis') return item.sisa_hari >= 0 && item.sisa_hari <= 10;
                    if (filterStatus === 'expired') return item.sisa_hari < 0;
                    if (filterStatus === 'dipinjam') return item.status === 'Dipinjam';
                    return true;
                });
            }

            // Apply search
            if (searchTerm) {
                filtered = filtered.filter(item => 
                    item.kode_barang.toLowerCase().includes(searchTerm) ||
                    (item.peminjam && item.peminjam.toLowerCase().includes(searchTerm)) ||
                    (item.panel_code && item.panel_code.toLowerCase().includes(searchTerm)) ||
                    (item.master_code && item.master_code.toLowerCase().includes(searchTerm)) ||
                    (item.reservation_number && item.reservation_number.toLowerCase().includes(searchTerm))
                );
            }

            renderTable(filtered);
        }

        // Refresh data
        function refreshData() {
            loadData();
        }

        // Update current time
        function updateTime() {
            const now = new Date();
            const options = { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };
            document.getElementById('current-time').textContent = now.toLocaleDateString('id-ID', options);
        }

        // Auto-refresh every 30 seconds
        setInterval(() => {
            loadData();
            updateTime();
        }, 30000);

        // Update time every second
        setInterval(updateTime, 1000);

        // Initial load
        document.addEventListener('DOMContentLoaded', function() {
            loadData();
        });
    </script>

</body>
</html>