<?php
// Start session
session_start();

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

// Set timezone to Indonesia (WIB/WITA/WIT - adjust according to your location)
date_default_timezone_set('Asia/Jakarta');

// Redirect if not borrower user
if (!is_logged_in() || !is_user_type('borrower')) {
    header("Location: ../login.php");
    exit();
}

// Get borrower data
$borrower_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM borrower_users WHERE id = ?");
$stmt->bind_param("i", $borrower_id);
$stmt->execute();
$borrower_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Check if account is active
if ($borrower_data['status'] == 'nonactive') {
    error_log("Nonactive borrower attempted to access form: " . $_SESSION['username']);
    $_SESSION = array();
    session_destroy();
    header("Location: ../login.php?error=inactive");
    exit();
}

// Log activity
log_activity($conn, $borrower_id, 'borrower', 'Form Access', 'borrower user accessed borrowing form');

// Get current time
$current_time = new DateTime('now', new DateTimeZone('Asia/Jakarta'));
$current_date = $current_time->format('Y-m-d');
$current_time_formatted = $current_time->format('H:i');

// Calculate tomorrow for default return date
$tomorrow = clone $current_time;
$tomorrow->add(new DateInterval('P1D'));
$tomorrow_date = $tomorrow->format('Y-m-d');

// Set page title
$page_title = "Formulir peminjaman Color Code";

// Include header
include '../template_peminjam/header.php';
?>

<!-- Add QR Scanner Library -->
<script src="https://unpkg.com/html5-qrcode@2.3.4/html5-qrcode.min.js"></script>

