<?php
// Start session
session_start();

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

// Redirect if not IT user - using functions from connection.php
if (!is_logged_in() || !is_user_type('it')) {
    header("Location: ../login.php");
    exit();
}

// Get IT user data
$it_id = $_SESSION['user_id'];

// Set page title
$page_title = "Durasi Color";

// Log activity
log_activity($conn, $it_id, 'it', 'Color Duration Access', 'IT user accessed color duration page');

// Function to generate QR code - UPDATED: Only contains code barang
function generateQRCode($kode_barang) {
    require_once('../phpqrcode/qrlib.php');
    
    // Generate a unique filename
    $tempDir = "../qrcodes/";
    if (!is_dir($tempDir)) {
        mkdir($tempDir, 0755, true);
    }
    $filename = uniqid() . ".png";
    $filePath = $tempDir . $filename;
    
    // Generate QR code with only code barang
    QRcode::png($kode_barang, $filePath, QR_ECLEVEL_L, 10);
    
    // Return the image as base64
    $qrData = file_get_contents($filePath);
    $base64 = 'data:image/png;base64,' . base64_encode($qrData);
    
    // Remove the temporary file
    unlink($filePath);
    
    return $base64;
}

// Process bulk QR generation if submitted
if (isset($_POST['generate_bulk_qr'])) {
    $selected_items = $_POST['selected_items'] ?? [];
    $generated_count = 0;
    $error_count = 0;
    
    if (!empty($selected_items)) {
        foreach ($selected_items as $stock_id) {
            try {
                // Get stock item details
                $stmt = $conn->prepare("SELECT kode_barang FROM color_stock_items_surabaya WHERE id = ?");
                $stmt->bind_param("i", $stock_id);
                $stmt->execute();
                $result = $stmt->get_result();
                $item = $result->fetch_assoc();
                $stmt->close();
                
                if ($item && !empty($item['kode_barang'])) {
                    // Generate QR code with only code barang
                    $qr_code = generateQRCode($item['kode_barang']);
                    
                    // Update the item
                    $stmt = $conn->prepare("UPDATE color_stock_items_surabaya SET qr_code = ? WHERE id = ?");
                    $stmt->bind_param("si", $qr_code, $stock_id);
                    $stmt->execute();
                    $stmt->close();
                    
                    $generated_count++;
                    
                    // Log activity
                    log_activity($conn, $it_id, 'it', 'Bulk QR Generation', "IT user generated QR code for item ID: $stock_id");
                } else {
                    $error_count++;
                }
            } catch (Exception $e) {
                $error_count++;
                error_log("Error generating QR for item $stock_id: " . $e->getMessage());
            }
        }
        
        // Redirect with results
        header("Location: durasi_color_it.php?bulk_success=$generated_count&bulk_errors=$error_count&cache_bust=" . time());
        exit();
    } else {
        header("Location: durasi_color_it.php?error=no_items_selected");
        exit();
    }
}

