<?php
// Start session for any session-based functionality
session_start();

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

// Set page title
$page_title = "Data Color Panel";

// Get all buyers_surabaya for filter
$buyer_query = "SELECT id, nama_buyer FROM buyers_surabaya ORDER BY nama_buyer";
$buyer_result = $conn->query($buyer_query);

// Get all components for filter
$component_query = "SELECT id, component_name FROM color_components_surabaya ORDER BY component_name";
$component_result = $conn->query($component_query);

// Get monitoring data
// Total On Going (transaksi masih dipinjam)
$ongoing_query = "SELECT COUNT(*) as count FROM stock_transactions_surabaya WHERE status_peminjaman = 'Dipinjam'";
$ongoing_result = $conn->query($ongoing_query);
$total_ongoing = $ongoing_result->fetch_assoc()['count'];

// Total Dipinjam (code barang dengan status dipinjam)
$dipinjam_query = "SELECT COUNT(*) as count FROM color_stock_items_surabaya WHERE status = 'Dipinjam'";
$dipinjam_result = $conn->query($dipinjam_query);
$total_dipinjam = $dipinjam_result->fetch_assoc()['count'];

// Total Overdue (transaksi dipinjam yang sudah overdue)
$overdue_query = "
    SELECT COUNT(*) as count 
    FROM stock_transactions_surabaya st
    INNER JOIN transaction_items_surabaya ti ON st.id = ti.transaction_id
    WHERE st.status_peminjaman = 'Dipinjam' 
    AND ti.status_waktu = 'overdue'
    AND TIMESTAMPDIFF(MINUTE, st.tanggal_pengembalian, NOW()) > 15
";
$overdue_result = $conn->query($overdue_query);
$total_overdue = $overdue_result->fetch_assoc()['count'];

// Include header if exists
if (file_exists('includes/header.php')) {
    include 'includes/header.php';
}
?>