<!-- Main Content Area -->
<main class="flex-1 p-2 sm:p-3 lg:p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-100">    
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-4 lg:p-6 mb-4 sm:mb-6">
        <div class="flex items-center justify-between mb-3 sm:mb-4">
            <h2 class="text-lg sm:text-xl lg:text-2xl font-bold text-gray-800">Formulir peminjaman Color Code</h2>
            
            <!-- Help Icon Button -->
            <button type="button" id="help-btn" class="flex items-center gap-2 px-3 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg shadow-sm transition-all duration-200 text-sm">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-3a1 1 0 00-.867.5 1 1 0 11-1.731-1A3 3 0 0113 8a3.001 3.001 0 01-2 2.83V11a1 1 0 11-2 0v-1a1 1 0 011-1 1 1 0 100-2zm0 8a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd" />
                </svg>
                <span class="hidden sm:inline">Bantuan</span>
            </button>
        </div>
        
        <!-- Important Notice about Copy Panel -->
        <div class="mb-3 sm:mb-4 p-3 bg-yellow-50 border-l-4 border-yellow-400 rounded-md">
            <div class="flex items-start">
                <svg class="h-5 w-5 text-yellow-600 mt-0.5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                </svg>
                <div class="ml-3">
                    <h3 class="text-sm font-semibold text-yellow-800">Perhatian Penting</h3>
                    <p class="text-xs text-yellow-700 mt-1">
                        Hanya <strong>Copy Panel</strong> yang dapat dipinjam. <strong>Master Color</strong> tidak dapat dipinjam karena berfungsi sebagai wadah asli.
                    </p>
                </div>
            </div>
        </div>
        
        <!-- Server Time Display -->
        <div class="mb-3 sm:mb-4 p-2 sm:p-3 bg-blue-50 border border-blue-200 rounded-md">
            <p class="text-xs sm:text-sm text-blue-700">
                <strong>Waktu Server:</strong> <?php echo $current_time->format('d-m-Y H:i:s T'); ?>
                <span class="block sm:inline sm:ml-4"><strong>Timezone:</strong> <?php echo $current_time->getTimezone()->getName(); ?></span>
            </p>
        </div>
        
        <!-- Borrower Information Display -->
        <div class="mb-4 sm:mb-6 p-3 sm:p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg">
            <h3 class="text-sm sm:text-base lg:text-lg font-semibold text-gray-800 mb-3">Informasi Peminjam</h3>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
                <div class="bg-white p-2 sm:p-3 rounded-md shadow-sm">
                    <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">NIK</label>
                    <p class="text-xs sm:text-sm font-semibold text-gray-900 break-all"><?php echo htmlspecialchars($borrower_data['nik'] ?: 'Tidak tersedia'); ?></p>
                </div>
                <div class="bg-white p-2 sm:p-3 rounded-md shadow-sm">
                    <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Nama Lengkap</label>
                    <p class="text-xs sm:text-sm font-semibold text-gray-900 break-words"><?php echo htmlspecialchars($borrower_data['nama_borrower']); ?></p>
                </div>
                <div class="bg-white p-2 sm:p-3 rounded-md shadow-sm sm:col-span-2 lg:col-span-1">
                    <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Lokasi Posisi</label>
                    <p class="text-xs sm:text-sm font-semibold text-gray-900">
                        <span class="inline-flex px-2 py-1 text-xs font-medium rounded-full bg-green-100 text-green-800">
                            <?php echo htmlspecialchars($borrower_data['lokasi_posisi']); ?>
                        </span>
                    </p>
                </div>
            </div>
        </div>

        <form id="peminjaman-form" method="post" action="proses_peminjaman.php" class="space-y-4 sm:space-y-6">
            <!-- Transaction Date and Time -->
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4 lg:gap-6">
                <div>
                    <label for="tanggal_transaksi_date" class="block text-xs sm:text-sm font-medium text-gray-700 mb-1 sm:mb-2">Tanggal Transaksi</label>
                    <input type="date" id="tanggal_transaksi_date" name="tanggal_transaksi_date" value="<?php echo $current_date; ?>" class="w-full px-2 sm:px-3 lg:px-4 py-2 text-sm sm:text-base border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" required>
                </div>
                
                <div>
                    <label for="tanggal_transaksi_time" class="block text-xs sm:text-sm font-medium text-gray-700 mb-1 sm:mb-2">Waktu Transaksi (24 Jam)</label>
                    <input type="time" id="tanggal_transaksi_time" name="tanggal_transaksi_time" value="<?php echo $current_time_formatted; ?>" class="w-full px-2 sm:px-3 lg:px-4 py-2 text-sm sm:text-base border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" required step="60">
                    <p class="text-xs text-gray-500 mt-1">Format 24 jam (00:00 - 23:59)</p>
                </div>
            </div>
            
            <!-- Return Date and Time -->
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4 lg:gap-6">
                <div>
                    <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-1 sm:mb-2">Tanggal & Waktu Pengembalian</label>
                    <div class="grid grid-cols-2 gap-2">
                        <input type="date" id="tanggal_pengembalian_date" name="tanggal_pengembalian_date" value="<?php echo $tomorrow_date; ?>" class="w-full px-1 sm:px-2 lg:px-4 py-2 text-xs sm:text-sm lg:text-base border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" required>
                        <input type="time" id="tanggal_pengembalian_time" name="tanggal_pengembalian_time" value="<?php echo $current_time_formatted; ?>" class="w-full px-1 sm:px-2 lg:px-4 py-2 text-xs sm:text-sm lg:text-base border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" required step="60">
                    </div>
                    <p class="text-xs text-gray-500 mt-1">Pilih tanggal dan waktu pengembalian.</p>
                </div>
                
                <div>
                    <label class="block text-xs sm:text-sm font-medium text-gray-700 mb-1 sm:mb-2">Durasi Peminjaman (Otomatis)</label>
                    <div class="w-full px-2 sm:px-3 lg:px-4 py-2 bg-gray-100 border border-gray-300 rounded-md text-gray-700 text-xs sm:text-sm lg:text-base" id="duration-display">
                        -
                    </div>
                    <p class="text-xs text-gray-500 mt-1">Durasi dihitung otomatis.</p>
                </div>
            </div>
            
            <!-- QR Code Scanner Section -->
            <div class="bg-gray-50 p-3 sm:p-4 rounded-lg border">
                <div class="mb-4">
                    <h3 class="text-sm sm:text-base lg:text-lg font-semibold text-gray-700 mb-3">Scan QR Code Barang (Copy Panel)</h3>
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                        <!-- Scanner Controls -->
                        <div>
                            <button type="button" id="start-scanner-btn" class="w-full inline-flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 mb-2">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
                                    <path fill-rule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" clip-rule="evenodd" />
                                </svg>
                                Mulai Scan QR Code
                            </button>
                            <button type="button" id="stop-scanner-btn" class="w-full inline-flex items-center justify-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 hidden">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
                                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8 7a1 1 0 00-1 1v4a1 1 0 001 1h4a1 1 0 001-1V8a1 1 0 00-1-1H8z" clip-rule="evenodd" />
                                </svg>
                                Stop Scanner
                            </button>
                        </div>
                        
                        <!-- Manual Input Alternative -->
                        <div>
                            <div class="flex items-center mb-2">
                                <div class="flex-1 border-t border-gray-300"></div>
                                <span class="px-3 text-gray-500 text-sm">atau</span>
                                <div class="flex-1 border-t border-gray-300"></div>
                            </div>
                            <div class="flex gap-1 sm:gap-2">
                                <input type="text" id="manual-code-input" class="flex-1 px-2 sm:px-3 py-2 text-xs sm:text-sm border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" placeholder="Input manual (00001)">
                                <button type="button" id="add-manual-btn" class="flex-shrink-0 px-2 sm:px-4 py-2 border border-transparent rounded-md shadow-sm text-xs sm:text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 sm:h-5 sm:w-5" viewBox="0 0 20 20" fill="currentColor">
                                        <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
                                    </svg>
                                    <span class="hidden sm:inline ml-1">Tambah</span>
                                </button>
                            </div>
                            <p class="text-xs text-gray-500 mt-1">Format: 5 digit angka (contoh: 00001)</p>
                        </div>
                    </div>
                    
                    <!-- QR Scanner Area -->
                    <div id="qr-reader" class="mt-4 rounded-lg overflow-hidden bg-black" style="display: none;"></div>
                    
                    <!-- Scanner Status -->
                    <div id="scanner-status" class="mt-2 p-2 rounded text-sm text-center hidden"></div>
                </div>
            </div>
            
            <!-- Shopping Cart -->
            <div id="cart-container" class="hidden">
                <div class="flex flex-col gap-3 mb-3">
                    <h3 class="text-sm sm:text-base lg:text-lg font-semibold text-gray-700">Keranjang Peminjaman (Copy Panel)</h3>
                    <div class="flex flex-col sm:flex-row gap-2">
                        <button type="button" id="check-borrowing-btn" class="inline-flex items-center justify-center px-3 sm:px-4 py-2 border border-transparent rounded-md shadow-sm text-xs sm:text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 w-full sm:w-auto">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 sm:h-5 sm:w-5 mr-1 sm:mr-2" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v3.586L7.707 9.293a1 1 0 00-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 10.586V7z" clip-rule="evenodd" />
                            </svg>
                            Cek
                        </button>
                        <button type="button" id="clear-cart" class="inline-flex items-center justify-center px-3 sm:px-4 py-2 border border-transparent rounded-md shadow-sm text-xs sm:text-sm font-medium text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 w-full sm:w-auto">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 sm:h-5 sm:w-5 mr-1 sm:mr-2" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
                            </svg>
                            Hapus
                        </button>
                    </div>
                </div>
                
                <!-- Cart Table -->
                <div class="overflow-x-auto -mx-2 sm:mx-0">
                    <div class="inline-block min-w-full align-middle">
                        <div class="overflow-hidden border border-gray-200 rounded-md">
                            <table class="min-w-full divide-y divide-gray-200 text-xs sm:text-sm">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th scope="col" class="px-1 sm:px-3 lg:px-6 py-2 sm:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No</th>
                                        <th scope="col" class="px-1 sm:px-3 lg:px-6 py-2 sm:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kode</th>
                                        <th scope="col" class="hidden sm:table-cell px-3 lg:px-6 py-2 sm:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Buyer</th>
                                        <th scope="col" class="px-1 sm:px-3 lg:px-6 py-2 sm:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Color</th>
                                        <th scope="col" class="hidden md:table-cell px-3 lg:px-6 py-2 sm:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Component</th>
                                        <th scope="col" class="px-1 sm:px-3 lg:px-6 py-2 sm:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Rack</th>
                                        <th scope="col" class="px-1 sm:px-3 lg:px-6 py-2 sm:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                        <th scope="col" class="hidden lg:table-cell px-3 lg:px-6 py-2 sm:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Lokasi</th>
                                        <th scope="col" class="px-1 sm:px-3 lg:px-6 py-2 sm:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody id="cart-items" class="bg-white divide-y divide-gray-200">
                                    <!-- Cart items will be inserted here -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <div id="cart-empty-message" class="text-center py-4 text-gray-500 text-xs sm:text-sm">
                    Keranjang peminjaman kosong. Silakan scan QR code Copy Panel untuk menambahkan barang.
                </div>
            </div>
            
            <!-- Keterangan -->
            <div>
                <label for="keterangan" class="block text-xs sm:text-sm font-medium text-gray-700 mb-1 sm:mb-2">Keterangan</label>
                <textarea id="keterangan" name="keterangan" rows="3" class="w-full px-2 sm:px-3 lg:px-4 py-2 text-xs sm:text-sm lg:text-base border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 resize-none" placeholder="Keterangan tambahan (opsional)"></textarea>
            </div>
            
            <!-- Hidden fields -->
            <input type="hidden" name="cart_items" id="cart-items-input" value="">
            
            <!-- Submit Button -->
            <div class="pt-4 flex justify-end">
                <button type="submit" id="submit-button" class="inline-flex justify-center py-2 sm:py-3 px-4 sm:px-6 border border-transparent shadow-sm text-sm sm:text-base font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 w-full sm:w-auto" disabled>
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 sm:h-6 sm:w-6 mr-2" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z" clip-rule="evenodd" />
                    </svg>
                    Pinjam
                </button>
            </div>
        </form>
    </div>
    
    <!-- Help Modal -->
    <div id="help-modal" class="fixed inset-0 z-50 overflow-y-auto hidden">
        <div class="flex items-center justify-center min-h-screen px-2 sm:px-4 pt-2 pb-4 text-center">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
            </div>
            
            <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle w-full max-w-2xl mx-2 sm:mx-4">
                <div class="bg-white px-3 sm:px-4 lg:px-6 pt-4 sm:pt-5 pb-3 sm:pb-4">
                    <div class="sm:flex sm:items-start">
                        <div class="mx-auto flex-shrink-0 flex items-center justify-center h-10 w-10 sm:h-12 sm:w-12 rounded-full bg-blue-100 sm:mx-0">
                            <svg class="h-5 w-5 sm:h-6 sm:w-6 text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                        </div>
                        <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
                            <h3 class="text-base sm:text-lg leading-6 font-medium text-gray-900">
                                Cara Penggunaan Peminjaman Color Code
                            </h3>
                            <div class="mt-3 sm:mt-4 space-y-3 sm:space-y-4 text-xs sm:text-sm text-gray-700">
                                <!-- Important Notice -->
                                <div class="bg-red-50 p-3 rounded-lg border border-red-200">
                                    <h4 class="font-semibold text-red-800 mb-2 flex items-center gap-2">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                                            <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                                        </svg>
                                        PENTING: Hanya Copy Panel
                                    </h4>
                                    <ul class="list-disc list-inside space-y-1 text-gray-600">
                                        <li><strong>Copy Panel</strong>: Dapat dipinjam (kode 5 digit: 00003, 00004, dst)</li>
                                        <li><strong>Master Color</strong>: TIDAK dapat dipinjam (wadah asli warna)</li>
                                        <li>Sistem akan menolak otomatis jika Anda mencoba scan Master Color</li>
                                    </ul>
                                </div>
                                
                                <!-- Scan QR Code -->
                                <div class="bg-blue-50 p-3 rounded-lg border border-blue-200">
                                    <h4 class="font-semibold text-blue-800 mb-2 flex items-center gap-2">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                                            <path fill-rule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" clip-rule="evenodd" />
                                        </svg>
                                        Metode 1: Scan QR Code
                                    </h4>
                                    <ol class="list-decimal list-inside space-y-1 text-gray-600">
                                        <li>Klik tombol <strong>"Mulai Scan QR Code"</strong></li>
                                        <li>Izinkan akses kamera saat diminta</li>
                                        <li>Arahkan kamera ke QR Code pada label Copy Panel</li>
                                        <li>Sistem akan otomatis mendeteksi dan menambahkan ke keranjang</li>
                                        <li>Klik <strong>"OK"</strong> pada notifikasi untuk melanjutkan scan item lain</li>
                                        <li>Jika scan Master Color, sistem akan menolak otomatis</li>
                                    </ol>
                                </div>
                                
                                <!-- Manual Input -->
                                <div class="bg-green-50 p-3 rounded-lg border border-green-200">
                                    <h4 class="font-semibold text-green-800 mb-2 flex items-center gap-2">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                                            <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
                                        </svg>
                                        Metode 2: Input Manual
                                    </h4>
                                    <ol class="list-decimal list-inside space-y-1 text-gray-600">
                                        <li>Ketik kode barang di kolon input (contoh: <strong>00001</strong>)</li>
                                        <li>Klik tombol <strong>"Tambah"</strong> atau tekan <strong>Enter</strong></li>
                                        <li>Sistem akan memvalidasi dan menambahkan ke keranjang</li>
                                        <li>Hanya Copy Panel yang akan diterima</li>
                                        <li>Ulangi untuk item lainnya</li>
                                    </ol>
                                </div>
                                
                                <!-- Important Notes -->
                                <div class="bg-yellow-50 p-3 rounded-lg border border-yellow-200">
                                    <h4 class="font-semibold text-yellow-800 mb-2 flex items-center gap-2">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                                            <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                                        </svg>
                                        Catatan Penting
                                    </h4>
                                    <ul class="list-disc list-inside space-y-1 text-gray-600">
                                        <li><strong>Format Kode:</strong> 5 digit angka (00001, 00002, dst)</li>
                                        <li><strong>Master Color:</strong> Tidak bisa dipinjam (akan ditolak sistem)</li>
                                        <li><strong>Copy Panel:</strong> Bisa dipinjam sesuai ketersediaan</li>
                                        <li><strong>Status Item:</strong> Item dengan status "Dipinjam" tidak bisa dipinjam lagi</li>
                                        <li><strong>Kedaluwarsa:</strong> Copy Panel baru berlaku 1 tahun, setelah dipinjam menjadi 90 hari</li>
                                        <li><strong>Approval:</strong> Peminjaman langsung disetujui otomatis</li>
                                    </ul>
                                </div>
                                
                                <!-- Steps After Scanning -->
                                <div class="bg-indigo-50 p-3 rounded-lg border border-indigo-200">
                                    <h4 class="font-semibold text-indigo-800 mb-2 flex items-center gap-2">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                                            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v3.586L7.707 9.293a1 1 0 00-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 10.586V7z" clip-rule="evenodd" />
                                        </svg>
                                        Setelah Menambahkan Item
                                    </h4>
                                    <ol class="list-decimal list-inside space-y-1 text-gray-600">
                                        <li>Periksa item di <strong>Keranjang Peminjaman</strong></li>
                                        <li>Pastikan semua item adalah Copy Panel</li>
                                        <li>Klik <strong>"Cek"</strong> untuk melihat detail peminjaman</li>
                                        <li>Pastikan tanggal dan waktu pengembalian sudah benar</li>
                                        <li>Isi keterangan tambahan jika diperlukan</li>
                                        <li>Klik <strong>"Konfirmasi Peminjaman"</strong> untuk menyelesaikan</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-3 sm:px-4 lg:px-6 py-3 flex justify-end">
                    <button type="button" id="help-close" class="w-full sm:w-auto inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        Mengerti
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Check Borrowing Modal -->
    <div id="check-borrowing-modal" class="fixed inset-0 z-50 overflow-y-auto hidden">
        <div class="flex items-center justify-center min-h-screen px-1 sm:px-4 pt-2 pb-4 text-center">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
            </div>
            
            <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle w-full max-w-7xl mx-1 sm:mx-4">
                <div class="bg-white px-2 sm:px-4 lg:px-6 pt-3 sm:pt-5 pb-3 sm:pb-4">
                    <div class="sm:flex sm:items-start">
                        <div class="mx-auto flex-shrink-0 flex items-center justify-center h-10 w-10 sm:h-12 sm:w-12 rounded-full bg-blue-100 sm:mx-0">
                            <svg class="h-5 w-5 sm:h-6 sm:w-6 text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                        </div>
                        <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
                            <h3 class="text-sm sm:text-base lg:text-lg leading-6 font-medium text-gray-900">
                                Detail Peminjaman Copy Panel
                            </h3>
                            <div class="mt-3 sm:mt-4">
                                <p class="text-xs sm:text-sm text-gray-500 mb-3 sm:mb-4">
                                    Berikut adalah daftar Copy Panel yang akan dipinjam:
                                </p>
                                
                                <div class="overflow-x-auto -mx-2 sm:mx-0">
                                    <div class="inline-block min-w-full align-middle">
                                        <div class="overflow-hidden border border-gray-200 rounded-md">
                                            <table class="min-w-full divide-y divide-gray-200 text-xs">
                                                <thead class="bg-gray-50">
                                                    <tr>
                                                        <th scope="col" class="px-1 sm:px-2 lg:px-4 py-1 sm:py-2 lg:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No</th>
                                                        <th scope="col" class="px-1 sm:px-2 lg:px-4 py-1 sm:py-2 lg:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kode</th>
                                                        <th scope="col" class="hidden sm:table-cell px-2 lg:px-4 py-1 sm:py-2 lg:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Buyer</th>
                                                        <th scope="col" class="px-1 sm:px-2 lg:px-4 py-1 sm:py-2 lg:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Color</th>
                                                        <th scope="col" class="hidden md:table-cell px-2 lg:px-4 py-1 sm:py-2 lg:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Component</th>
                                                        <th scope="col" class="px-1 sm:px-2 lg:px-4 py-1 sm:py-2 lg:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Rack</th>
                                                        <th scope="col" class="px-1 sm:px-2 lg:px-4 py-1 sm:py-2 lg:py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="modal-cart-items" class="bg-white divide-y divide-gray-200">
                                                    <!-- Items will be inserted here -->
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mt-3 sm:mt-4 space-y-2 text-xs sm:text-sm">
                                    <div class="grid grid-cols-1 gap-2">
                                        <div class="bg-gray-50 p-2 sm:p-3 rounded-md">
                                            <p class="text-gray-700">
                                                <strong>Tanggal & Waktu Transaksi:</strong><br>
                                                <span id="modal-tanggal-transaksi" class="break-words"></span>
                                            </p>
                                        </div>
                                        <div class="bg-gray-50 p-2 sm:p-3 rounded-md">
                                            <p class="text-gray-700">
                                                <strong>Durasi Peminjaman:</strong><br>
                                                <span id="modal-durasi"></span>
                                            </p>
                                        </div>
                                        <div class="bg-gray-50 p-2 sm:p-3 rounded-md">
                                            <p class="text-gray-700">
                                                <strong>Tanggal & Waktu Pengembalian:</strong><br>
                                                <span id="modal-tanggal-pengembalian" class="break-words"></span>
                                            </p>
                                        </div>
                                        <div class="bg-gray-50 p-2 sm:p-3 rounded-md">
                                            <p class="text-gray-700">
                                                <strong>Keterangan:</strong><br>
                                                <span id="modal-keterangan"></span>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-2 sm:px-4 lg:px-6 py-3 flex flex-col gap-2 sm:flex-row sm:justify-end">
                    <button type="button" id="modal-close" class="w-full sm:w-auto inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-3 sm:px-4 py-2 bg-white text-xs sm:text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                        Kembali
                    </button>
                    <button type="button" id="modal-submit" class="w-full sm:w-auto inline-flex justify-center rounded-md border border-transparent shadow-sm px-3 sm:px-4 py-2 bg-blue-600 text-xs sm:text-sm font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        Konfirmasi Peminjaman
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Popup Notification -->
    <div id="popup-notification" class="fixed inset-0 flex items-center justify-center z-[60] hidden px-2 sm:px-4">
        <div class="fixed inset-0 bg-black bg-opacity-50 transition-opacity"></div>
        <div class="bg-white rounded-lg p-3 sm:p-4 lg:p-6 w-full max-w-md mx-auto relative z-10 shadow-xl transform transition-all">
            <div id="popup-content">
                <!-- Dynamic content -->
            </div>
            <div class="mt-3 sm:mt-4 flex justify-end">
                <button id="close-popup" class="px-3 sm:px-4 py-2 bg-blue-600 text-white text-xs sm:text-sm rounded hover:bg-blue-700 transition-colors">
                    OK
                </button>
            </div>
        </div>
    </div>