// Process renewal request if submitted
if (isset($_POST['renew_item'])) {
    $stock_id = $_POST['stock_id'];
    
    // Get current stock item details
    $stmt = $conn->prepare("SELECT * FROM color_stock_items_surabaya WHERE id = ?");
    $stmt->bind_param("i", $stock_id);
    $stmt->execute();
    $item = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if (!$item) {
        header("Location: durasi_color_it.php?error=item_not_found");
        exit();
    }
    
    // Generate new code
    $stmt = $conn->prepare("SELECT MAX(CAST(SUBSTRING(kode_barang, 4) AS UNSIGNED)) as max_code FROM color_stock_items_surabaya");
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    $new_code_number = intval($result['max_code']) + 1;
    $new_code = 'CP.' . str_pad($new_code_number, 4, '0', STR_PAD_LEFT);
    $stmt->close();
    
    // Calculate new dates
    $current_date = date('Y-m-d');
    $expiry_date = date('Y-m-d', strtotime('+6 months', strtotime($current_date)));
    
    // Generate QR code with only new code barang
    $qr_code = generateQRCode($new_code);
    
    // Begin transaction
    $conn->begin_transaction();
    
    try {
        // Save the old item to history
        $stmt = $conn->prepare("INSERT INTO renew_code_history_surabaya 
                               (original_id, color_id, component_id, kode_barang, stock_number, status, lokasi, qr_code, tanggal_pembuatan, tanggal_kedaluwarsa, keterangan)
                               VALUES (?, ?, ?, ?, ?, 'Renew', ?, ?, ?, ?, ?)");
        $stmt->bind_param("iiiissssss", $item['id'], $item['color_id'], $item['component_id'], $item['kode_barang'], $item['stock_number'], 
                          $item['lokasi'], $item['qr_code'], $item['tanggal_pembuatan'], $item['tanggal_kedaluwarsa'], $item['keterangan']);
        $stmt->execute();
        $stmt->close();
        
        // Update the current item
        $stmt = $conn->prepare("UPDATE color_stock_items_surabaya 
                               SET kode_barang = ?, qr_code = ?, tanggal_pembuatan = ?, tanggal_kedaluwarsa = ?, status = 'Tersedia'
                               WHERE id = ?");
        $stmt->bind_param("ssssi", $new_code, $qr_code, $current_date, $expiry_date, $stock_id);
        $stmt->execute();
        $stmt->close();
        
        // Commit transaction
        $conn->commit();
        
        // Log activity
        log_activity($conn, $it_id, 'it', 'Renew Code', "IT user renewed code for item ID: $stock_id, New code: $new_code");
        
        // Redirect to prevent resubmission
        header("Location: durasi_color_it.php?success=1&cache_bust=" . time());
        exit();
        
    } catch (Exception $e) {
        // Rollback transaction
        $conn->rollback();
        header("Location: durasi_color_it.php?error=renewal_failed");
        exit();
    }
}

// Process status change from Rusak to Renew
if (isset($_POST['change_to_renew'])) {
    $stock_id = $_POST['stock_id'];
    
    // Get current stock item details
    $stmt = $conn->prepare("SELECT * FROM color_stock_items_surabaya WHERE id = ?");
    $stmt->bind_param("i", $stock_id);
    $stmt->execute();
    $item = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if (!$item) {
        header("Location: durasi_color_it.php?error=item_not_found");
        exit();
    }
    
    // Generate new code
    $stmt = $conn->prepare("SELECT MAX(CAST(SUBSTRING(kode_barang, 4) AS UNSIGNED)) as max_code FROM color_stock_items_surabaya");
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    $new_code_number = intval($result['max_code']) + 1;
    $new_code = 'CP.' . str_pad($new_code_number, 4, '0', STR_PAD_LEFT);
    $stmt->close();
    
    // Calculate new dates
    $current_date = date('Y-m-d');
    $expiry_date = date('Y-m-d', strtotime('+6 months', strtotime($current_date)));
    
    // Generate QR code with only new code barang
    $qr_code = generateQRCode($new_code);
    
    // Begin transaction
    $conn->begin_transaction();
    
    try {
        // Save the old item to history
        $stmt = $conn->prepare("INSERT INTO renew_code_history_surabaya 
                               (original_id, color_id, component_id, kode_barang, stock_number, status, lokasi, qr_code, tanggal_pembuatan, tanggal_kedaluwarsa, keterangan)
                               VALUES (?, ?, ?, ?, ?, 'Renew', ?, ?, ?, ?, ?)");
        $stmt->bind_param("iiiissssss", $item['id'], $item['color_id'], $item['component_id'], $item['kode_barang'], $item['stock_number'], 
                          $item['lokasi'], $item['qr_code'], $item['tanggal_pembuatan'], $item['tanggal_kedaluwarsa'], $item['keterangan']);
        $stmt->execute();
        $stmt->close();
        
        // Update the current item
        $stmt = $conn->prepare("UPDATE color_stock_items_surabaya 
                               SET kode_barang = ?, qr_code = ?, tanggal_pembuatan = ?, tanggal_kedaluwarsa = ?, status = 'Tersedia'
                               WHERE id = ?");
        $stmt->bind_param("ssssi", $new_code, $qr_code, $current_date, $expiry_date, $stock_id);
        $stmt->execute();
        $stmt->close();
        
        // Commit transaction
        $conn->commit();
        
        // Log activity
        log_activity($conn, $it_id, 'it', 'Changed From Rusak', "IT user changed status from Rusak to Tersedia for item ID: $stock_id, New code: $new_code");
        
        // Redirect to prevent resubmission
        header("Location: durasi_color_it.php?success=3&cache_bust=" . time());
        exit();
        
    } catch (Exception $e) {
        // Rollback transaction
        $conn->rollback();
        header("Location: durasi_color_it.php?error=status_change_failed");
        exit();
    }
}

// Generate QR code if requested
if (isset($_POST['generate_qr'])) {
    $stock_id = $_POST['stock_id'];
    
    // Get stock item details
    $stmt = $conn->prepare("SELECT kode_barang FROM color_stock_items_surabaya WHERE id = ?");
    $stmt->bind_param("i", $stock_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $item = $result->fetch_assoc();
    $stmt->close();
    
    if (!$item) {
        header("Location: durasi_color_it.php?error=item_not_found");
        exit();
    }
    
    // Generate QR code with only code barang
    $qr_code = generateQRCode($item['kode_barang']);
    
    // Update the item
    $stmt = $conn->prepare("UPDATE color_stock_items_surabaya SET qr_code = ? WHERE id = ?");
    $stmt->bind_param("si", $qr_code, $stock_id);
    $stmt->execute();
    $stmt->close();
    
    // Log activity
    log_activity($conn, $it_id, 'it', 'QR Code Generation', "IT user generated QR code for item ID: $stock_id");
    
    // Redirect to prevent resubmission
    header("Location: durasi_color_it.php?success=2&cache_bust=" . time());
    exit();
}

// Check for expired items and update status if needed
$current_date = date('Y-m-d');
$ten_days_from_now = date('Y-m-d', strtotime('+10 days'));

// Update to "Renew" status for items within 10 days of expiry
$stmt = $conn->prepare("UPDATE color_stock_items_surabaya 
                      SET status = 'Renew' 
                      WHERE tanggal_kedaluwarsa BETWEEN ? AND ? 
                      AND status = 'Tersedia'");
$stmt->bind_param("ss", $current_date, $ten_days_from_now);
$stmt->execute();
$stmt->close();

// Get items that are expired
$stmt = $conn->prepare("SELECT * FROM color_stock_items_surabaya WHERE tanggal_kedaluwarsa < ? AND status != 'Expired'");
$stmt->bind_param("s", $current_date);
$stmt->execute();
$expired_items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Process expired items
foreach ($expired_items as $item) {
    // Begin transaction for each expired item
    $conn->begin_transaction();
    
    try {
        // Save the old item to history
        $stmt = $conn->prepare("INSERT INTO expired_code_history_surabaya 
                              (original_id, color_id, component_id, kode_barang, stock_number, status, lokasi, qr_code, tanggal_pembuatan, tanggal_kedaluwarsa, keterangan)
                              VALUES (?, ?, ?, ?, ?, 'Expired', ?, ?, ?, ?, ?)");
        $stmt->bind_param("iiiissssss", $item['id'], $item['color_id'], $item['component_id'], $item['kode_barang'], $item['stock_number'], 
                         $item['lokasi'], $item['qr_code'], $item['tanggal_pembuatan'], $item['tanggal_kedaluwarsa'], $item['keterangan']);
        $stmt->execute();
        $stmt->close();
        
        // Generate new code
        $stmt = $conn->prepare("SELECT MAX(CAST(SUBSTRING(kode_barang, 4) AS UNSIGNED)) as max_code FROM color_stock_items_surabaya");
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $new_code_number = intval($result['max_code']) + 1;
        $new_code = 'CP.' . str_pad($new_code_number, 4, '0', STR_PAD_LEFT);
        $stmt->close();
        
        // Calculate new dates
        $new_date = date('Y-m-d');
        $new_expiry = date('Y-m-d', strtotime('+6 months', strtotime($new_date)));
        
        // Generate QR code with only new code barang
        $qr_code = generateQRCode($new_code);
        
        // Update the item
        $stmt = $conn->prepare("UPDATE color_stock_items_surabaya 
                              SET kode_barang = ?, status = 'Tersedia', tanggal_pembuatan = ?, tanggal_kedaluwarsa = ?, qr_code = ?
                              WHERE id = ?");
        $stmt->bind_param("ssssi", $new_code, $new_date, $new_expiry, $qr_code, $item['id']);
        $stmt->execute();
        $stmt->close();
        
        // Commit transaction
        $conn->commit();
        
        // Log activity
        log_activity($conn, $it_id, 'it', 'Expired Code Update', "System automatically updated expired item ID: {$item['id']}, New code: $new_code");
        
    } catch (Exception $e) {
        // Rollback transaction
        $conn->rollback();
        error_log("Error processing expired item {$item['id']}: " . $e->getMessage());
    }
}

// Include header
include '../template_it/header.php';
?>
<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-100">
    <!-- Notifications -->
    <?php if (isset($_GET['success']) && $_GET['success'] == 1): ?>
    <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-6" role="alert">
        <p class="font-bold">Sukses</p>
        <p>Code barang telah berhasil diperbaharui!</p>
    </div>
    <?php endif; ?>
    
    <?php if (isset($_GET['success']) && $_GET['success'] == 2): ?>
    <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-6" role="alert">
        <p class="font-bold">Sukses</p>
        <p>QR Code telah berhasil dibuat!</p>
    </div>
    <?php endif; ?>
    
    <?php if (isset($_GET['success']) && $_GET['success'] == 3): ?>
    <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-6" role="alert">
        <p class="font-bold">Sukses</p>
        <p>Status telah berhasil diubah dari Rusak dan code barang telah diperbaharui!</p>
    </div>
    <?php endif; ?>
    
    <!-- Bulk QR Generation Success -->
    <?php if (isset($_GET['bulk_success'])): ?>
    <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-6" role="alert">
        <p class="font-bold">Sukses Bulk QR Generation</p>
        <p>Berhasil membuat <?php echo $_GET['bulk_success']; ?> QR Code. 
        <?php if (isset($_GET['bulk_errors']) && $_GET['bulk_errors'] > 0): ?>
            Gagal: <?php echo $_GET['bulk_errors']; ?> item.
        <?php endif; ?>
        </p>
    </div>
    <?php endif; ?>
    
    <?php if (isset($_GET['error'])): ?>
    <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6" role="alert">
        <p class="font-bold">Error</p>
        <p>
            <?php 
            switch($_GET['error']) {
                case 'item_not_found':
                    echo 'Item tidak ditemukan!';
                    break;
                case 'renewal_failed':
                    echo 'Gagal memperbarui code barang!';
                    break;
                case 'status_change_failed':
                    echo 'Gagal mengubah status item!';
                    break;
                case 'no_items_selected':
                    echo 'Tidak ada item yang dipilih untuk generate QR code!';
                    break;
                default:
                    echo 'Terjadi kesalahan yang tidak diketahui!';
            }
            ?>
        </p>
    </div>
    <?php endif; ?>

    <!-- Color Duration Management Card -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold text-gray-800">Manajemen Durasi Warna</h2>
            
            <!-- Search and Filter Section -->
            <div class="flex space-x-4">
                <div>
                    <label for="codeSearch" class="block text-sm font-medium text-gray-700 mb-1">Cari Code Barang:</label>
                    <div class="relative">
                        <input type="text" id="codeSearch" 
                               class="border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm pl-10" 
                               placeholder="Masukkan code barang (ex: CP.0001)">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                            </svg>
                        </div>
                        <button id="clearSearch" class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600 hidden">
                            <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        </button>
                    </div>
                    <!-- Search Status Indicator -->
                    <div id="searchStatus" class="mt-1 text-sm text-gray-500 hidden">
                        <span id="searchResultCount"></span>
                    </div>
                </div>
                <div>
                    <label for="buyerFilter" class="block text-sm font-medium text-gray-700 mb-1">Filter Buyer:</label>
                    <select id="buyerFilter" class="border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm">
                        <option value="">Semua Buyer</option>
                        <?php
                        // Get all buyers_surabaya with error handling
                        try {
                            $buyer_query = "SELECT id, nama_buyer FROM buyers_surabaya ORDER BY nama_buyer";
                            $buyer_result = $conn->query($buyer_query);
                            
                            if ($buyer_result) {
                                while ($buyer = $buyer_result->fetch_assoc()) {
                                    $buyer_name = htmlspecialchars($buyer['nama_buyer'] ?? 'Unknown Buyer');
                                    echo '<option value="' . $buyer_name . '">' . $buyer_name . '</option>';
                                }
                            }
                        } catch (Exception $e) {
                            error_log("Error loading buyers_surabaya: " . $e->getMessage());
                        }
                        ?>
                    </select>
                </div>
                <div class="flex items-end">
                    <button id="refreshData" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center">
                        <svg class="h-5 w-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                        </svg>
                        Refresh
                    </button>
                </div>
            </div>
        </div>
        
        <!-- Bulk Actions Section -->
        <div class="bg-gray-50 rounded-lg p-4 mb-6">
            <div class="flex justify-between items-center">
                <div class="flex items-center space-x-4">
                    <h3 class="text-lg font-semibold text-gray-800">Aksi Bulk</h3>
                    <div class="text-sm text-gray-600">
                        <span id="selectedCount">0</span> item dipilih
                    </div>
                </div>
                <div class="flex items-center space-x-3">
                    <label class="flex items-center">
                        <input type="checkbox" id="selectAll" class="form-checkbox h-4 w-4 text-blue-600">
                        <span class="ml-2 text-sm text-gray-700">Pilih Semua (yang terlihat)</span>
                    </label>
                    <button id="bulkQRButton" 
                            class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center"
                            disabled>
                        <svg class="h-4 w-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                        </svg>
                        Generate QR Code Terpilih
                    </button>
                </div>
            </div>
            
            <!-- Progress Bar (hidden by default) -->
            <div id="bulkProgress" class="mt-4 hidden">
                <div class="bg-gray-200 rounded-full h-3">
                    <div id="progressBar" class="bg-blue-600 h-3 rounded-full transition-all duration-300" style="width: 0%"></div>
                </div>
                <div class="flex justify-between text-sm text-gray-600 mt-1">
                    <span id="progressText">Memproses...</span>
                    <span id="progressPercent">0%</span>
                </div>
            </div>
        </div>
        
        <!-- Search Results Notification -->
        <div id="searchNotification" class="hidden mb-4 p-4 bg-blue-50 border-l-4 border-blue-400">
            <div class="flex">
                <div class="flex-shrink-0">
                    <svg class="h-5 w-5 text-blue-400" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd"></path>
                    </svg>
                </div>
                <div class="ml-3">
                    <p class="text-sm text-blue-700" id="searchNotificationText"></p>
                </div>
            </div>
        </div>
        
        <!-- Color List -->
        <div class="overflow-x-auto">
            <table class="min-w-full bg-white border border-gray-200">
                <thead>
                    <tr>
                        <th class="px-4 py-3 border-b text-left text-sm font-medium text-gray-700 uppercase tracking-wider">No</th>
                        <th class="px-4 py-3 border-b text-left text-sm font-medium text-gray-700 uppercase tracking-wider">Buyer</th>
                        <th class="px-4 py-3 border-b text-left text-sm font-medium text-gray-700 uppercase tracking-wider">Color Code</th>
                        <th class="px-4 py-3 border-b text-left text-sm font-medium text-gray-700 uppercase tracking-wider">Deskripsi</th>
                        <th class="px-4 py-3 border-b text-left text-sm font-medium text-gray-700 uppercase tracking-wider">Aksi</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200" id="colorTableBody">
                    <?php
                    // Get color panel data with buyer information with better error handling
                    try {
                        $query = "SELECT mcp.id, mcp.code_color, mcp.deskripsi, mcp.status, mcp.kode_warna_hex, 
                                         COALESCE(b.nama_buyer, 'Unknown Buyer') as nama_buyer 
                                 FROM master_color_panel_surabaya mcp
                                 LEFT JOIN buyers_surabaya b ON mcp.buyer_id = b.id
                                 ORDER BY COALESCE(b.nama_buyer, 'Unknown Buyer'), mcp.code_color";
                        $result = $conn->query($query);
                        $i = 1;
                        
                        if ($result && $result->num_rows > 0) {
                            while ($row = $result->fetch_assoc()) {
                                // Color indicator class based on status
                                $statusClass = '';
                                switch ($row['status'] ?? 'Hijau') {
                                    case 'Hijau':
                                        $statusClass = 'bg-green-200 text-green-800';
                                        break;
                                    case 'Kuning':
                                        $statusClass = 'bg-yellow-200 text-yellow-800';
                                        break;
                                    case 'Merah':
                                        $statusClass = 'bg-red-200 text-red-800';
                                        break;
                                    default:
                                        $statusClass = 'bg-green-200 text-green-800';
                                }
                                
                                // Handle missing data
                                $color_code = htmlspecialchars($row['code_color'] ?? 'Unknown Color');
                                $buyer_name = htmlspecialchars($row['nama_buyer'] ?? 'Unknown Buyer');
                                $description = htmlspecialchars($row['deskripsi'] ?? '');
                                $hex_color = $row['kode_warna_hex'] ?? '#ffffff';
                    ?>
                    <tr class="hover:bg-gray-50 color-row" data-buyer="<?php echo $buyer_name; ?>" data-color-id="<?php echo $row['id']; ?>">
                        <td class="px-4 py-3 whitespace-nowrap"><?php echo $i++; ?></td>
                        <td class="px-4 py-3 whitespace-nowrap"><?php echo $buyer_name; ?></td>
                        <td class="px-4 py-3">
                            <button class="toggle-color-details flex items-center font-medium text-blue-600 hover:text-blue-900 cursor-pointer" 
                                    data-id="<?php echo $row['id']; ?>"
                                    data-color="<?php echo $color_code; ?>">
                                <i class="fas fa-chevron-right mr-2 transition-transform duration-200 expand-icon"></i>
                                <?php echo $color_code; ?>
                                <span class="ml-2 w-4 h-4 rounded-full" style="background-color: <?php echo $hex_color; ?>"></span>
                            </button>
                        </td>
                        <td class="px-4 py-3"><?php echo $description; ?></td>
                        <td class="px-4 py-3 text-right text-sm font-medium">
                            <span class="text-gray-400 text-sm">Klik Color Code untuk detail</span>
                        </td>
                    </tr>
                    <!-- Component Details Row (Hidden by default) -->
                    <tr class="component-details-row hidden" id="details-<?php echo $row['id']; ?>" data-color-id="<?php echo $row['id']; ?>">
                        <td colspan="5" class="px-0 py-0">
                            <div class="bg-gray-50 border-l-4 border-blue-500">
                                <div class="p-6">
                                    <div class="mb-4">
                                        <h4 class="text-lg font-semibold text-gray-800 mb-2">
                                            Detail Komponen - <?php echo $color_code; ?> 
                                            (<?php echo $buyer_name; ?>)
                                        </h4>
                                    </div>
                                    
                                    <!-- Loading indicator -->
                                    <div class="loading-indicator flex items-center justify-center py-8">
                                        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                                        <span class="ml-2 text-gray-600">Memuat data...</span>
                                    </div>
                                    
                                    <!-- Component details will be loaded here -->
                                    <div class="component-content hidden">
                                        <div class="overflow-x-auto">
                                            <table class="min-w-full divide-y divide-gray-300">
                                                <thead class="bg-gray-100">
                                                    <tr>
                                                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider">
                                                            <input type="checkbox" class="form-checkbox h-4 w-4 text-blue-600 select-all-color" 
                                                                   data-color-id="<?php echo $row['id']; ?>">
                                                        </th>
                                                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider">Component</th>
                                                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider">Code Barang</th>
                                                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider">Lokasi</th>
                                                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider">Rack No</th>
                                                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider">Tanggal Pembuatan</th>
                                                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider">Tanggal Kedaluwarsa</th>
                                                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider">Status</th>
                                                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider">QR Code</th>
                                                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider">Aksi</th>
                                                    </tr>
                                                </thead>
                                                <tbody class="component-list bg-white divide-y divide-gray-200">
                                                    <!-- Component data will be inserted here via JavaScript -->
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>
                    <?php 
                            }
                        } else {
                            // Show message when no data found
                            echo '<tr><td colspan="5" class="px-4 py-8 text-center text-gray-500">Tidak ada data warna yang ditemukan.</td></tr>';
                        }
                    } catch (Exception $e) {
                        error_log("Error loading color data: " . $e->getMessage());
                        echo '<tr><td colspan="5" class="px-4 py-8 text-center text-red-500">Terjadi kesalahan saat memuat data. Silakan refresh halaman.</td></tr>';
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<!-- Bulk QR Generation Form (Hidden) -->
<form id="bulkQRForm" method="post" class="hidden">
    <input type="hidden" name="generate_bulk_qr" value="1">
    <div id="selectedItemsContainer"></div>
</form>

<!-- QR Code Viewer Modal -->
<div id="qrModal" 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>
        
        <!-- Modal Content -->
        <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="mt-3 text-center sm:mt-0 sm:text-left w-full">
                        <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">QR Code</h3>
                        
                        <div class="flex flex-col items-center">
                            <div class="w-64 h-64 border border-gray-300 flex items-center justify-center mb-4" id="qrCodeImage">
                                <!-- QR Code will be inserted here -->
                            </div>
                            <div class="text-sm text-gray-600 mb-4" id="qrCodeInfo">
                                <!-- QR Code info will be inserted here -->
                            </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" 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-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm" id="closeQrModal">
                    Tutup
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Print Single Item Modal -->
<div id="printSingleModal" 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>
        
        <!-- Modal Content -->
        <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-2xl 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="mt-3 text-center sm:mt-0 sm:text-left w-full" id="printSingleContent">
                        <div class="flex justify-between items-center mb-6 print-header">
                            <h3 class="text-lg leading-6 font-medium text-gray-900">Print Preview</h3>
                            <div>
                                <button id="printSingleItemBtn" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md flex items-center">
                                    <i class="fas fa-print mr-2"></i> Cetak
                                </button>
                            </div>
                        </div>
                        
                        <div id="singleItemContent" class="flex flex-col items-center">
                            <!-- Content will be populated via JavaScript -->
                        </div>

                        <div class="mt-8">
                            <div class="flex justify-between">
                                <div class="w-1/3 text-center">
                                    <p>K.A Unit</p>
                                    <div class="h-16"></div>
                                    <p>____________</p>
                                    <p>Y Andi S</p>
                                </div>
                                <div class="w-1/3 text-center">
                                    <p>Color Panel</p>
                                    <div class="h-16"></div>
                                    <p>____________</p>
                                    <p>Alifi A.U</p>
                                </div>
                                <div class="w-1/3 text-center">
                                    <p>Akzonobel</p>
                                    <div class="h-16"></div>
                                    <p>____________</p>
                                    <p>Asmari</p>
                                </div>
                            </div>
                        </div>
                        <div class="mt-8">
                            <div class="flex justify-between">
                                <div class="w-1/3 text-center">
                                    <p>Approved by</p>
                                    <div class="h-16"></div>
                                    <p>____________</p>
                                    <p>Eris</p>
                                </div>
                                <div class="w-1/3 text-center">
                                    <p>Approved by QC</p>
                                    <div class="h-16"></div>
                                    <p>____________</p>
                                    <p>Suhari yanto</p>
                                </div>
                                <div class="w-1/3 text-center">
                                    <p>Approved by</p>
                                    <div class="h-16"></div>
                                    <p>____________</p>
                                    <p>QC Buyer</p>
                                </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" 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-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm" id="closePrintSingleModal">
                    Tutup
                </button>
            </div>
        </div>
    </div>
</div>
<style>
@media print {
    .print-header {
        display: none !important;
    }
    
    /* Hide header di dalam content area saat print */
    .print-only-header {
        display: none !important;
    }
    
    /* Ensure proper page setup for PDF */
    @page {
        margin: 1cm;
        size: A4;
    }
    
    body {
        print-color-adjust: exact;
        -webkit-print-color-adjust: exact;
    }
    
    /* Hide unnecessary elements during print */
    .no-print {
        display: none !important;
    }
}

.expand-icon.rotated {
    transform: rotate(90deg);
}

.component-details-row {
    animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}

.loading-indicator {
    animation: pulse 1.5s ease-in-out infinite;
}

/* Search highlight styles */
.search-highlight {
    background-color: #fef08a !important;
    border: 2px solid #f59e0b !important;
}

.search-match-found {
    background-color: #dcfce7 !important;
    border-left: 4px solid #16a34a !important;
}

/* Search input focus styles */
#codeSearch:focus {
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    border-color: #3b82f6;
}

/* Refresh button animation */
#refreshData.loading svg {
    animation: spin 1s linear infinite;
}

@keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

/* Error states */
.error-state {
    background-color: #fef2f2;
    border: 1px solid #fecaca;
    color: #dc2626;
}

.no-data-state {
    background-color: #f8fafc;
    border: 1px solid #e2e8f0;
    color: #64748b;
}

/* Bulk action styles */
.bulk-actions-section {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border: 1px solid #e2e8f0;
    border-radius: 0.75rem;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.bulk-actions-section:hover {
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.3s ease;
}

/* Checkbox styles */
.form-checkbox {
    appearance: none;
    background-color: #fff;
    border: 2px solid #d1d5db;
    border-radius: 0.25rem;
    color: #3b82f6;
    display: inline-block;
    position: relative;
    transition: background-color 0.2s, border-color 0.2s;
}

.form-checkbox:checked {
    background-color: #3b82f6;
    border-color: #3b82f6;
}

.form-checkbox:checked::before {
    content: '\2713';
    color: white;
    font-size: 0.75rem;
    font-weight: bold;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.form-checkbox:focus {
    outline: none;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-checkbox:hover {
    border-color: #3b82f6;
}

/* Selected row highlighting */
.row-selected {
    background-color: #dbeafe !important;
    border-left: 4px solid #3b82f6 !important;
}

.row-selected:hover {
    background-color: #bfdbfe !important;
}

/* Progress bar styles */
.progress-container {
    background-color: #f3f4f6;
    border-radius: 9999px;
    height: 0.75rem;
    overflow: hidden;
    position: relative;
}

.progress-bar {
    background: linear-gradient(90deg, #10b981 0%, #059669 100%);
    height: 100%;
    transition: width 0.3s ease;
    border-radius: 9999px;
    position: relative;
}

.progress-bar::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.3) 50%, transparent 100%);
    animation: shimmer 2s infinite;
}

@keyframes shimmer {
    0% { transform: translateX(-100%); }
    100% { transform: translateX(100%); }
}

/* Progress text animation */
.progress-text {
    animation: progressPulse 1.5s ease-in-out infinite;
}

@keyframes progressPulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.6; }
}

/* Bulk button states */
#bulkQRButton:disabled {
    background-color: #9ca3af;
    cursor: not-allowed;
    transform: none;
}

#bulkQRButton:not(:disabled):hover {
    background-color: #059669;
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    transition: all 0.2s ease;
}

#bulkQRButton:not(:disabled):active {
    transform: translateY(0);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* Loading state for bulk button */
#bulkQRButton.loading {
    position: relative;
    color: transparent;
}

#bulkQRButton.loading::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 16px;
    height: 16px;
    margin: -8px 0 0 -8px;
    border: 2px solid #ffffff;
    border-radius: 50%;
    border-top-color: transparent;
    animation: spin 1s linear infinite;
}

/* Selected count badge */
.selected-count {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    color: white;
    padding: 0.25rem 0.75rem;
    border-radius: 9999px;
    font-weight: 600;
    font-size: 0.875rem;
    box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
}

.selected-count.zero {
    background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
    box-shadow: 0 2px 4px rgba(107, 114, 128, 0.3);
}

/* Enhanced table styles */
.component-table {
    border-collapse: separate;
    border-spacing: 0;
    border-radius: 0.5rem;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.component-table th {
    background: linear-gradient(135deg, #f9fafb 0%, #f3f4f6 100%);
    border-bottom: 2px solid #e5e7eb;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    font-size: 0.75rem;
}

.component-table td {
    border-bottom: 1px solid #f3f4f6;
    transition: background-color 0.2s ease;
}

.component-table tr:hover td {
    background-color: #f8fafc;
}

/* QR Code modal enhancements */
#qrModal .modal-content {
    backdrop-filter: blur(4px);
    background-color: rgba(255, 255, 255, 0.95);
}

#qrCodeImage {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border: 2px dashed #d1d5db;
    border-radius: 0.5rem;
    transition: border-color 0.3s ease;
}

#qrCodeImage:hover {
    border-color: #3b82f6;
}

/* Print modal enhancements */
#printSingleModal .modal-content {
    max-height: 90vh;
    overflow-y: auto;
}