<!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>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body class="bg-gray-100">

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-100">
    <!-- Page Header -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Data Color Panel</h2>
        <p class="text-gray-600">Kelola dan lihat data warna dan komponennya</p>
    </div>
    
    <!-- Monitoring Cards -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <!-- Total On Going Card -->
        <div class="bg-white rounded-lg shadow-md p-6 cursor-pointer hover:shadow-lg transition-shadow duration-200" onclick="showOnGoingModal()">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-clock text-blue-600 text-xl"></i>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Total On Going</p>
                    <p class="text-2xl font-bold text-blue-600"><?php echo $total_ongoing; ?></p>
                    <p class="text-xs text-gray-500">Transaksi Dipinjam</p>
                </div>
            </div>
        </div>

        <!-- Total Dipinjam Card -->
        <div class="bg-white rounded-lg shadow-md p-6 cursor-pointer hover:shadow-lg transition-shadow duration-200" onclick="showDipinjamModal()">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-hand-holding text-green-600 text-xl"></i>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Total Dipinjam</p>
                    <p class="text-2xl font-bold text-green-600"><?php echo $total_dipinjam; ?></p>
                    <p class="text-xs text-gray-500">Code Barang</p>
                </div>
            </div>
        </div>

        <!-- Total Overdue Card -->
        <div class="bg-white rounded-lg shadow-md p-6 cursor-pointer hover:shadow-lg transition-shadow duration-200" onclick="showOverdueModal()">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-exclamation-triangle text-red-600 text-xl"></i>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Total Overdue</p>
                    <p class="text-2xl font-bold text-red-600"><?php echo $total_overdue; ?></p>
                    <p class="text-xs text-gray-500">Transaksi Terlambat</p>
                </div>
            </div>
        </div>

        <!-- System Status Card -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-chart-line text-purple-600 text-xl"></i>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">System Status</p>
                    <p class="text-2xl font-bold text-purple-600">Online</p>
                    <p class="text-xs text-gray-500">Real-time Monitoring</p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Search Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold text-gray-700">
                <i class="fas fa-search mr-2 text-blue-600"></i>Pencarian Real-time
            </h3>
            <button id="search_help" class="bg-blue-100 hover:bg-blue-200 text-blue-700 font-medium py-2 px-4 rounded-lg transition duration-150 ease-in-out flex items-center">
                <i class="fas fa-question-circle mr-2"></i>Petunjuk Pencarian
            </button>
        </div>
        
        <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                <i id="search_icon" class="fas fa-search text-gray-400 transition-colors duration-200"></i>
            </div>
            <input type="text" id="realtime_search" 
                   placeholder="Ketik kode barang (contoh: CP.0001) atau color code (contoh: WDG 001)..." 
                   class="w-full pl-12 pr-16 py-4 border-2 border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-base font-medium transition-all duration-200 hover:border-gray-300"
                   autocomplete="off"
                   spellcheck="false">
            <div class="absolute inset-y-0 right-0 pr-4 flex items-center space-x-2">
                <div id="search_loading" class="hidden">
                    <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-500"></div>
                </div>
                <button id="clear_search" class="text-gray-400 hover:text-red-500 hidden transition-colors duration-200 p-1 rounded-full hover:bg-red-50">
                    <i class="fas fa-times text-sm"></i>
                </button>
            </div>
        </div>
        
        <div id="search_status" class="mt-3 hidden">
            <div class="flex items-center justify-between bg-blue-50 border border-blue-200 rounded-lg p-3">
                <div class="flex items-center">
                    <i class="fas fa-info-circle mr-2 text-blue-600"></i>
                    <span id="search_status_text" class="text-sm font-medium text-blue-800"></span>
                </div>
                <div id="search_results_count" class="text-xs text-blue-600 bg-blue-100 px-2 py-1 rounded-full font-medium"></div>
            </div>
        </div>
        
        <!-- Enhanced Search Suggestions -->
        <div id="search_suggestions" class="mt-4 hidden">
            <div class="text-xs text-gray-500 mb-3">Contoh pencarian yang dapat digunakan:</div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div class="bg-gray-50 rounded-lg p-3">
                    <div class="text-xs font-medium text-gray-700 mb-2">Pencarian Kode Barang:</div>
                    <div class="flex flex-wrap gap-2">
                        <button class="search-suggestion bg-blue-100 hover:bg-blue-200 text-blue-700 text-xs px-2 py-1 rounded transition-colors duration-200" data-search="CP.0001">
                            CP.0001
                        </button>
                        <button class="search-suggestion bg-blue-100 hover:bg-blue-200 text-blue-700 text-xs px-2 py-1 rounded transition-colors duration-200" data-search="CP.0020">
                            CP.0020
                        </button>
                        <button class="search-suggestion bg-blue-100 hover:bg-blue-200 text-blue-700 text-xs px-2 py-1 rounded transition-colors duration-200" data-search="CP.0036">
                            CP.0036
                        </button>
                    </div>
                </div>
                <div class="bg-gray-50 rounded-lg p-3">
                    <div class="text-xs font-medium text-gray-700 mb-2">Pencarian Color Code:</div>
                    <div class="flex flex-wrap gap-2">
                        <button class="search-suggestion bg-green-100 hover:bg-green-200 text-green-700 text-xs px-2 py-1 rounded transition-colors duration-200" data-search="WDG 001">
                            WDG 001
                        </button>
                        <button class="search-suggestion bg-green-100 hover:bg-green-200 text-green-700 text-xs px-2 py-1 rounded transition-colors duration-200" data-search="GREEN NC">
                            GREEN NC
                        </button>
                        <button class="search-suggestion bg-green-100 hover:bg-green-200 text-green-700 text-xs px-2 py-1 rounded transition-colors duration-200" data-search="483">
                            483
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Search Type Indicator -->
        <div id="search_type_indicator" class="mt-2 hidden">
            <div class="flex items-center space-x-2">
                <div class="w-2 h-2 bg-blue-500 rounded-full animate-pulse"></div>
                <span id="search_type_text" class="text-xs text-gray-600"></span>
            </div>
        </div>
    </div>
    
    <!-- Filters Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold text-gray-700">Filter Data</h3>
            <button id="filter_help" class="bg-blue-100 hover:bg-blue-200 text-blue-700 font-medium py-1 px-3 rounded-md transition duration-150 ease-in-out flex items-center">
                <i class="fas fa-question-circle mr-2"></i>Petunjuk Filter
            </button>
        </div>
        
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <!-- Buyer Filter -->
            <div>
                <label for="buyer_filter" class="block text-sm font-medium text-gray-700 mb-1">Buyer</label>
                <select id="buyer_filter" class="w-full rounded-md border border-gray-300 shadow-sm px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    <option value="">Semua Buyer</option>
                    <?php while ($buyer = $buyer_result->fetch_assoc()): ?>
                        <option value="<?php echo $buyer['id']; ?>"><?php echo htmlspecialchars($buyer['nama_buyer']); ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            
            <!-- Color Code Filter -->
            <div>
                <label for="color_filter" class="block text-sm font-medium text-gray-700 mb-1">Kode Warna</label>
                <select id="color_filter" class="w-full rounded-md border border-gray-300 shadow-sm px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500" disabled>
                    <option value="">Pilih Buyer Terlebih Dahulu</option>
                </select>
            </div>
            
            <!-- Component Filter -->
            <div>
                <label for="component_filter" class="block text-sm font-medium text-gray-700 mb-1">Component</label>
                <select id="component_filter" class="w-full rounded-md border border-gray-300 shadow-sm px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500" disabled>
                    <option value="">Pilih Color Code Terlebih Dahulu</option>
                </select>
            </div>
            
            <!-- Status Filter -->
            <div>
                <label for="status_filter" class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                <select id="status_filter" class="w-full rounded-md border border-gray-300 shadow-sm px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    <option value="">Semua Status</option>
                    <option value="Tersedia">Tersedia</option>
                    <option value="Dipinjam">Dipinjam</option>
                    <option value="Rusak">Rusak</option>
                    <option value="Expired">Expired</option>
                    <option value="Renew">Renew</option>
                    <option value="Hilang">Hilang</option>
                </select>
            </div>
        </div>
        
        <!-- Apply and Reset Filters Button -->
        <div class="mt-4 flex space-x-2">
            <button id="apply_filters" class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-md transition duration-150 ease-in-out">
                <i class="fas fa-filter mr-2"></i>Terapkan Filter
            </button>
            <button id="reset_filters" class="bg-gray-500 hover:bg-gray-600 text-white font-medium py-2 px-4 rounded-md transition duration-150 ease-in-out">
                <i class="fas fa-undo mr-2"></i>Reset Filter
            </button>
        </div>
    </div>
    
    <!-- Color Data Grid -->
    <div class="bg-white rounded-lg shadow-md p-6">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-semibold text-gray-800">Data Color & Component</h3>
            <div id="data_count" class="bg-blue-100 text-blue-800 font-medium py-1 px-3 rounded-md">
                Loading...
            </div>
        </div>
        
        <div id="color_data_container" class="overflow-x-auto">
            <!-- Data will be loaded here via AJAX -->
            <div class="flex justify-center items-center h-40">
                <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
                <span class="ml-2 text-gray-500">Memuat data...</span>
            </div>
        </div>
    </div>