</main>
<script>
// QR Scanner instance and states
let html5QrcodeScanner = null;
let scannerActive = false;
let scannerPaused = false;

// Function to show popup notifications
function showPopupNotification(type, message, autoClose = false, pauseScanner = false) {
    const popupContent = document.getElementById('popup-content');
    
    let icon, textColor, bgColor;
    if (type === 'warning') {
        icon = '<path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />';
        textColor = 'text-yellow-800';
        bgColor = 'bg-yellow-50 border-yellow-400';
    } else if (type === 'success') {
        icon = '<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />';
        textColor = 'text-green-800';
        bgColor = 'bg-green-50 border-green-400';
    } else if (type === 'error') {
        icon = '<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />';
        textColor = 'text-red-800';
        bgColor = 'bg-red-50 border-red-400';
    } else {
        icon = '<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v2H7a1 1 0 100 2h2v2a1 1 0 102 0v-2h2a1 1 0 100-2h-2V7z" clip-rule="evenodd" />';
        textColor = 'text-blue-800';
        bgColor = 'bg-blue-50 border-blue-400';
    }
    
    popupContent.innerHTML = `
        <div class="flex p-2 sm:p-3 lg:p-4 border rounded-md ${bgColor}">
            <div class="flex-shrink-0">
                <svg class="h-4 w-4 sm:h-5 sm:w-5 lg:h-6 lg:w-6 ${type === 'warning' ? 'text-yellow-500' : type === 'success' ? 'text-green-500' : type === 'error' ? 'text-red-500' : 'text-blue-500'}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                    ${icon}
                </svg>
            </div>
            <div class="ml-2 sm:ml-3">
                <h3 class="text-xs sm:text-sm lg:text-base font-medium ${textColor}">
                    ${type === 'warning' ? 'Perhatian' : type === 'success' ? 'Berhasil' : type === 'error' ? 'Error' : 'Informasi'}
                </h3>
                <p class="mt-1 text-xs sm:text-sm ${textColor}">${message}</p>
            </div>
        </div>
    `;
    
    const popupNotification = document.getElementById('popup-notification');
    popupNotification.dataset.pauseScanner = pauseScanner.toString();
    
    if (pauseScanner && scannerActive && !scannerPaused) {
        pauseScannerTemporarily();
    }
    
    popupNotification.classList.remove('hidden');
    
    if (autoClose && !pauseScanner) {
        setTimeout(() => {
            popupNotification.classList.add('hidden');
        }, 8000);
    }
}