/* Notification enhancements */
.notification {
    border-radius: 0.5rem;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    animation: slideInFromTop 0.3s ease-out;
}

@keyframes slideInFromTop {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* Status badge improvements */
.status-badge {
    font-weight: 600;
    font-size: 0.75rem;
    padding: 0.25rem 0.75rem;
    border-radius: 9999px;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.status-tersedia {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
}

.status-dipinjam {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    color: white;
}

.status-rusak {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: white;
}

.status-expired {
    background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
    color: white;
}

.status-renew {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    color: white;
}

.status-hilang {
    background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
    color: white;
}

/* Action button improvements */
.action-button {
    font-size: 0.75rem;
    padding: 0.375rem 0.75rem;
    border-radius: 0.375rem;
    font-weight: 600;
    transition: all 0.2s ease;
    border: none;
    cursor: pointer;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.action-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.action-button:active {
    transform: translateY(0);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-button.primary {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    color: white;
}

.action-button.success {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
}

.action-button.warning {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    color: white;
}

.action-button.danger {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: white;
}

/* Search enhancements */
#codeSearch {
    transition: all 0.3s ease;
    border-radius: 0.5rem;
}

#codeSearch:focus {
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    transform: scale(1.02);
}

#clearSearch {
    transition: all 0.2s ease;
}

#clearSearch:hover {
    color: #ef4444;
    transform: scale(1.1);
}