</main>

<!-- QR Code Modal -->
<div id="qr_code_modal" class="fixed z-50 inset-0 overflow-y-auto hidden">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-md sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-900">
                        <i class="fas fa-qrcode mr-2 text-blue-600"></i>QR Code Detail
                    </h3>
                    <button type="button" id="close_qr_modal" class="text-gray-400 hover:text-gray-600 focus:outline-none">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                
                <div class="text-center">
                    <!-- QR Code Image -->
                    <div class="mb-4 p-4 bg-gray-50 rounded-lg">
                        <img id="qr_code_image" src="" alt="QR Code" class="mx-auto max-w-full h-auto" style="max-width: 250px;">
                    </div>
                    
                    <!-- Item Details -->
                    <div class="bg-blue-50 rounded-lg p-4 mb-4">
                        <div class="text-sm text-gray-600 mb-2">Kode Barang</div>
                        <div id="qr_item_code" class="text-lg font-bold text-blue-900 font-mono"></div>
                    </div>
                    
                    <!-- Additional Details -->
                    <div class="grid grid-cols-2 gap-4 text-left">
                        <div class="bg-gray-50 rounded-lg p-3">
                            <div class="text-xs text-gray-500 mb-1">Component</div>
                            <div id="qr_component" class="text-sm font-medium text-gray-900"></div>
                        </div>
                        <div class="bg-gray-50 rounded-lg p-3">
                            <div class="text-xs text-gray-500 mb-1">Status</div>
                            <div id="qr_status" class="text-sm font-medium"></div>
                        </div>
                        <div class="bg-gray-50 rounded-lg p-3">
                            <div class="text-xs text-gray-500 mb-1">Lokasi</div>
                            <div id="qr_location" class="text-sm font-medium text-gray-900"></div>
                        </div>
                        <div class="bg-gray-50 rounded-lg p-3">
                            <div class="text-xs text-gray-500 mb-1">Rack No</div>
                            <div id="qr_rack" class="text-sm font-medium text-gray-900"></div>
                        </div>
                    </div>
                    
                    <!-- Download Button -->
                    <div class="mt-4">
                        <button id="download_qr" class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-md transition duration-150 ease-in-out">
                            <i class="fas fa-download mr-2"></i>Download QR Code
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- On Going Modal -->
<div id="ongoing_modal" class="fixed z-50 inset-0 overflow-y-auto hidden">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-7xl sm:w-full">
            <div class="bg-white px-8 pt-6 pb-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-900">
                        <i class="fas fa-clock mr-2 text-blue-600"></i>Transaksi On Going
                    </h3>
                    <button type="button" id="close_ongoing_modal" class="text-gray-400 hover:text-gray-600 focus:outline-none">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                
                <div id="ongoing_data" class="max-h-[70vh] overflow-y-auto">
                    <!-- Data will be loaded here via AJAX -->
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Dipinjam Modal -->
<div id="dipinjam_modal" class="fixed z-50 inset-0 overflow-y-auto hidden">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-7xl sm:w-full">
            <div class="bg-white px-8 pt-6 pb-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-900">
                        <i class="fas fa-hand-holding mr-2 text-green-600"></i>Code Barang Dipinjam
                    </h3>
                    <button type="button" id="close_dipinjam_modal" class="text-gray-400 hover:text-gray-600 focus:outline-none">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                
                <div id="dipinjam_data" class="max-h-[70vh] overflow-y-auto">
                    <!-- Data will be loaded here via AJAX -->
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Overdue Modal -->
<div id="overdue_modal" class="fixed z-50 inset-0 overflow-y-auto hidden">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-7xl sm:w-full">
            <div class="bg-white px-6 pt-5 pb-4">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-900">
                        <i class="fas fa-exclamation-triangle mr-2 text-red-600"></i>Transaksi Overdue
                    </h3>
                    <button type="button" id="close_overdue_modal" class="text-gray-400 hover:text-gray-600 focus:outline-none">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                
                <div id="overdue_data" class="max-h-[70vh] overflow-y-auto">
                    <!-- Data will be loaded here via AJAX -->
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Borrowed Item Detail Modal -->
<div id="borrowed_detail_modal" class="fixed z-50 inset-0 overflow-y-auto hidden">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-md sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-900">
                        <i class="fas fa-info-circle mr-2 text-blue-600"></i>Detail Peminjaman
                    </h3>
                    <button type="button" id="close_borrowed_detail_modal" class="text-gray-400 hover:text-gray-600 focus:outline-none">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                
                <div id="borrowed_detail_data">
                    <!-- Data will be loaded here via AJAX -->
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Reservation Detail Modal -->
<div id="reservation_detail_modal" class="fixed z-50 inset-0 overflow-y-auto hidden">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-6xl sm:w-full">
            <div class="bg-white px-8 pt-6 pb-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-900">
                        <i class="fas fa-receipt mr-2 text-purple-600"></i>Detail Reservation
                    </h3>
                    <button type="button" id="close_reservation_detail_modal" class="text-gray-400 hover:text-gray-600 focus:outline-none">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                
                <div id="reservation_detail_data" class="max-h-[70vh] overflow-y-auto">
                    <!-- Data will be loaded here via AJAX -->
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Search Help Modal -->
<div id="search_help_modal" class="fixed z-10 inset-0 overflow-y-auto hidden">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="sm:flex sm:items-start">
                    <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-blue-100 sm:mx-0 sm:h-10 sm:w-10">
                        <i class="fas fa-search text-blue-600"></i>
                    </div>
                    <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                        <h3 class="text-lg leading-6 font-medium text-gray-900">
                            Petunjuk Pencarian Real-time
                        </h3>
                        <div class="mt-2">
                            <p class="text-sm text-gray-500 mb-3">
                                Fitur pencarian akan otomatis mendeteksi jenis pencarian:
                            </p>
                            <div class="space-y-3">
                                <div class="bg-blue-50 rounded-lg p-3">
                                    <div class="text-sm font-medium text-blue-900 mb-1">Pencarian Kode Barang</div>
                                    <div class="text-xs text-blue-700">Contoh: CP.0001, CP.0020</div>
                                    <div class="text-xs text-gray-600 mt-1">• Menampilkan hanya color yang memiliki kode barang tersebut</div>
                                    <div class="text-xs text-gray-600">• Otomatis membuka detail dan highlight hasil</div>
                                </div>
                                <div class="bg-green-50 rounded-lg p-3">
                                    <div class="text-sm font-medium text-green-900 mb-1">Pencarian Color Code</div>
                                    <div class="text-xs text-green-700">Contoh: WDG 001, GREEN NC, 483</div>
                                    <div class="text-xs text-gray-600 mt-1">• Menampilkan hanya color yang cocok dengan pencarian</div>
                                    <div class="text-xs text-gray-600">• Mengurutkan hasil berdasarkan kesesuaian</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button type="button" id="close_search_help" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                    Tutup
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Filter Help Modal -->
<div id="filter_help_modal" class="fixed z-10 inset-0 overflow-y-auto hidden">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="sm:flex sm:items-start">
                    <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-blue-100 sm:mx-0 sm:h-10 sm:w-10">
                        <i class="fas fa-info-circle text-blue-600"></i>
                    </div>
                    <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                        <h3 class="text-lg leading-6 font-medium text-gray-900">
                            Petunjuk Penggunaan Filter
                        </h3>
                        <div class="mt-2">
                            <p class="text-sm text-gray-500">
                                Untuk mempermudah pencarian, gunakan filter dengan urutan sebagai berikut:
                            </p>
                            <ul class="list-disc list-inside mt-2 text-sm text-gray-500">
                                <li>Pilih filter pembeli terlebih dahulu</li>
                                <li>Lalu pilih filter color code</li>
                                <li>Lalu pilih filter component</li>
                                <li>Baru klik tombol "Terapkan Filter" untuk mencari data sesuai yang dicari</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button type="button" id="close_filter_help" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                    Tutup
                </button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    let searchTimeout;
    let currentSearchTerm = '';
    
    // Load initial data
    loadColorData();
    
    // Real-time search functionality
    const searchInput = document.getElementById('realtime_search');
    const clearSearchBtn = document.getElementById('clear_search');
    const searchStatus = document.getElementById('search_status');
    const searchStatusText = document.getElementById('search_status_text');
    const searchResultsCount = document.getElementById('search_results_count');
    const searchLoading = document.getElementById('search_loading');
    const searchIcon = document.getElementById('search_icon');
    const searchSuggestions = document.getElementById('search_suggestions');
    const searchTypeIndicator = document.getElementById('search_type_indicator');
    const searchTypeText = document.getElementById('search_type_text');
    
    // Show/hide search suggestions
    searchInput.addEventListener('focus', function() {
        if (this.value.trim() === '') {
            searchSuggestions.classList.remove('hidden');
        }
    });
    
    searchInput.addEventListener('blur', function() {
        setTimeout(() => {
            searchSuggestions.classList.add('hidden');
        }, 200);
    });
    
    // Handle search suggestions clicks
    document.querySelectorAll('.search-suggestion').forEach(btn => {
        btn.addEventListener('click', function() {
            const searchValue = this.dataset.search;
            searchInput.value = searchValue;
            searchInput.focus();
            searchSuggestions.classList.add('hidden');
            performSearch(searchValue);
        });
    });
    
    // Function to detect search type and show indicator
    function updateSearchTypeIndicator(searchTerm) {
        if (!searchTerm) {
            searchTypeIndicator.classList.add('hidden');
            return;
        }
        
        const isKodeBarang = (searchTerm.toUpperCase().indexOf('CP.') === 0 || /^CP\.\d+/.test(searchTerm.toUpperCase()));
        
        if (isKodeBarang) {
            searchTypeText.textContent = 'Mencari berdasarkan Kode Barang';
            searchTypeIndicator.classList.remove('hidden');
        } else {
            searchTypeText.textContent = 'Mencari berdasarkan Color Code';
            searchTypeIndicator.classList.remove('hidden');
        }
    }
    
    searchInput.addEventListener('input', function() {
        const searchTerm = this.value.trim();
        
        // Update search type indicator
        updateSearchTypeIndicator(searchTerm);
        
        // Hide suggestions when typing
        if (searchTerm) {
            searchSuggestions.classList.add('hidden');
        }
        
        // Show/hide clear button and loading
        if (searchTerm) {
            clearSearchBtn.classList.remove('hidden');
            searchIcon.classList.remove('fa-search');
            searchIcon.classList.add('fa-search', 'text-blue-500');
        } else {
            clearSearchBtn.classList.add('hidden');
            searchStatus.classList.add('hidden');
            searchTypeIndicator.classList.add('hidden');
            searchIcon.classList.remove('text-blue-500');
            searchIcon.classList.add('text-gray-400');
            if (!searchTerm) {
                searchSuggestions.classList.remove('hidden');
            }
        }
        
        // Clear previous timeout
        clearTimeout(searchTimeout);
        
        // Set new timeout for search
        if (searchTerm.length >= 1) {
            searchLoading.classList.remove('hidden');
            searchTimeout = setTimeout(function() {
                performSearch(searchTerm);
            }, 300); // 300ms delay for real-time search
        } else {
            searchLoading.classList.add('hidden');
            currentSearchTerm = '';
            loadColorData();
        }
    });
    
    // Clear search functionality
    clearSearchBtn.addEventListener('click', function() {
        searchInput.value = '';
        clearSearchBtn.classList.add('hidden');
        searchStatus.classList.add('hidden');
        searchTypeIndicator.classList.add('hidden');
        searchLoading.classList.add('hidden');
        searchSuggestions.classList.remove('hidden');
        searchIcon.classList.remove('text-blue-500');
        searchIcon.classList.add('text-gray-400');
        currentSearchTerm = '';
        loadColorData(); // Reload data without search
        searchInput.focus();
    });
    
    // QR Code Modal functionality
    const qrModal = document.getElementById('qr_code_modal');
    const closeQrModal = document.getElementById('close_qr_modal');
    const downloadQrBtn = document.getElementById('download_qr');
    
    // Close QR modal
    closeQrModal.addEventListener('click', function() {
        qrModal.classList.add('hidden');
    });
    
    // Close QR modal when clicking outside
    qrModal.addEventListener('click', function(e) {
        if (e.target === qrModal) {
            qrModal.classList.add('hidden');
        }
    });
    
    // Download QR code
    downloadQrBtn.addEventListener('click', function() {
        const qrImage = document.getElementById('qr_code_image');
        const itemCode = document.getElementById('qr_item_code').textContent;
        
        if (qrImage.src) {
            const link = document.createElement('a');
            link.href = qrImage.src;
            link.download = `QR_${itemCode}.png`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    });
    
    // Function to show QR code modal
    window.showQRModal = function(qrCode, itemCode, component, status, location, rack) {
        document.getElementById('qr_code_image').src = qrCode;
        document.getElementById('qr_item_code').textContent = itemCode;
        document.getElementById('qr_component').textContent = component;
        document.getElementById('qr_location').textContent = location;
        document.getElementById('qr_rack').textContent = rack;
        
        // Set status with appropriate styling
        const statusElement = document.getElementById('qr_status');
        statusElement.textContent = status;
        statusElement.className = 'text-sm font-medium';
        
        switch (status) {
            case 'Tersedia':
                statusElement.classList.add('text-green-700');
                break;
            case 'Dipinjam':
                statusElement.classList.add('text-blue-700');
                break;
            case 'Rusak':
                statusElement.classList.add('text-red-700');
                break;
            case 'Expired':
                statusElement.classList.add('text-gray-700');
                break;
            case 'Renew':
                statusElement.classList.add('text-purple-700');
                break;
            case 'Hilang':
                statusElement.classList.add('text-yellow-700');
                break;
            default:
                statusElement.classList.add('text-gray-700');
        }
        
        qrModal.classList.remove('hidden');
    };

    // Monitoring Modal Functions
    window.showOnGoingModal = function() {
        const modal = document.getElementById('ongoing_modal');
        const dataContainer = document.getElementById('ongoing_data');
        
        modal.classList.remove('hidden');
        dataContainer.innerHTML = '<div class="text-center py-4"><div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div><span class="ml-2 text-gray-500">Memuat data...</span></div>';
        
        fetch('get_monitoring_data.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'type=ongoing'
        })
        .then(response => response.text())
        .then(data => {
            dataContainer.innerHTML = data;
        })
        .catch(error => {
            dataContainer.innerHTML = '<div class="text-red-500 text-center p-4">Error loading data</div>';
        });
    };

    window.showDipinjamModal = function() {
        const modal = document.getElementById('dipinjam_modal');
        const dataContainer = document.getElementById('dipinjam_data');
        
        modal.classList.remove('hidden');
        dataContainer.innerHTML = '<div class="text-center py-4"><div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div><span class="ml-2 text-gray-500">Memuat data...</span></div>';
        
        fetch('get_monitoring_data.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'type=dipinjam'
        })
        .then(response => response.text())
        .then(data => {
            dataContainer.innerHTML = data;
        })
        .catch(error => {
            dataContainer.innerHTML = '<div class="text-red-500 text-center p-4">Error loading data</div>';
        });
    };

    window.showOverdueModal = function() {
        const modal = document.getElementById('overdue_modal');
        const dataContainer = document.getElementById('overdue_data');
        
        modal.classList.remove('hidden');
        dataContainer.innerHTML = '<div class="text-center py-4"><div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div><span class="ml-2 text-gray-500">Memuat data...</span></div>';
        
        fetch('get_monitoring_data.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'type=overdue'
        })
        .then(response => response.text())
        .then(data => {
            dataContainer.innerHTML = data;
        })
        .catch(error => {
            dataContainer.innerHTML = '<div class="text-red-500 text-center p-4">Error loading data</div>';
        });
    };

    window.showBorrowedItemDetail = function(kodeBarang) {
        const modal = document.getElementById('borrowed_detail_modal');
        const dataContainer = document.getElementById('borrowed_detail_data');
        
        modal.classList.remove('hidden');
        dataContainer.innerHTML = '<div class="text-center py-4"><div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div><span class="ml-2 text-gray-500">Memuat data...</span></div>';
        
        fetch('get_monitoring_data.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `type=borrowed_detail&kode_barang=${encodeURIComponent(kodeBarang)}`
        })
        .then(response => response.text())
        .then(data => {
            dataContainer.innerHTML = data;
        })
        .catch(error => {
            dataContainer.innerHTML = '<div class="text-red-500 text-center p-4">Error loading data</div>';
        });
    };

    // New function for reservation detail modal
    window.showReservationDetail = function(reservationNumber, filterType = 'all') {
        const modal = document.getElementById('reservation_detail_modal');
        const dataContainer = document.getElementById('reservation_detail_data');
        
        modal.classList.remove('hidden');
        dataContainer.innerHTML = '<div class="text-center py-4"><div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div><span class="ml-2 text-gray-500">Memuat data...</span></div>';
        
        fetch('get_monitoring_data.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `type=reservation_detail&reservation_number=${encodeURIComponent(reservationNumber)}&filter_type=${encodeURIComponent(filterType)}`
        })
        .then(response => response.text())
        .then(data => {
            dataContainer.innerHTML = data;
        })
        .catch(error => {
            dataContainer.innerHTML = '<div class="text-red-500 text-center p-4">Error loading data</div>';
        });
    };
    
    // Close monitoring modals
    document.getElementById('close_ongoing_modal').addEventListener('click', function() {
        document.getElementById('ongoing_modal').classList.add('hidden');
    });
    
    document.getElementById('close_dipinjam_modal').addEventListener('click', function() {
        document.getElementById('dipinjam_modal').classList.add('hidden');
    });
    
    document.getElementById('close_overdue_modal').addEventListener('click', function() {
        document.getElementById('overdue_modal').classList.add('hidden');
    });

    document.getElementById('close_borrowed_detail_modal').addEventListener('click', function() {
        document.getElementById('borrowed_detail_modal').classList.add('hidden');
    });

    // Close reservation detail modal
    document.getElementById('close_reservation_detail_modal').addEventListener('click', function() {
        document.getElementById('reservation_detail_modal').classList.add('hidden');
    });

    // Close reservation modal when clicking outside
    document.getElementById('reservation_detail_modal').addEventListener('click', function(e) {
        if (e.target === this) {
            this.classList.add('hidden');
        }
    });
    
    // Search help modal controls
    const searchHelpButton = document.getElementById('search_help');
    const searchHelpModal = document.getElementById('search_help_modal');
    const closeSearchHelp = document.getElementById('close_search_help');
    
    searchHelpButton.addEventListener('click', function() {
        searchHelpModal.classList.remove('hidden');
    });
    
    closeSearchHelp.addEventListener('click', function() {
        searchHelpModal.classList.add('hidden');
    });
    
    // Close search modal when clicking outside
    searchHelpModal.addEventListener('click', function(e) {
        if (e.target === searchHelpModal) {
            searchHelpModal.classList.add('hidden');
        }
    });
    
    // Filter help modal controls
    const filterHelpButton = document.getElementById('filter_help');
    const filterHelpModal = document.getElementById('filter_help_modal');
    const closeFilterHelp = document.getElementById('close_filter_help');
    
    filterHelpButton.addEventListener('click', function() {
        filterHelpModal.classList.remove('hidden');
    });
    
    closeFilterHelp.addEventListener('click', function() {
        filterHelpModal.classList.add('hidden');
    });
    
    // Close filter modal when clicking outside
    filterHelpModal.addEventListener('click', function(e) {
        if (e.target === filterHelpModal) {
            filterHelpModal.classList.add('hidden');
        }
    });
    
    // Add event listeners for filter buttons
    document.getElementById('apply_filters').addEventListener('click', loadColorData);
    document.getElementById('reset_filters').addEventListener('click', function() {
        document.getElementById('buyer_filter').value = '';
        document.getElementById('color_filter').value = '';
        document.getElementById('color_filter').disabled = true;
        document.getElementById('color_filter').innerHTML = '<option value="">Pilih Buyer Terlebih Dahulu</option>';
        document.getElementById('component_filter').value = '';
        document.getElementById('component_filter').disabled = true;
        document.getElementById('component_filter').innerHTML = '<option value="">Pilih Color Code Terlebih Dahulu</option>';
        document.getElementById('status_filter').value = '';
        loadColorData();
    });
    
    // Add event listener for buyer filter change
    document.getElementById('buyer_filter').addEventListener('change', function() {
        const buyerId = this.value;
        const colorFilter = document.getElementById('color_filter');
        const componentFilter = document.getElementById('component_filter');
        
        // Reset component filter
        componentFilter.innerHTML = '<option value="">Pilih Color Code Terlebih Dahulu</option>';
        componentFilter.disabled = true;
        
        if (buyerId) {
            // Enable color filter and fetch color codes for the selected buyer
            colorFilter.disabled = false;
            colorFilter.innerHTML = '<option value="">Loading...</option>';
            
            fetch('get_color_codes.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `buyer_id=${buyerId}`
            })
            .then(response => response.json())
            .then(data => {
                colorFilter.innerHTML = '<option value="">Semua Kode Warna</option>';
                data.forEach(color => {
                    const option = document.createElement('option');
                    option.value = color.id;
                    option.textContent = color.code_color + ' - ' + color.deskripsi;
                    colorFilter.appendChild(option);
                });
            })
            .catch(error => {
                colorFilter.innerHTML = '<option value="">Error loading color codes</option>';
                console.error('Error:', error);
            });
        } else {
            // Reset color filter if no buyer is selected
            colorFilter.innerHTML = '<option value="">Pilih Buyer Terlebih Dahulu</option>';
            colorFilter.disabled = true;
        }
    });
    
    // Add event listener for color filter change
    document.getElementById('color_filter').addEventListener('change', function() {
        const colorId = this.value;
        const componentFilter = document.getElementById('component_filter');
        
        if (colorId) {
            // Enable component filter and fetch components for the selected color
            componentFilter.disabled = false;
            componentFilter.innerHTML = '<option value="">Loading...</option>';
            
            fetch('get_color_components_surabaya_pages.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `color_id=${colorId}`
            })
            .then(response => response.json())
            .then(data => {
                componentFilter.innerHTML = '<option value="">Semua Component</option>';
                data.forEach(component => {
                    const option = document.createElement('option');
                    option.value = component.id;
                    option.textContent = component.component_name;
                    componentFilter.appendChild(option);
                });
            })
            .catch(error => {
                componentFilter.innerHTML = '<option value="">Error loading components</option>';
                console.error('Error:', error);
            });
        } else {
            // Reset component filter if no color is selected
            componentFilter.innerHTML = '<option value="">Pilih Color Code Terlebih Dahulu</option>';
            componentFilter.disabled = true;
        }
    });
    
    // Function to perform search
    function performSearch(searchTerm) {
        currentSearchTerm = searchTerm;
        
        if (searchTerm) {
            const isKodeBarang = (searchTerm.toUpperCase().indexOf('CP.') === 0 || /^CP\.\d+/.test(searchTerm.toUpperCase()));
            const searchType = isKodeBarang ? 'kode barang' : 'color code';
            
            searchStatusText.textContent = `Mencari ${searchType}: "${searchTerm}"...`;
            searchStatus.classList.remove('hidden');
        }
        
        loadColorData();
    }
    
    // Function to load color data with filters and search
    function loadColorData() {
        const buyer = document.getElementById('buyer_filter').value;
        const color = document.getElementById('color_filter').value;
        const component = document.getElementById('component_filter').value;
        const status = document.getElementById('status_filter').value;
        
        const container = document.getElementById('color_data_container');
        container.innerHTML = `
            <div class="flex justify-center items-center h-40">
                <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
                <span class="ml-2 text-gray-500">Memuat data...</span>
            </div>
        `;
        
        // AJAX request to get filtered data
        fetch('get_color_data.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `buyer=${buyer}&color=${color}&component=${component}&status=${status}&search=${encodeURIComponent(currentSearchTerm)}`
        })
        .then(response => response.text())
        .then(data => {
            container.innerHTML = data;
            updateDataCount();
            updateSearchStatus();
            
            // Add click event listeners to color headers for toggle functionality
            addColorToggleListeners();
        })
        .catch(error => {
            container.innerHTML = `<div class="text-red-500 text-center p-4">Error loading data: ${error.message}</div>`;
        });
    }
    
    // Function to add toggle listeners to color headers
    function addColorToggleListeners() {
        const colorHeaders = document.querySelectorAll('.color-header');
        colorHeaders.forEach(header => {
            header.addEventListener('click', function() {
                const colorId = this.dataset.colorId;
                const componentsTable = document.getElementById(`components-${colorId}`);
                const toggleIcon = this.querySelector('.toggle-icon');
                
                if (componentsTable.classList.contains('hidden')) {
                    componentsTable.classList.remove('hidden');
                    toggleIcon.classList.remove('fa-chevron-right');
                    toggleIcon.classList.add('fa-chevron-down');
                } else {
                    componentsTable.classList.add('hidden');
                    toggleIcon.classList.remove('fa-chevron-down');
                    toggleIcon.classList.add('fa-chevron-right');
                }
            });
        });
    }
    
    // Function to update search status
    function updateSearchStatus() {
        if (currentSearchTerm) {
            const highlightedItems = document.querySelectorAll('.search-highlight');
            const isKodeBarang = (currentSearchTerm.toUpperCase().indexOf('CP.') === 0 || /^CP\.\d+/.test(currentSearchTerm.toUpperCase()));
            const searchType = isKodeBarang ? 'kode barang' : 'color code';
            
            if (highlightedItems.length > 0) {
                searchStatusText.textContent = `Ditemukan ${highlightedItems.length} hasil untuk ${searchType}: "${currentSearchTerm}"`;
                searchStatus.classList.remove('hidden');
            } else {
                searchStatusText.textContent = `Tidak ada hasil untuk ${searchType}: "${currentSearchTerm}"`;
                searchStatus.classList.remove('hidden');
            }
        }
    }
    
    // Add keyboard shortcuts
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + F to focus search
        if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
            e.preventDefault();
            searchInput.focus();
            searchInput.select();
        }
        
        // Escape to clear search
        if (e.key === 'Escape' && searchInput === document.activeElement) {
            clearSearchBtn.click();
        }
        
        // Enter to search when focused on search input
        if (e.key === 'Enter' && searchInput === document.activeElement) {
            e.preventDefault();
            const searchTerm = searchInput.value.trim();
            if (searchTerm) {
                performSearch(searchTerm);
            }
        }
    });
    
    // Function to update the data count display
    function updateDataCount() {
        const dataCount = document.getElementById('data_count');
        const colorItems = document.querySelectorAll('.color-item');
        const totalComponents = document.querySelectorAll('.component-row').length;
        
        if (currentSearchTerm) {
            const searchResults = document.querySelectorAll('.search-highlight').length;
            const isKodeBarang = (currentSearchTerm.toUpperCase().indexOf('CP.') === 0 || /^CP\.\d+/.test(currentSearchTerm.toUpperCase()));
            const searchType = isKodeBarang ? 'kode barang' : 'color code';
            
            dataCount.textContent = `${colorItems.length} Warna, ${totalComponents} Komponen (${searchResults} hasil ${searchType})`;
        } else {
            dataCount.textContent = `${colorItems.length} Warna, ${totalComponents} Komponen`;
        }
    }
});
</script>

<?php 
// Include footer if exists
if (file_exists('includes/footer.php')) {
    include 'includes/footer.php';
}
?>

</body>
</html>