// Function to pause scanner
function pauseScannerTemporarily() {
    if (html5QrcodeScanner && scannerActive && !scannerPaused) {
        html5QrcodeScanner.pause().then(() => {
            scannerPaused = true;
            updateScannerStatus('Scanner dijeda. Klik OK untuk melanjutkan.', 'warning');
        }).catch(() => {
            console.log('Pause not supported');
        });
    }
}

// Function to resume scanner
function resumeScannerAfterPause() {
    if (html5QrcodeScanner && scannerActive && scannerPaused) {
        html5QrcodeScanner.resume().then(() => {
            scannerPaused = false;
            updateScannerStatus('Scanner aktif. Arahkan kamera ke QR Code Copy Panel.', 'success');
        }).catch(() => {
            stopQRScanner();
            setTimeout(() => startQRScanner(), 500);
        });
    }
}

// Function to update scanner status
function updateScannerStatus(message, type = 'info') {
    const statusDiv = document.getElementById('scanner-status');
    let bgColor = 'bg-blue-100 text-blue-700';
    
    if (type === 'success') bgColor = 'bg-green-100 text-green-700';
    else if (type === 'error') bgColor = 'bg-red-100 text-red-700';
    else if (type === 'warning') bgColor = 'bg-yellow-100 text-yellow-700';
    
    statusDiv.className = `mt-2 p-2 rounded text-sm text-center ${bgColor}`;
    statusDiv.textContent = message;
    statusDiv.classList.remove('hidden');
}