/* Filter enhancements */
#buyerFilter {
    transition: all 0.3s ease;
    border-radius: 0.5rem;
}

#buyerFilter:focus {
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* Responsive improvements */
@media (max-width: 768px) {
    .bulk-actions-section {
        flex-direction: column;
        gap: 1rem;
    }
    
    .bulk-actions-section .flex {
        flex-direction: column;
        align-items: stretch;
    }
    
    #bulkQRButton {
        width: 100%;
        justify-content: center;
    }
    
    .component-table {
        font-size: 0.875rem;
    }
    
    .component-table th,
    .component-table td {
        padding: 0.5rem;
    }
}

@media (max-width: 640px) {
    .search-filter-section {
        flex-direction: column;
        gap: 1rem;
    }
    
    .search-filter-section > div {
        width: 100%;
    }
}

/* Accessibility improvements */
.form-checkbox:focus-visible {
    outline: 2px solid #3b82f6;
    outline-offset: 2px;
}

button:focus-visible {
    outline: 2px solid #3b82f6;
    outline-offset: 2px;
}

/* High contrast mode support */
@media (prefers-contrast: high) {
    .form-checkbox {
        border-width: 3px;
    }
    
    .status-badge {
        border: 2px solid currentColor;
    }
    
    .action-button {
        border: 2px solid currentColor;
    }
}

/* Reduced motion support */
@media (prefers-reduced-motion: reduce) {
    * {
        animation-duration: 0.01ms !important;
        animation-iteration-count: 1 !important;
        transition-duration: 0.01ms !important;
    }
}