// Function to start QR Scanner
function startQRScanner() {
    const qrReaderDiv = document.getElementById('qr-reader');
    const startBtn = document.getElementById('start-scanner-btn');
    const stopBtn = document.getElementById('stop-scanner-btn');
    
    qrReaderDiv.style.display = 'block';
    startBtn.classList.add('hidden');
    stopBtn.classList.remove('hidden');
    
    updateScannerStatus('Memulai scanner...', 'info');
    
    html5QrcodeScanner = new Html5Qrcode('qr-reader');
    
    const config = { 
        fps: 10, 
        qrbox: { width: 250, height: 250 },
        aspectRatio: 1.0
    };
    
    html5QrcodeScanner.start(
        { facingMode: "environment" },
        config,
        (decodedText) => onScanSuccess(decodedText),
        () => {}
    ).then(() => {
        scannerActive = true;
        scannerPaused = false;
        updateScannerStatus('Scanner aktif. Arahkan kamera ke QR Code Copy Panel.', 'success');
    }).catch((err) => {
        console.error('Unable to start scanning:', err);
        updateScannerStatus('Gagal memulai scanner: ' + err, 'error');
        stopQRScanner();
    });
}

// Function to stop QR Scanner
function stopQRScanner() {
    const qrReaderDiv = document.getElementById('qr-reader');
    const startBtn = document.getElementById('start-scanner-btn');
    const stopBtn = document.getElementById('stop-scanner-btn');
    
    if (html5QrcodeScanner && scannerActive) {
        html5QrcodeScanner.stop().then(() => {
            scannerActive = false;
            scannerPaused = false;
            qrReaderDiv.style.display = 'none';
            startBtn.classList.remove('hidden');
            stopBtn.classList.add('hidden');
            updateScannerStatus('Scanner dihentikan.', 'info');
            
            setTimeout(() => {
                document.getElementById('scanner-status').classList.add('hidden');
            }, 2000);
        }).catch((err) => {
            console.error('Unable to stop scanning:', err);
        });
    }
}

// Function when QR code scanned
function onScanSuccess(decodedText) {
    let kodeBarang = '';
    
    try {
        const data = JSON.parse(decodedText);
        kodeBarang = data.kode_barang || decodedText;
    } catch (e) {
        kodeBarang = decodedText;
    }
    
    // Updated validation for 5-digit format
    if (!/^\d{5}$/.test(kodeBarang)) {
        updateScannerStatus('Format QR Code tidak valid. Expected: ##### (5 digit)', 'error');
        return;
    }
    
    if ('vibrate' in navigator) {
        navigator.vibrate(100);
    }
    
    updateScannerStatus(`Scan berhasil: ${kodeBarang}`, 'success');
    validateAndAddItem(kodeBarang, true);
}

// Calculate duration
function calculateAndDisplayDuration() {
    const startDate = document.getElementById('tanggal_transaksi_date').value;
    const startTime = document.getElementById('tanggal_transaksi_time').value;
    const endDate = document.getElementById('tanggal_pengembalian_date').value;
    const endTime = document.getElementById('tanggal_pengembalian_time').value;
    const durationDisplay = document.getElementById('duration-display');
    
    if (startDate && startTime && endDate && endTime) {
        const startDateTime = new Date(startDate + 'T' + startTime + ':00');
        const endDateTime = new Date(endDate + 'T' + endTime + ':00');
        
        if (endDateTime > startDateTime) {
            const diffInMs = endDateTime.getTime() - startDateTime.getTime();
            const diffInHours = diffInMs / (1000 * 60 * 60);
            
            let durationText;
            if (diffInHours < 24) {
                durationText = diffInHours.toFixed(1) + ' jam';
            } else {
                const diffInDays = diffInHours / 24;
                durationText = diffInDays.toFixed(1) + ' hari';
            }
            
            durationDisplay.textContent = durationText;
            durationDisplay.className = 'w-full px-2 sm:px-3 lg:px-4 py-2 bg-green-100 border border-green-300 rounded-md text-green-700 font-medium text-xs sm:text-sm lg:text-base';
        } else if (endDateTime.getTime() === startDateTime.getTime()) {
            durationDisplay.textContent = 'Waktu pengembalian tidak boleh sama dengan waktu transaksi';
            durationDisplay.className = 'w-full px-2 sm:px-3 lg:px-4 py-2 bg-red-100 border border-red-300 rounded-md text-red-700 text-xs sm:text-sm lg:text-base';
        } else {
            durationDisplay.textContent = 'Waktu pengembalian harus setelah waktu transaksi';
            durationDisplay.className = 'w-full px-2 sm:px-3 lg:px-4 py-2 bg-red-100 border border-red-300 rounded-md text-red-700 text-xs sm:text-sm lg:text-base';
        }
    } else {
        durationDisplay.textContent = '-';
        durationDisplay.className = 'w-full px-2 sm:px-3 lg:px-4 py-2 bg-gray-100 border border-gray-300 rounded-md text-gray-700 text-xs sm:text-sm lg:text-base';
    }
}

// Cart data
let cartData = [];

// Update cart display
function updateCartDisplay() {
    const cartContainer = document.getElementById('cart-container');
    const cartItems = document.getElementById('cart-items');
    const cartEmptyMessage = document.getElementById('cart-empty-message');
    const submitButton = document.getElementById('submit-button');
    const cartItemsInput = document.getElementById('cart-items-input');
    
    if (cartData.length > 0) {
        cartContainer.classList.remove('hidden');
        cartEmptyMessage.classList.add('hidden');
        submitButton.removeAttribute('disabled');
    } else {
        cartEmptyMessage.classList.remove('hidden');
        submitButton.setAttribute('disabled', 'disabled');
    }
    
    cartItems.innerHTML = '';
    
    cartData.forEach((item, index) => {
        const row = document.createElement('tr');
        
        let rowClass = '';
        if (item.status === 'Dipinjam') rowClass = 'bg-yellow-50';
        else if (item.status === 'Rusak') rowClass = 'bg-red-50';
        else if (item.status === 'Expired' || item.status === 'Renew') rowClass = 'bg-gray-100';
        
        row.className = rowClass;
        row.innerHTML = `
            <td class="px-1 sm:px-3 lg:px-6 py-2 sm:py-4 whitespace-nowrap text-xs text-gray-500">${index + 1}</td>
            <td class="px-1 sm:px-3 lg:px-6 py-2 sm:py-4 whitespace-nowrap text-xs font-medium text-gray-900 break-all">${item.kode_barang}</td>
            <td class="hidden sm:table-cell px-3 lg:px-6 py-2 sm:py-4 whitespace-nowrap text-xs text-gray-500 break-words">${item.buyer_name}</td>
            <td class="px-1 sm:px-3 lg:px-6 py-2 sm:py-4 whitespace-nowrap text-xs text-gray-500 break-words">${item.color_code}</td>
            <td class="hidden md:table-cell px-3 lg:px-6 py-2 sm:py-4 whitespace-nowrap text-xs text-gray-500 break-words">${item.component_name}</td>
            <td class="px-1 sm:px-3 lg:px-6 py-2 sm:py-4 whitespace-nowrap text-xs text-gray-500">${item.rack_no}</td>
            <td class="px-1 sm:px-3 lg:px-6 py-2 sm:py-4 whitespace-nowrap text-xs text-gray-500">
                <span class="inline-flex px-1 py-0.5 text-xs font-semibold rounded-full ${item.status === 'Tersedia' ? 'bg-green-100 text-green-800' : 
                    item.status === 'Dipinjam' ? 'bg-yellow-100 text-yellow-800' : 
                    item.status === 'Rusak' ? 'bg-red-100 text-red-800' : 'bg-gray-100 text-gray-800'}">
                    ${item.status}
                </span>
            </td>
            <td class="hidden lg:table-cell px-3 lg:px-6 py-2 sm:py-4 whitespace-nowrap text-xs text-gray-500">${item.lokasi}</td>
            <td class="px-1 sm:px-3 lg:px-6 py-2 sm:py-4 whitespace-nowrap text-xs text-gray-500">
                <button type="button" class="remove-from-cart text-red-600 hover:text-red-900 p-1" data-index="${index}">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3 sm:h-4 sm:w-4" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
                    </svg>
                </button>
            </td>
        `;
        cartItems.appendChild(row);
    });
    
    cartItemsInput.value = JSON.stringify(cartData);
    
    document.querySelectorAll('.remove-from-cart').forEach(button => {
        button.addEventListener('click', function() {
            const index = parseInt(this.dataset.index);
            removeFromCart(index);
        });
    });
}