/* Dark mode support (if needed in future) */
@media (prefers-color-scheme: dark) {
    .bulk-actions-section {
        background: linear-gradient(135deg, #1f2937 0%, #111827 100%);
        border-color: #374151;
    }
    
    .form-checkbox {
        background-color: #374151;
        border-color: #6b7280;
    }
    
    .component-table th {
        background: linear-gradient(135deg, #374151 0%, #1f2937 100%);
        border-color: #4b5563;
        color: #f9fafb;
    }
    
    .component-table td {
        border-color: #374151;
    }
    
    .component-table tr:hover td {
        background-color: #374151;
    }
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Cache DOM elements
    const qrModal = document.getElementById('qrModal');
    const closeQrModalBtn = document.getElementById('closeQrModal');
    const qrCodeImage = document.getElementById('qrCodeImage');
    const qrCodeInfo = document.getElementById('qrCodeInfo');
    const printSingleModal = document.getElementById('printSingleModal');
    const closePrintSingleModalBtn = document.getElementById('closePrintSingleModal');
    const printSingleItemBtn = document.getElementById('printSingleItemBtn');
    const singleItemContent = document.getElementById('singleItemContent');
    const buyerFilter = document.getElementById('buyerFilter');
    const codeSearch = document.getElementById('codeSearch');
    const clearSearch = document.getElementById('clearSearch');
    const searchStatus = document.getElementById('searchStatus');
    const searchResultCount = document.getElementById('searchResultCount');
    const searchNotification = document.getElementById('searchNotification');
    const searchNotificationText = document.getElementById('searchNotificationText');
    const refreshDataBtn = document.getElementById('refreshData');
    
    // Bulk action elements
    const selectAllCheckbox = document.getElementById('selectAll');
    const bulkQRButton = document.getElementById('bulkQRButton');
    const selectedCount = document.getElementById('selectedCount');
    const bulkQRForm = document.getElementById('bulkQRForm');
    const selectedItemsContainer = document.getElementById('selectedItemsContainer');
    const bulkProgress = document.getElementById('bulkProgress');
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    const progressPercent = document.getElementById('progressPercent');
    
    // Track which details are currently open
    let openDetails = new Set();
    let searchResults = new Map(); // Map untuk menyimpan hasil pencarian
    let isSearchActive = false;
    let componentDataCache = new Map(); // Cache untuk data komponen
    let selectedItems = new Set(); // Track selected items for bulk actions
    
    // Global variable untuk data print
    let currentPrintData = {};

    // Bulk action functionality
    function updateSelectedCount() {
        const count = selectedItems.size;
        if (selectedCount) {
            selectedCount.textContent = count;
            selectedCount.className = count > 0 ? 'selected-count' : 'selected-count zero';
        }
        
        if (bulkQRButton) {
            bulkQRButton.disabled = count === 0;
            if (count === 0) {
                bulkQRButton.classList.add('disabled');
            } else {
                bulkQRButton.classList.remove('disabled');
            }
        }
        
        // Update select all checkbox state
        updateSelectAllState();
    }

    function updateSelectAllState() {
        if (!selectAllCheckbox) return;
        
        const visibleCheckboxes = document.querySelectorAll('.item-checkbox:not([style*="display: none"])');
        const checkedVisible = Array.from(visibleCheckboxes).filter(cb => cb.checked);
        
        if (visibleCheckboxes.length === 0) {
            selectAllCheckbox.indeterminate = false;
            selectAllCheckbox.checked = false;
        } else if (checkedVisible.length === visibleCheckboxes.length) {
            selectAllCheckbox.indeterminate = false;
            selectAllCheckbox.checked = true;
        } else if (checkedVisible.length > 0) {
            selectAllCheckbox.indeterminate = true;
            selectAllCheckbox.checked = false;
        } else {
            selectAllCheckbox.indeterminate = false;
            selectAllCheckbox.checked = false;
        }
    }

    // Select all functionality
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            const visibleCheckboxes = document.querySelectorAll('.item-checkbox:not([style*="display: none"])');
            const shouldCheck = this.checked;
            
            visibleCheckboxes.forEach(checkbox => {
                const itemId = parseInt(checkbox.value);
                if (shouldCheck) {
                    checkbox.checked = true;
                    selectedItems.add(itemId);
                    checkbox.closest('tr')?.classList.add('row-selected');
                } else {
                    checkbox.checked = false;
                    selectedItems.delete(itemId);
                    checkbox.closest('tr')?.classList.remove('row-selected');
                }
            });
            
            updateSelectedCount();
        });
    }

    // Individual checkbox handling
    function handleItemCheckboxChange(checkbox) {
        const itemId = parseInt(checkbox.value);
        if (checkbox.checked) {
            selectedItems.add(itemId);
            checkbox.closest('tr')?.classList.add('row-selected');
        } else {
            selectedItems.delete(itemId);
            checkbox.closest('tr')?.classList.remove('row-selected');
        }
        updateSelectedCount();
    }

    // Color-level select all functionality
    function handleColorSelectAll(checkbox) {
        const colorId = checkbox.dataset.colorId;
        const colorCheckboxes = document.querySelectorAll(`tr[data-color-id="${colorId}"] .item-checkbox`);
        const shouldCheck = checkbox.checked;
        
        colorCheckboxes.forEach(cb => {
            const itemId = parseInt(cb.value);
            if (shouldCheck) {
                cb.checked = true;
                selectedItems.add(itemId);
                cb.closest('tr')?.classList.add('row-selected');
            } else {
                cb.checked = false;
                selectedItems.delete(itemId);
                cb.closest('tr')?.classList.remove('row-selected');
            }
        });
        
        updateSelectedCount();
    }

    // Bulk QR generation
    if (bulkQRButton) {
        bulkQRButton.addEventListener('click', function() {
            if (selectedItems.size === 0) return;
            
            // Show confirmation dialog
            const confirmMessage = `Apakah Anda yakin ingin membuat QR Code untuk ${selectedItems.size} item terpilih?`;
            if (!confirm(confirmMessage)) return;
            
            // Prepare form data
            selectedItemsContainer.innerHTML = '';
            selectedItems.forEach(itemId => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'selected_items[]';
                input.value = itemId;
                selectedItemsContainer.appendChild(input);
            });
            
            // Show progress
            showBulkProgress();
            
            // Submit form
            bulkQRForm.submit();
        });
    }

    function showBulkProgress() {
        if (bulkProgress) {
            bulkProgress.classList.remove('hidden');
            bulkQRButton.classList.add('loading');
            bulkQRButton.disabled = true;
            
            // Simulate progress (since we're doing server-side processing)
            let progress = 0;
            const total = selectedItems.size;
            const interval = setInterval(() => {
                progress += Math.random() * 15;
                if (progress > 90) progress = 90;
                
                const percent = Math.round(progress);
                progressBar.style.width = percent + '%';
                progressPercent.textContent = percent + '%';
                progressText.textContent = `Memproses ${Math.floor((progress / 100) * total)}/${total} item...`;
                
                if (progress >= 90) {
                    clearInterval(interval);
                    progressText.textContent = 'Menyelesaikan...';
                }
            }, 200);
        }
    }

    // Refresh data functionality
    refreshDataBtn.addEventListener('click', function() {
        this.classList.add('loading');
        
        // Clear all caches and selections
        componentDataCache.clear();
        searchResults.clear();
        openDetails.clear();
        selectedItems.clear();
        
        // Clear search
        codeSearch.value = '';
        buyerFilter.value = '';
        clearSearchResults();
        
        // Close all open details
        closeAllDetails();
        
        // Add cache busting parameter and reload
        const currentUrl = window.location.href.split('?')[0];
        const cacheBust = Date.now();
        window.location.href = `${currentUrl}?cache_bust=${cacheBust}`;
    });

    // Search functionality with debouncing
    let searchTimeout;
    codeSearch.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        const searchTerm = this.value.trim().toUpperCase();
        
        searchTimeout = setTimeout(() => {
            if (searchTerm.length === 0) {
                // Clear search
                clearSearchResults();
                clearSearch.classList.add('hidden');
                isSearchActive = false;
            } else {
                // Perform search
                performSearch(searchTerm);
                clearSearch.classList.remove('hidden');
                isSearchActive = true;
            }
        }, 300); // 300ms debounce
    });

    // Clear search functionality
    clearSearch.addEventListener('click', function() {
        codeSearch.value = '';
        clearSearchResults();
        this.classList.add('hidden');
        isSearchActive = false;
        codeSearch.focus();
    });

    // Enhanced buyer filter that works with search
    buyerFilter.addEventListener('change', function() {
        if (isSearchActive) {
            // If search is active, re-perform search with current filter
            const searchTerm = codeSearch.value.trim().toUpperCase();
            if (searchTerm.length > 0) {
                performSearch(searchTerm);
            }
        } else {
            // Normal filter behavior
            applyBuyerFilter();
        }
    });

    function performSearch(searchTerm) {
        searchResults.clear();
        
        // Show loading state
        searchStatus.classList.remove('hidden');
        searchResultCount.textContent = 'Mencari...';
        
        // Search through all code barang using API with cache busting
        const cacheBust = Date.now();
        searchCodeBarang(searchTerm, cacheBust).then(results => {
            if (results && results.length > 0) {
                displaySearchResults(results, searchTerm);
            } else {
                showNoResults(searchTerm);
            }
        }).catch(error => {
            console.error('Search error:', error);
            showSearchError();
        });
    }

    async function searchCodeBarang(searchTerm, cacheBust = null) {
        try {
            let url = `../api/search_code_barang.php?search=${encodeURIComponent(searchTerm)}`;
            if (cacheBust) {
                url += `&cb=${cacheBust}`;
            }
            
            const response = await fetch(url, {
                cache: 'no-cache',
                headers: {
                    'Cache-Control': 'no-cache',
                    'Pragma': 'no-cache'
                }
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            
            // Handle both success and failure cases properly
            if (data.success) {
                return data.results || [];
            } else {
                console.error('API error:', data.error || 'Unknown error');
                return [];
            }
        } catch (error) {
            console.error('Fetch error:', error);
            return [];
        }
    }

    function displaySearchResults(results, searchTerm) {
        // First, hide all rows and close all details
        hideAllRows();
        closeAllDetails();
        
        // Apply buyer filter if active
        const selectedBuyer = buyerFilter.value;
        let filteredResults = results;
        
        if (selectedBuyer) {
            filteredResults = results.filter(result => 
                (result.buyer_name || 'Unknown Buyer') === selectedBuyer
            );
        }
        
        if (filteredResults.length === 0 && selectedBuyer) {
            showNoResults(searchTerm, true);
            return;
        }
        
        // Group results by color_id
        const groupedResults = {};
        filteredResults.forEach(result => {
            const colorId = result.color_id;
            if (colorId && !groupedResults[colorId]) {
                groupedResults[colorId] = [];
            }
            if (colorId) {
                groupedResults[colorId].push(result);
            }
        });
        
        // Store search results
        searchResults = new Map(Object.entries(groupedResults));
        
        // Show relevant color rows and auto-open their details
        let totalItems = 0;
        searchResults.forEach((items, colorId) => {
            const colorRow = document.querySelector(`.color-row[data-color-id="${colorId}"]`);
            if (colorRow) {
                colorRow.style.display = '';
                // Auto-open details for this color
                autoOpenColorDetails(colorId, items, searchTerm);
                totalItems += items.length;
            }
        });
        
        // Update search status
        updateSearchStatus(totalItems, searchTerm);
        showSearchNotification(totalItems, filteredResults.length, searchTerm);
    }

    function autoOpenColorDetails(colorId, items, searchTerm) {
        const detailRow = document.getElementById(`details-${colorId}`);
        const toggleButton = document.querySelector(`[data-id="${colorId}"]`);
        const expandIcon = toggleButton ? toggleButton.querySelector('.expand-icon') : null;
        
        if (detailRow && toggleButton && expandIcon) {
            // Show details
            detailRow.classList.remove('hidden');
            detailRow.style.display = '';
            expandIcon.classList.add('rotated');
            openDetails.add(colorId);
            
            // Clear cache for this color to ensure fresh data
            componentDataCache.delete(colorId);
            
            // Load component details with search highlighting
            fetchColorDetailsWithSearch(colorId, detailRow, items, searchTerm);
            detailRow.dataset.loaded = 'true';
        }
    }

    function fetchColorDetailsWithSearch(colorId, detailRow, searchItems, searchTerm) {
        const loadingIndicator = detailRow.querySelector('.loading-indicator');
        const componentContent = detailRow.querySelector('.component-content');
        const componentList = detailRow.querySelector('.component-list');
        
        // Show loading
        loadingIndicator.classList.remove('hidden');
        componentContent.classList.add('hidden');
        
        // Add cache busting to ensure fresh data
        const cacheBust = Date.now();
        const url = `../api/get_color_components_surabaya.php?color_id=${colorId}&cb=${cacheBust}`;
        
        fetch(url, {
            cache: 'no-cache',
            headers: {
                'Cache-Control': 'no-cache',
                'Pragma': 'no-cache'
            }
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                // Handle both successful and failed responses
                if (data.success === false) {
                    throw new Error(data.message || data.error || 'API returned error');
                }
                
                loadingIndicator.classList.add('hidden');
                componentContent.classList.remove('hidden');
                componentList.innerHTML = '';
                
                // Handle case where components array might be empty
                const components = data.components || [];
                
                if (components.length === 0) {
                    componentList.innerHTML = '<tr><td colspan="10" class="px-4 py-8 text-center text-gray-500 no-data-state">Tidak ada komponen ditemukan untuk warna ini.</td></tr>';
                } else {
                    // Create a set of matching code barang for highlighting
                    const matchingCodes = new Set(searchItems.map(item => item.kode_barang));
                    
                    // Cache the data
                    componentDataCache.set(colorId, data);
                    
                    components.forEach(component => {
                        const isMatch = matchingCodes.has(component.kode_barang);
                        const row = createComponentRow(component, data, isMatch, searchTerm);
                        componentList.appendChild(row);
                    });
                }
                
                // Add event listeners for newly created elements
                addEventListenersToNewElements(detailRow);
            })
            .catch(error => {
                console.error('Error fetching color details:', error);
                loadingIndicator.classList.add('hidden');
                componentContent.classList.remove('hidden');
                componentList.innerHTML = `<tr><td colspan="10" class="px-4 py-8 text-center text-red-500 error-state">
                    Terjadi kesalahan saat mengambil data: ${error.message}. 
                    <button class="text-blue-500 underline ml-2" onclick="location.reload()">Refresh Halaman</button>
                </td></tr>`;
            });
    }

    function createComponentRow(component, data, isMatch, searchTerm) {
        const today = new Date();
        let expiryDate = null;
        let daysDiff = null;
        
        // Handle expiry date safely
        if (component.tanggal_kedaluwarsa) {
            try {
                expiryDate = new Date(component.tanggal_kedaluwarsa);
                daysDiff = Math.ceil((expiryDate - today) / (1000 * 60 * 60 * 24));
            } catch (e) {
                console.warn('Invalid expiry date:', component.tanggal_kedaluwarsa);
            }
        }
        
        let statusClass = '';
        let statusText = component.status || 'Unknown';
        
        switch (statusText) {
            case 'Tersedia':
                statusClass = 'status-tersedia';
                break;
            case 'Dipinjam':
                statusClass = 'status-dipinjam';
                break;
            case 'Rusak':
                statusClass = 'status-rusak';
                break;
            case 'Expired':
                statusClass = 'status-expired';
                break;
            case 'Renew':
                statusClass = 'status-renew';
                break;
            case 'Hilang':
                statusClass = 'status-hilang';
                break;
            default:
                statusClass = 'bg-gray-100 text-gray-800';
        }
        
        const row = document.createElement('tr');
        row.className = `hover:bg-gray-50 ${isMatch ? 'search-match-found' : ''}`;
        
        // Highlight code barang if it matches search
        let codeBarangDisplay = component.kode_barang || 'N/A';
        if (isMatch && searchTerm) {
            try {
                const regex = new RegExp(`(${searchTerm})`, 'gi');
                codeBarangDisplay = codeBarangDisplay.replace(regex, '<mark class="bg-yellow-300 px-1 rounded">$1</mark>');
            } catch (e) {
                console.warn('Regex error:', e);
                // Fallback to simple replace
                codeBarangDisplay = codeBarangDisplay.replace(new RegExp(searchTerm, 'gi'), `<mark class="bg-yellow-300 px-1 rounded">${searchTerm}</mark>`);
            }
        }
        
        // Safe data access with defaults
        const componentName = component.component_name || 'Unknown Component';
        const location = component.lokasi || '-';
        const rackNo = component.rack_no || '-';
        const creationDate = component.tanggal_pembuatan || '-';
        const expiryDateStr = component.tanggal_kedaluwarsa || '-';
        const buyerName = data.buyer_name || 'Unknown Buyer';
        const colorCode = data.color_code || 'Unknown Color';
        
        row.innerHTML = `
            <td class="px-4 py-3 whitespace-nowrap text-sm">
                <input type="checkbox" class="form-checkbox h-4 w-4 text-blue-600 item-checkbox" 
                       value="${component.id || ''}" 
                       ${selectedItems.has(parseInt(component.id)) ? 'checked' : ''}>
            </td>
            <td class="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900">
                ${componentName}
            </td>
            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500 ${isMatch ? 'search-highlight' : ''}">
                ${codeBarangDisplay}
            </td>
            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                ${location}
            </td>
            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                ${rackNo}
            </td>
            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                ${creationDate}
            </td>
            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                ${expiryDateStr}
                ${daysDiff !== null && daysDiff > 0 && daysDiff <= 10 ? 
                    `<span class="ml-2 px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800">
                        ${daysDiff} hari lagi
                    </span>` : ''}
            </td>
            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                <span class="status-badge ${statusClass}">
                    ${statusText}
                </span>
            </td>
            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                ${component.qr_code ? 
                    `<button class="view-qr-code action-button primary" 
                            data-qr="${encodeURIComponent(component.qr_code)}"
                            data-code="${component.kode_barang || 'N/A'}"
                            data-info="Code Barang: ${component.kode_barang || 'N/A'}
Buyer: ${buyerName}
Component: ${componentName}
Color Code: ${colorCode}
Location: ${location}
Rack No: ${rackNo}
Tanggal: ${creationDate} - ${expiryDateStr}">
                        Lihat QR
                    </button>` : 
                    `<form method="post" class="inline">
                        <input type="hidden" name="stock_id" value="${component.id || ''}">
                        <button type="submit" name="generate_qr" class="action-button success">
                            Buat QR Code
                        </button>
                    </form>`
                }
            </td>
            <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
                <div class="flex flex-col space-y-2">
                    <button class="print-single-item action-button primary"
                        data-buyer="${buyerName}"
                        data-color="${colorCode}"
                        data-component="${componentName}"
                        data-code="${component.kode_barang || 'N/A'}"
                        data-lokasi="${location}"
                        data-rack="${rackNo}"
                        data-tanggal="${creationDate} - ${expiryDateStr}"
                        data-status="${statusText}"
                        data-qr="${component.qr_code ? encodeURIComponent(component.qr_code) : ''}">
                        Cetak
                    </button>
                    
                    ${statusText === 'Renew' ? 
                        `<form method="post" class="inline">
                            <input type="hidden" name="stock_id" value="${component.id || ''}">
                            <button type="submit" name="renew_item" class="action-button warning">
                                Jalankan
                            </button>
                        </form>` : 
                        ''
                    }
                    
                    ${statusText === 'Rusak' ? 
                        `<form method="post" class="inline">
                            <input type="hidden" name="stock_id" value="${component.id || ''}">
                            <button type="submit" name="change_to_renew" class="action-button danger">
                                Ubah ke Baru
                            </button>
                        </form>` : 
                        ''
                    }
                </div>
            </td>
        `;
        
        return row;
    }

    function hideAllRows() {
        const colorRows = document.querySelectorAll('.color-row');
        colorRows.forEach(row => {
            if (row) row.style.display = 'none';
        });
        const detailRows = document.querySelectorAll('.component-details-row');
        detailRows.forEach(row => {
            if (row) row.style.display = 'none';
        });
    }

    function showAllRows() {
        const colorRows = document.querySelectorAll('.color-row');
        colorRows.forEach(row => {
            if (row) row.style.display = '';
        });
    }

    function closeAllDetails() {
        openDetails.clear();
        const expandIcons = document.querySelectorAll('.expand-icon');
        expandIcons.forEach(icon => {
            if (icon) icon.classList.remove('rotated');
        });
        const detailRows = document.querySelectorAll('.component-details-row');
        detailRows.forEach(detailRow => {
            if (detailRow) {
                detailRow.classList.add('hidden');
                detailRow.dataset.loaded = 'false';
            }
        });
    }

    function clearSearchResults() {
        searchResults.clear();
        showAllRows();
        closeAllDetails();
        
        if (searchStatus) searchStatus.classList.add('hidden');
        if (searchNotification) searchNotification.classList.add('hidden');
        
        // Apply current buyer filter
        applyBuyerFilter();
        
        // Remove search highlights
        const highlights = document.querySelectorAll('.search-highlight, .search-match-found');
        highlights.forEach(el => {
            if (el) {
                el.classList.remove('search-highlight', 'search-match-found');
            }
        });
        
        // Update bulk selection state
        updateSelectAllState();
    }

    function applyBuyerFilter() {
        const selectedBuyer = buyerFilter ? buyerFilter.value : '';
        
        const colorRows = document.querySelectorAll('.color-row');
        colorRows.forEach(row => {
            if (!row) return;
            
            const rowBuyer = row.getAttribute('data-buyer') || '';
            if (selectedBuyer === '' || rowBuyer === selectedBuyer) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
        
        const detailRows = document.querySelectorAll('.component-details-row');
        detailRows.forEach(detailRow => {
            if (!detailRow) return;
            
            const colorId = detailRow.getAttribute('data-color-id');
            const colorRow = document.querySelector(`.color-row[data-color-id="${colorId}"]`);
            
            if (colorRow) {
                const rowBuyer = colorRow.getAttribute('data-buyer') || '';
                
                if (selectedBuyer === '' || rowBuyer === selectedBuyer) {
                    if (openDetails.has(colorId)) {
                        detailRow.style.display = '';
                    } else {
                        detailRow.style.display = 'none';
                    }
                } else {
                    detailRow.style.display = 'none';
                }
            }
        });
        
        // Update bulk selection state after filter
        updateSelectAllState();
    }

    function updateSearchStatus(count, searchTerm) {
        if (searchResultCount) {
            searchResultCount.textContent = `Ditemukan ${count} code barang yang cocok dengan "${searchTerm}"`;
        }
        if (searchStatus) {
            searchStatus.classList.remove('hidden');
        }
    }

    function showSearchNotification(totalItems, totalResults, searchTerm) {
        if (searchNotificationText) {
            searchNotificationText.textContent = `Pencarian untuk "${searchTerm}" menemukan ${totalItems} item. Detail otomatis dibuka.`;
        }
        if (searchNotification) {
            searchNotification.classList.remove('hidden');
        }
    }

    function showNoResults(searchTerm, filteredByBuyer = false) {
        hideAllRows();
        const message = filteredByBuyer ? 
            `Tidak ditemukan code barang "${searchTerm}" untuk buyer yang dipilih.` :
            `Tidak ditemukan code barang yang cocok dengan "${searchTerm}".`;
        
        if (searchResultCount) {
            searchResultCount.textContent = message;
        }
        if (searchStatus) {
            searchStatus.classList.remove('hidden');
        }
        if (searchNotificationText) {
            searchNotificationText.textContent = message;
        }
        if (searchNotification) {
            searchNotification.classList.remove('hidden');
        }
    }

    function showSearchError() {
        if (searchResultCount) {
            searchResultCount.textContent = 'Terjadi kesalahan saat melakukan pencarian.';
        }
        if (searchStatus) {
            searchStatus.classList.remove('hidden');
        }
    }

    // Enhanced toggle color details dengan improved caching
    document.addEventListener('click', function(e) {
        if (e.target.closest('.toggle-color-details')) {
            const button = e.target.closest('.toggle-color-details');
            const colorId = button.getAttribute('data-id');
            const detailRow = document.getElementById(`details-${colorId}`);
            const expandIcon = button.querySelector('.expand-icon');
            
            if (!detailRow || !expandIcon) {
                console.warn('Missing elements for color details toggle');
                return;
            }
            
            if (detailRow.classList.contains('hidden')) {
                // Show details
                detailRow.classList.remove('hidden');
                detailRow.style.display = '';
                expandIcon.classList.add('rotated');
                openDetails.add(colorId);
                
                // Load component details
                if (isSearchActive && searchResults.has(colorId)) {
                    // Load with search highlighting
                    const searchTerm = codeSearch ? codeSearch.value.trim().toUpperCase() : '';
                    const searchItems = searchResults.get(colorId) || [];
                    fetchColorDetailsWithSearch(colorId, detailRow, searchItems, searchTerm);
                } else {
                    // Normal load - check cache first
                    if (componentDataCache.has(colorId) && detailRow.dataset.loaded === 'true') {
                        // Use cached data
                        const cachedData = componentDataCache.get(colorId);
                        renderCachedComponents(detailRow, cachedData);
                    } else {
                        // Fetch fresh data
                        fetchColorDetails(colorId, detailRow);
                        detailRow.dataset.loaded = 'true';
                    }
                }
            } else {
                // Hide details
                detailRow.classList.add('hidden');
                expandIcon.classList.remove('rotated');
                openDetails.delete(colorId);
            }
        }
    });

    // Function to render cached components
    function renderCachedComponents(detailRow, data) {
        if (!detailRow || !data) {
            console.warn('Missing data for rendering cached components');
            return;
        }
        
        const loadingIndicator = detailRow.querySelector('.loading-indicator');
        const componentContent = detailRow.querySelector('.component-content');
        const componentList = detailRow.querySelector('.component-list');
        
        if (loadingIndicator) loadingIndicator.classList.add('hidden');
        if (componentContent) componentContent.classList.remove('hidden');
        if (componentList) componentList.innerHTML = '';
        
        const components = data.components || [];
        
        if (components.length === 0) {
            if (componentList) {
                componentList.innerHTML = '<tr><td colspan="10" class="px-4 py-8 text-center text-gray-500 no-data-state">Tidak ada komponen ditemukan untuk warna ini.</td></tr>';
            }
        } else {
            components.forEach(component => {
                const row = createComponentRow(component, data, false, '');
                if (componentList && row) {
                    componentList.appendChild(row);
                }
            });
        }
        
        addEventListenersToNewElements(detailRow);
    }

    // Close modals
    if (closeQrModalBtn) {
        closeQrModalBtn.addEventListener('click', function() {
            if (qrModal) qrModal.classList.add('hidden');
        });
    }

    if (closePrintSingleModalBtn) {
        closePrintSingleModalBtn.addEventListener('click', function() {
            if (printSingleModal) printSingleModal.classList.add('hidden');
            currentPrintData = {};
        });
    }

    // Print single item functionality
    if (printSingleItemBtn) {
        printSingleItemBtn.addEventListener('click', function() {
            const fileName = currentPrintData.code || 'unknown';
            
            const printContent = document.getElementById('printSingleContent');
            if (!printContent) {
                console.error('Print content not found');
                return;
            }
            
            const printContents = printContent.innerHTML;
            const originalContents = document.body.innerHTML;
            const originalTitle = document.title;
            
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = printContents;
            const printHeaders = tempDiv.querySelectorAll('.print-header');
            printHeaders.forEach(header => header.remove());
            
            document.title = fileName;
            
            const metaTag = document.createElement('meta');
            metaTag.name = 'print-filename';
            metaTag.content = fileName;
            document.head.appendChild(metaTag);
            
            document.body.innerHTML = `
                <div style="padding: 20px; max-width: 800px; margin: 0 auto;">
                    ${tempDiv.innerHTML}
                </div>
            `;
            
            const printHandler = function() {
                setTimeout(() => {
                    document.body.innerHTML = originalContents;
                    document.title = originalTitle;
                    const meta = document.querySelector('meta[name="print-filename"]');
                    if (meta) meta.remove();
                    location.reload();
                }, 1000);
            };
            
            window.addEventListener('afterprint', printHandler, { once: true });
            
            setTimeout(() => {
                window.print();
            }, 100);
        });
    }

    // Function to fetch color details (normal mode)
    function fetchColorDetails(colorId, detailRow) {
        if (!colorId || !detailRow) {
            console.warn('Missing parameters for fetchColorDetails');
            return;
        }
        
        const loadingIndicator = detailRow.querySelector('.loading-indicator');
        const componentContent = detailRow.querySelector('.component-content');
        const componentList = detailRow.querySelector('.component-list');
        
        // Show loading
        if (loadingIndicator) loadingIndicator.classList.remove('hidden');
        if (componentContent) componentContent.classList.add('hidden');
        
        // Add cache busting to ensure fresh data
        const cacheBust = Date.now();
        const url = `../api/get_color_components_surabaya.php?color_id=${colorId}&cb=${cacheBust}`;
        
        fetch(url, {
            cache: 'no-cache',
            headers: {
                'Cache-Control': 'no-cache',
                'Pragma': 'no-cache'
            }
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success === false) {
                    throw new Error(data.message || data.error || 'API returned error');
                }
                
                if (loadingIndicator) loadingIndicator.classList.add('hidden');
                if (componentContent) componentContent.classList.remove('hidden');
                if (componentList) componentList.innerHTML = '';
                
                // Handle case where components array might be empty
                const components = data.components || [];
                
                // Cache the data
                componentDataCache.set(colorId, data);
                
                if (components.length === 0) {
                    if (componentList) {
                        componentList.innerHTML = '<tr><td colspan="10" class="px-4 py-8 text-center text-gray-500 no-data-state">Tidak ada komponen ditemukan untuk warna ini.</td></tr>';
                    }
                } else {
                    components.forEach(component => {
                        const row = createComponentRow(component, data, false, '');
                        if (componentList && row) {
                            componentList.appendChild(row);
                        }
                    });
                }
                
                addEventListenersToNewElements(detailRow);
            })
            .catch(error => {
                console.error('Error fetching color details:', error);
                if (loadingIndicator) {
                    loadingIndicator.innerHTML = `<p class="text-red-500 error-state">Terjadi kesalahan saat mengambil data: ${error.message}. <button class="text-blue-500 underline ml-2" onclick="location.reload()">Refresh Halaman</button></p>`;
                }
            });
    }
    
    // Function to add event listeners to newly created elements
    function addEventListenersToNewElements(container) {
        if (!container) return;
        
        // Add event listeners for checkboxes
        const checkboxes = container.querySelectorAll('.item-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                handleItemCheckboxChange(this);
            });
        });
        
        // Add event listeners for color select all checkboxes
        const colorSelectAllCheckboxes = container.querySelectorAll('.select-all-color');
        colorSelectAllCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                handleColorSelectAll(this);
            });
        });
        
        // Add event listeners for QR code buttons
        const qrButtons = container.querySelectorAll('.view-qr-code');
        qrButtons.forEach(button => {
            button.addEventListener('click', function() {
                try {
                    const qrCode = decodeURIComponent(this.getAttribute('data-qr') || '');
                    const codeBarang = this.getAttribute('data-code') || '';
                    const qrInfo = this.getAttribute('data-info') || '';
                    
                    if (qrCodeImage) {
                        qrCodeImage.innerHTML = qrCode ? 
                            `<img src="${qrCode}" alt="QR Code" class="max-w-full max-h-full">` :
                            '<p class="text-gray-500">QR Code tidak tersedia</p>';
                    }
                    if (qrCodeInfo) {
                        // Show QR info with emphasis on code barang
                        qrCodeInfo.innerHTML = `
                            <div class="text-center">
                                <p class="font-bold text-lg text-blue-600 mb-2">QR Code berisi: ${codeBarang}</p>
                                <div class="text-sm text-gray-600 border-t pt-2">
                                    <p class="font-medium mb-1">Detail Item:</p>
                                    ${qrInfo.replace(/\n/g, '<br>')}
                                </div>
                            </div>
                        `;
                    }
                    
                    if (qrModal) qrModal.classList.remove('hidden');
                } catch (error) {
                    console.error('Error displaying QR code:', error);
                }
            });
        });
        
        // Add event listeners for print single item buttons
        const printButtons = container.querySelectorAll('.print-single-item');
        printButtons.forEach(button => {
            button.addEventListener('click', function() {
                try {
                    const buyer = this.getAttribute('data-buyer') || 'Unknown Buyer';
                    const color = this.getAttribute('data-color') || 'Unknown Color';
                    const component = this.getAttribute('data-component') || 'Unknown Component';
                    const code = this.getAttribute('data-code') || 'N/A';
                    const lokasi = this.getAttribute('data-lokasi') || '-';
                    const rack = this.getAttribute('data-rack') || '-';
                    const tanggal = this.getAttribute('data-tanggal') || '-';
                    const status = this.getAttribute('data-status') || 'Unknown';
                    
                    currentPrintData = {
                        buyer: buyer.replace(/\s+/g, '_'),
                        code: code,
                        color: color
                    };
                    
                    let qrCode = null;
                    const qrCodeData = this.getAttribute('data-qr');
                    if (qrCodeData) {
                        try {
                            qrCode = decodeURIComponent(qrCodeData);
                        } catch (e) {
                            console.warn('Error decoding QR code:', e);
                        }
                    }
                    
                    if (singleItemContent) {
                        singleItemContent.innerHTML = `
                            <div class="flex flex-col items-center mb-6 border p-6 rounded-lg w-full max-w-md mx-auto">
                                <div class="print-only-header text-center mb-4">
                                    <h4 class="text-xl font-semibold mb-2">${buyer} - ${color}</h4>
                                    <h5 class="text-lg mb-4">${component} (${code})</h5>
                                </div>
                                
                                ${qrCode ? 
                                    `<div class="flex justify-center mb-6">
                                        <img src="${qrCode}" alt="QR Code" class="w-64 h-64">
                                    </div>` : 
                                    `<div class="flex justify-center mb-6">
                                        <p class="text-gray-500 italic">QR Code tidak tersedia</p>
                                    </div>`
                                }
                                
                                <div class="grid grid-cols-2 gap-x-8 gap-y-2 text-sm w-full">
                                    <p><strong>Buyer:</strong> ${buyer}</p>
                                    <p><strong>Lokasi:</strong> ${lokasi}</p>
                                    <p><strong>Color Code:</strong> ${color}</p>
                                    <p><strong>Rack No:</strong> ${rack}</p>
                                    <p><strong>Component:</strong> ${component}</p>
                                    <p><strong>Status:</strong> ${status}</p>
                                    <p><strong>Code Barang:</strong> ${code}</p>
                                    <p><strong>Tanggal:</strong> ${tanggal}</p>
                                </div>
                            </div>
                        `;
                    }
                    
                    if (printSingleModal) printSingleModal.classList.remove('hidden');
                } catch (error) {
                    console.error('Error preparing print data:', error);
                }
            });
        });
    }

    // Handle form submissions to prevent multiple clicks
    document.addEventListener('submit', function(e) {
        const form = e.target;
        if (form.tagName === 'FORM') {
            const submitButton = form.querySelector('button[type="submit"]');
            if (submitButton) {
                submitButton.disabled = true;
                submitButton.textContent = 'Memproses...';
            }
        }
    });

    // Close modals when clicking outside
    if (qrModal) {
        qrModal.addEventListener('click', function(e) {
            if (e.target === this) {
                this.classList.add('hidden');
            }
        });
    }

    if (printSingleModal) {
        printSingleModal.addEventListener('click', function(e) {
            if (e.target === this) {
                this.classList.add('hidden');
                currentPrintData = {};
            }
        });
    }

    // Handle keyboard events
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            if (qrModal) qrModal.classList.add('hidden');
            if (printSingleModal) printSingleModal.classList.add('hidden');
            currentPrintData = {};
        }
    });

    // Initialize
    updateSelectedCount();
});
</script>

<?php include '../template_it/footer.php'; ?>