// Add to cart
function addToCart(item, fromScanner = false) {
    const exists = cartData.some(cartItem => cartItem.id === item.id);
    
    if (exists) {
        const message = 'Item ini sudah ada di keranjang peminjaman.';
        showPopupNotification('warning', message, !fromScanner, fromScanner);
        return;
    }
    
    if (item.status === 'Dipinjam') {
        const message = `Code barang <strong>${item.kode_barang}</strong> sedang dipinjam oleh borrower lain dan tidak dapat dipinjam kembali.`;
        showPopupNotification('error', message, false, fromScanner);
        return;
    }
    
    cartData.push(item);
    updateCartDisplay();
    
    const successMessage = `Copy Panel <strong>${item.kode_barang}</strong> (${item.component_name}) masuk list peminjaman.`;
    showPopupNotification('success', successMessage, !fromScanner, fromScanner);
    
    if (item.status === 'Rusak') {
        setTimeout(() => {
            const warningMessage = `Copy Panel <strong>${item.kode_barang}</strong> dapat dipinjam, namun dengan kualitas warna yang sudah rusak dikhawatirkan kualitas yang dihasilkan nanti kurang bagus.`;
            showPopupNotification('warning', warningMessage, false, fromScanner);
        }, fromScanner ? 100 : 3000);
    }
}

// Remove from cart
function removeFromCart(index) {
    const removedItem = cartData[index];
    cartData.splice(index, 1);
    updateCartDisplay();
    showPopupNotification('success', `Item <strong>${removedItem.kode_barang}</strong> berhasil dihapus dari keranjang peminjaman.`, true);
}

// Validate and add item
function validateAndAddItem(kodeBarang, fromScanner = false) {
    if (!kodeBarang || kodeBarang.trim() === '') {
        showPopupNotification('error', 'Silakan masukkan code barang terlebih dahulu.', true);
        return;
    }
    
    showPopupNotification('info', 'Memvalidasi code barang...');
    
    fetch(`validate_code_barang.php?kode_barang=${encodeURIComponent(kodeBarang.trim())}`)
        .then(response => response.json())
        .then(data => {
            document.getElementById('popup-notification').classList.add('hidden');
            
            if (data.success) {
                addToCart(data.item, fromScanner);
            } else {
                const message = data.message || 'Maaf code barang tidak ada di master color panel atau bukan Copy Panel.';
                showPopupNotification('error', message, !fromScanner, fromScanner);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('popup-notification').classList.add('hidden');
            const errorMessage = 'Terjadi kesalahan saat memvalidasi code barang. Silakan coba lagi.';
            showPopupNotification('error', errorMessage, !fromScanner, fromScanner);
        });
}

document.addEventListener('DOMContentLoaded', function() {
    calculateAndDisplayDuration();
    
    // Date/time change handlers
    document.getElementById('tanggal_transaksi_date').addEventListener('change', calculateAndDisplayDuration);
    document.getElementById('tanggal_transaksi_time').addEventListener('change', calculateAndDisplayDuration);
    document.getElementById('tanggal_pengembalian_date').addEventListener('change', calculateAndDisplayDuration);
    document.getElementById('tanggal_pengembalian_time').addEventListener('change', calculateAndDisplayDuration);
    
    // Help button
    document.getElementById('help-btn').addEventListener('click', function() {
        document.getElementById('help-modal').classList.remove('hidden');
    });
    
    document.getElementById('help-close').addEventListener('click', function() {
        document.getElementById('help-modal').classList.add('hidden');
    });
    
    // Close popup
    document.getElementById('close-popup').addEventListener('click', function() {
        const popupNotification = document.getElementById('popup-notification');
        const shouldResume = popupNotification.dataset.pauseScanner === 'true';
        
        popupNotification.classList.add('hidden');
        
        if (shouldResume && scannerPaused) {
            resumeScannerAfterPause();
        }
    });
    
    // QR Scanner buttons
    document.getElementById('start-scanner-btn').addEventListener('click', startQRScanner);
    document.getElementById('stop-scanner-btn').addEventListener('click', stopQRScanner);
    
    // Manual input
    document.getElementById('add-manual-btn').addEventListener('click', function() {
        const manualInput = document.getElementById('manual-code-input');
        const kodeBarang = manualInput.value.trim();
        
        if (kodeBarang) {
            validateAndAddItem(kodeBarang, false);
            manualInput.value = '';
        } else {
            showPopupNotification('error', 'Silakan masukkan code barang.', true);
        }
    });
    
    // Enter key for manual input
    document.getElementById('manual-code-input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            document.getElementById('add-manual-btn').click();
        }
    });
    
    // Clear cart
    document.getElementById('clear-cart').addEventListener('click', function() {
        if (cartData.length === 0) {
            showPopupNotification('info', 'Keranjang peminjaman sudah kosong.', true);
            return;
        }
        
        cartData = [];
        updateCartDisplay();
        showPopupNotification('success', 'Keranjang peminjaman berhasil dibersihkan.', true);
    });
    
    // Check borrowing button
    document.getElementById('check-borrowing-btn').addEventListener('click', function() {
        if (cartData.length === 0) {
            showPopupNotification('warning', 'Keranjang peminjaman kosong. Silakan scan QR code Copy Panel terlebih dahulu.', true);
            return;
        }
        
        const modalCartItems = document.getElementById('modal-cart-items');
        modalCartItems.innerHTML = '';
        
        cartData.forEach((item, index) => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td class="px-1 sm:px-2 lg:px-4 py-1 sm:py-2 lg:py-4 whitespace-nowrap text-xs text-gray-500">${index + 1}</td>
                <td class="px-1 sm:px-2 lg:px-4 py-1 sm:py-2 lg:py-4 whitespace-nowrap text-xs font-medium text-gray-900 break-all">${item.kode_barang}</td>
                <td class="hidden sm:table-cell px-2 lg:px-4 py-1 sm:py-2 lg:py-4 whitespace-nowrap text-xs text-gray-500 break-words">${item.buyer_name}</td>
                <td class="px-1 sm:px-2 lg:px-4 py-1 sm:py-2 lg:py-4 whitespace-nowrap text-xs text-gray-500 break-words">${item.color_code}</td>
                <td class="hidden md:table-cell px-2 lg:px-4 py-1 sm:py-2 lg:py-4 whitespace-nowrap text-xs text-gray-500 break-words">${item.component_name}</td>
                <td class="px-1 sm:px-2 lg:px-4 py-1 sm:py-2 lg:py-4 whitespace-nowrap text-xs text-gray-500">${item.rack_no}</td>
                <td class="px-1 sm:px-2 lg:px-4 py-1 sm:py-2 lg:py-4 whitespace-nowrap text-xs text-gray-500">${item.status}</td>
            `;
            modalCartItems.appendChild(row);
        });
        
        const transactionDate = new Date(document.getElementById('tanggal_transaksi_date').value + 'T' + document.getElementById('tanggal_transaksi_time').value + ':00');
        const returnDate = new Date(document.getElementById('tanggal_pengembalian_date').value + 'T' + document.getElementById('tanggal_pengembalian_time').value + ':00');
        
        const formatDateTime = (date) => {
            const options = { 
                weekday: 'long', 
                year: 'numeric', 
                month: 'long', 
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
            };
            return date.toLocaleDateString('id-ID', options);
        };
        
        const diffInMs = returnDate.getTime() - transactionDate.getTime();
        const diffInHours = diffInMs / (1000 * 60 * 60);
        
        let modalDurationText;
        if (diffInHours < 24) {
            modalDurationText = diffInHours.toFixed(1) + ' jam';
        } else {
            const diffInDays = diffInHours / 24;
            modalDurationText = diffInDays.toFixed(1) + ' hari';
        }
        
        document.getElementById('modal-tanggal-transaksi').textContent = formatDateTime(transactionDate);
        document.getElementById('modal-durasi').textContent = modalDurationText;
        document.getElementById('modal-tanggal-pengembalian').textContent = formatDateTime(returnDate);
        document.getElementById('modal-keterangan').textContent = document.getElementById('keterangan').value || '-';
        
        document.getElementById('check-borrowing-modal').classList.remove('hidden');
    });
    
    // Modal close
    document.getElementById('modal-close').addEventListener('click', function() {
        document.getElementById('check-borrowing-modal').classList.add('hidden');
    });
    
    // Modal submit
    document.getElementById('modal-submit').addEventListener('click', function() {
        showPopupNotification('info', 'Memproses permintaan peminjaman Copy Panel, mohon tunggu...');
        
        const modalSubmit = document.getElementById('modal-submit');
        modalSubmit.disabled = true;
        modalSubmit.textContent = 'Memproses...';
        
        document.getElementById('check-borrowing-modal').classList.add('hidden');
        
        const formData = new FormData(document.getElementById('peminjaman-form'));
        
        fetch('proses_peminjaman.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            document.getElementById('popup-notification').classList.add('hidden');
            
            if (data.success) {
                let successMessage = data.message;
                if (data.data && data.data.current_server_time) {
                    successMessage += `<br><small><strong>Waktu server:</strong> ${data.data.current_server_time}</small>`;
                }
                showPopupNotification('success', successMessage, true);
                
                setTimeout(() => {
                    resetForm();
                }, 2000);
            } else {
                showPopupNotification('error', data.message, true);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('popup-notification').classList.add('hidden');
            showPopupNotification('error', 'Terjadi kesalahan sistem. Silakan coba lagi.', true);
        })
        .finally(() => {
            modalSubmit.disabled = false;
            modalSubmit.textContent = 'Konfirmasi Peminjaman';
        });
    });
    
    // Form validation
    document.getElementById('peminjaman-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (cartData.length === 0) {
            showPopupNotification('error', 'Keranjang peminjaman kosong. Silakan scan minimal satu QR code Copy Panel untuk dipinjam.', true);
            return;
        }
        
        const startDate = document.getElementById('tanggal_transaksi_date').value;
        const startTime = document.getElementById('tanggal_transaksi_time').value;
        const endDate = document.getElementById('tanggal_pengembalian_date').value;
        const endTime = document.getElementById('tanggal_pengembalian_time').value;
        
        if (startDate && startTime && endDate && endTime) {
            const startDateTime = new Date(startDate + 'T' + startTime + ':00');
            const endDateTime = new Date(endDate + 'T' + endTime + ':00');
            
            if (endDateTime <= startDateTime) {
                showPopupNotification('error', 'Tanggal dan waktu pengembalian harus setelah tanggal dan waktu transaksi.', true);
                return;
            }
        }
        
        document.getElementById('check-borrowing-btn').click();
    });
    
    // Reset form function
    function resetForm() {
        const currentTime = new Date();
        const currentDate = currentTime.toISOString().split('T')[0];
        const currentTimeFormatted = currentTime.toTimeString().slice(0, 5);
        
        document.getElementById('tanggal_transaksi_date').value = currentDate;
        document.getElementById('tanggal_transaksi_time').value = currentTimeFormatted;
        
        const tomorrow = new Date(currentTime);
        tomorrow.setDate(tomorrow.getDate() + 1);
        const tomorrowDate = tomorrow.toISOString().split('T')[0];
        
        document.getElementById('tanggal_pengembalian_date').value = tomorrowDate;
        document.getElementById('tanggal_pengembalian_time').value = currentTimeFormatted;
        
        document.getElementById('keterangan').value = '';
        document.getElementById('manual-code-input').value = '';
        
        cartData = [];
        updateCartDisplay();
        
        if (scannerActive) {
            stopQRScanner();
        }
        
        calculateAndDisplayDuration();
    }
    
    // Session messages
    <?php
    if (isset($_SESSION['success'])) {
        echo 'showPopupNotification("success", "' . addslashes($_SESSION['success']) . '", true);';
        unset($_SESSION['success']);
    }
    
    if (isset($_SESSION['error'])) {
        echo 'showPopupNotification("error", "' . addslashes($_SESSION['error']) . '", true);';
        unset($_SESSION['error']);
    }
    ?>
    
    updateCartDisplay();
    
    // Handle page visibility
    document.addEventListener('visibilitychange', function() {
        if (document.hidden && scannerActive) {
            stopQRScanner();
        }
    });
    
    window.addEventListener('beforeunload', function() {
        if (scannerActive) {
            stopQRScanner();
        }
    });
});
</script>

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