<?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'); // Use Asia/Makassar for WITA or Asia/Jayapura for WIT

// Redirect if not borrower user - using functions from connection.php
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, redirect to logout if not
if ($borrower_data['status'] == 'nonactive') {
    // Log this attempt
    error_log("Nonactive borrower attempted to access form: " . $_SESSION['username']);
    
    // Clear all session variables
    $_SESSION = array();
    
    // Destroy the session
    session_destroy();
    
    // Redirect to login with message
    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 with proper timezone
$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';
?>

<!-- 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">
        <h2 class="text-lg sm:text-xl lg:text-2xl font-bold text-gray-800 mb-3 sm:mb-4">Formulir peminjaman Color Code</h2>
        
        <!-- Server Time Display for Debugging -->
        <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>
            
            <!-- Input Code Barang Section -->
            <div class="bg-gray-50 p-3 sm:p-4 rounded-lg border">
                <div class="flex flex-col gap-3 mb-4">
                    <h3 class="text-sm sm:text-base lg:text-lg font-semibold text-gray-700">Input Code Barang</h3>
                    <button type="button" id="add-input-row" 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-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-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 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>
                        Tambah Peminjaman
                    </button>
                </div>
                
                <div id="input-container" class="space-y-3">
                    <!-- First input row -->
                    <div class="input-row flex flex-col gap-2">
                        <div class="flex-1">
                            <input type="text" class="kode-barang-input 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" placeholder="Masukkan code barang (contoh: CP.0001)">
                        </div>
                        <div class="flex gap-2">
                            <button type="button" class="add-item-btn 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-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 flex-1">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 sm:h-5 sm:w-5 mr-1" 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>
                                Add
                            </button>
                            <button type="button" class="remove-input-btn inline-flex items-center justify-center px-2 sm:px-3 py-2 border border-gray-300 rounded-md shadow-sm text-xs 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 w-12 sm:w-auto" disabled>
                                <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="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
                                </svg>
                            </button>
                        </div>
                    </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</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>
                
                <!-- Mobile-Optimized 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 via JavaScript -->
                                </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 masukkan code barang untuk ditambahkan.
                </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 to store cart items -->
            <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>
    
    <!-- Check Borrowing Modal - Ultra Responsive -->
    <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>
            
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            
            <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" id="modal-title">
                                Detail Peminjaman
                            </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 item yang akan dipinjam:
                                </p>
                                
                                <!-- Ultra Responsive Table Container -->
                                <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">
                                                    <!-- Cart items will be duplicated 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 Container -->
    <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 will go here -->
            </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">
                    Tutup
                </button>
            </div>
        </div>
    </div>
</main>

<script>
// Function to show popup notifications
function showPopupNotification(type, message, autoClose = false) {
    const popupContent = document.getElementById('popup-content');
    
    // Get appropriate icon and colors based on type
    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';
    }
    
    // Create the popup content
    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>
    `;
    
    // Show popup
    const popupNotification = document.getElementById('popup-notification');
    popupNotification.classList.remove('hidden');
    
    // Auto-close the notification after specified seconds if requested
    if (autoClose) {
        setTimeout(() => {
            popupNotification.classList.add('hidden');
        }, 8000);
    }
}

// Function to calculate and display 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 array
let cartData = [];

// Function to 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');
    
    // Show/hide cart container and submit button based on items
    if (cartData.length > 0) {
        cartContainer.classList.remove('hidden');
        cartEmptyMessage.classList.add('hidden');
        submitButton.removeAttribute('disabled');
    } else {
        cartEmptyMessage.classList.remove('hidden');
        submitButton.setAttribute('disabled', 'disabled');
    }
    
    // Clear current cart items
    cartItems.innerHTML = '';
    
    // Add each item to cart
    cartData.forEach((item, index) => {
        const row = document.createElement('tr');
        
        // Set row color based on status
        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);
    });
    
    // Update hidden input with JSON of cart items
    cartItemsInput.value = JSON.stringify(cartData);
    
    // Add event listeners to remove buttons
    document.querySelectorAll('.remove-from-cart').forEach(button => {
        button.addEventListener('click', function() {
            const index = parseInt(this.dataset.index);
            removeFromCart(index);
        });
    });
}

// Function to add item to cart
function addToCart(item) {
    // Check if item is already in cart
    const exists = cartData.some(cartItem => cartItem.id === item.id);
    
    if (exists) {
        showPopupNotification('warning', 'Item ini sudah ada di keranjang peminjaman.', true);
        return;
    }
    
    // Check if item status is "Dipinjam" and prevent adding
    if (item.status === 'Dipinjam') {
        showPopupNotification('error', `Code barang <strong>${item.kode_barang}</strong> sedang dipinjam oleh borrower lain dan tidak dapat dipinjam kembali.`);
        return;
    }
    
    // Add item to cart
    cartData.push(item);
    
    // Update cart display
    updateCartDisplay();
    
    // Show success message
    showPopupNotification('success', `Item <strong>${item.kode_barang}</strong> (${item.component_name}) berhasil ditambahkan ke keranjang peminjaman.`, true);
    
    // Show warnings based on status
    if (item.status === 'Rusak') {
        showPopupNotification('warning', `Code barang <strong>${item.kode_barang}</strong> dapat dipinjam, namun dengan kualitas warna yang sudah rusak dikhawatirkan kualitas yang dihasilkan nanti kurang bagus.`);
    }
}

// Function to remove item 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);
}

// Function to validate and add item by code
function validateAndAddItem(kodeBarang) {
    if (!kodeBarang || kodeBarang.trim() === '') {
        showPopupNotification('error', 'Silakan masukkan code barang terlebih dahulu.', true);
        return;
    }
    
    // Show loading message
    showPopupNotification('info', 'Mencari code barang...');
    
    // Fetch item details from server
    fetch(`validate_code_barang.php?kode_barang=${encodeURIComponent(kodeBarang.trim())}`)
        .then(response => response.json())
        .then(data => {
            // Hide loading message
            document.getElementById('popup-notification').classList.add('hidden');
            
            if (data.success) {
                addToCart(data.item);
            } else {
                showPopupNotification('error', data.message || 'Maaf code barang tidak ada di master color panel.', true);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('popup-notification').classList.add('hidden');
            showPopupNotification('error', 'Terjadi kesalahan saat memvalidasi code barang. Silakan coba lagi.', true);
        });
}

document.addEventListener('DOMContentLoaded', function() {
    // Calculate initial duration
    calculateAndDisplayDuration();
    
    // Date and 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);
    
    // Close popup when button is clicked
    document.getElementById('close-popup').addEventListener('click', function() {
        document.getElementById('popup-notification').classList.add('hidden');
    });
    
    // Add input row functionality
    document.getElementById('add-input-row').addEventListener('click', function() {
        const inputContainer = document.getElementById('input-container');
        const newRow = document.createElement('div');
        newRow.className = 'input-row flex flex-col gap-2';
        newRow.innerHTML = `
            <div class="flex-1">
                <input type="text" class="kode-barang-input 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" placeholder="Masukkan code barang (contoh: CP.0001)">
            </div>
            <div class="flex gap-2">
                <button type="button" class="add-item-btn 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-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 flex-1">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 sm:h-5 sm:w-5 mr-1" 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>
                    Add
                </button>
                <button type="button" class="remove-input-btn inline-flex items-center justify-center px-2 sm:px-3 py-2 border border-gray-300 rounded-md shadow-sm text-xs 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 w-12 sm:w-auto">
                    <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="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
                    </svg>
                </button>
            </div>
        `;
        inputContainer.appendChild(newRow);
        updateRemoveButtonStates();
        attachInputRowEvents(newRow);
    });
    
    // Update remove button states
    function updateRemoveButtonStates() {
        const inputRows = document.querySelectorAll('.input-row');
        inputRows.forEach((row, index) => {
            const removeBtn = row.querySelector('.remove-input-btn');
            if (inputRows.length === 1) {
                removeBtn.disabled = true;
                removeBtn.classList.add('opacity-50', 'cursor-not-allowed');
            } else {
                removeBtn.disabled = false;
                removeBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            }
        });
    }
    
    // Attach events to input row
    function attachInputRowEvents(row) {
        // Add button click event
        const addBtn = row.querySelector('.add-item-btn');
        const input = row.querySelector('.kode-barang-input');
        const removeBtn = row.querySelector('.remove-input-btn');
        
        addBtn.addEventListener('click', function() {
            const kodeBarang = input.value.trim();
            validateAndAddItem(kodeBarang);
            input.value = ''; // Clear input after adding
        });
        
        // Enter key on input
        input.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                addBtn.click();
            }
        });
        
        // Remove button click event
        removeBtn.addEventListener('click', function() {
            if (document.querySelectorAll('.input-row').length > 1) {
                row.remove();
                updateRemoveButtonStates();
            }
        });
    }
    
    // Attach events to initial input row
    attachInputRowEvents(document.querySelector('.input-row'));
    updateRemoveButtonStates();
    
    // Clear cart button
    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 masukkan code barang terlebih dahulu.', true);
            return;
        }
        
        // Fill modal with cart items
        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);
        });
        
        // Format dates and times for display
        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);
        };
        
        // Calculate duration for modal
        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';
        }
        
        // Fill transaction details
        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 || '-';
        
        // Show modal
        document.getElementById('check-borrowing-modal').classList.remove('hidden');
    });
    
    // Modal close button
    document.getElementById('modal-close').addEventListener('click', function() {
        document.getElementById('check-borrowing-modal').classList.add('hidden');
    });
    
    // Modal submit button
    document.getElementById('modal-submit').addEventListener('click', function() {
        // Show loading notification
        showPopupNotification('info', 'Memproses permintaan peminjaman, mohon tunggu...');
        
        // Disable the modal submit button to prevent double submission
        const modalSubmit = document.getElementById('modal-submit');
        modalSubmit.disabled = true;
        modalSubmit.textContent = 'Memproses...';
        
        // Hide modal
        document.getElementById('check-borrowing-modal').classList.add('hidden');
        
        // Submit form via AJAX
        const formData = new FormData(document.getElementById('peminjaman-form'));
        
        fetch('proses_peminjaman.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            // Hide loading notification
            document.getElementById('popup-notification').classList.add('hidden');
            
            if (data.success) {
                // Show success notification
                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);
                
                // Reset form after successful submission
                setTimeout(() => {
                    resetForm();
                }, 2000);
            } else {
                // Show error notification
                showPopupNotification('error', data.message, true);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            // Hide loading notification
            document.getElementById('popup-notification').classList.add('hidden');
            
            // Show error notification
            showPopupNotification('error', 'Terjadi kesalahan sistem. Silakan coba lagi.', true);
        })
        .finally(() => {
            // Re-enable the modal submit button
            modalSubmit.disabled = false;
            modalSubmit.textContent = 'Konfirmasi Peminjaman';
        });
    });
    
    // Form validation - prevent default form submission
    document.getElementById('peminjaman-form').addEventListener('submit', function(e) {
        e.preventDefault(); // Always prevent default submission
        
        if (cartData.length === 0) {
            showPopupNotification('error', 'Keranjang peminjaman kosong. Silakan masukkan minimal satu code barang untuk dipinjam.', true);
            return;
        }
        
        // Validate dates
        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;
            }
        }
        
        // Trigger check borrowing modal
        document.getElementById('check-borrowing-btn').click();
    });
    
    // Function to reset form after successful submission
    function resetForm() {
        // Reset date and time
        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;
        
        // Reset keterangan
        document.getElementById('keterangan').value = '';
        
        // Clear all input rows except the first one
        const inputContainer = document.getElementById('input-container');
        const inputRows = inputContainer.querySelectorAll('.input-row');
        for (let i = inputRows.length - 1; i > 0; i--) {
            inputRows[i].remove();
        }
        
        // Clear the first input
        inputContainer.querySelector('.kode-barang-input').value = '';
        
        // Clear cart data
        cartData = [];
        updateCartDisplay();
        
        // Update remove button states
        updateRemoveButtonStates();
        
        // Recalculate duration
        calculateAndDisplayDuration();
    }
    
    // Display session messages if they exist
    <?php
    // Display session messages if they exist
    if (isset($_SESSION['success'])) {
        echo 'const sessionSuccess = "' . addslashes($_SESSION['success']) . '";';
        echo 'showPopupNotification("success", sessionSuccess, true);';
        unset($_SESSION['success']);
    }
    
    if (isset($_SESSION['error'])) {
        echo 'const sessionError = "' . addslashes($_SESSION['error']) . '";';
        echo 'showPopupNotification("error", sessionError, true);';
        unset($_SESSION['error']);
    }
    ?>
    
    // Initialize cart display
    updateCartDisplay();
    
    // Add mobile-specific optimizations
    if (window.innerWidth <= 640) { // Mobile devices
        // Reduce auto-close time for mobile
        const originalShowPopupNotification = showPopupNotification;
        showPopupNotification = function(type, message, autoClose = false) {
            return originalShowPopupNotification(type, message, autoClose);
        };
        
        // Improve touch targets on mobile
        document.querySelectorAll('button, input, select, textarea').forEach(element => {
            element.style.minHeight = '44px'; // Apple's recommended minimum touch target
        });
        
        // Handle mobile keyboard visibility
        const viewport = document.querySelector('meta[name=viewport]');
        if (viewport) {
            let viewportContent = viewport.getAttribute('content');
            
            // When input is focused, adjust viewport to prevent zoom
            document.querySelectorAll('input, textarea').forEach(input => {
                input.addEventListener('focus', function() {
                    if (viewport) {
                        viewport.setAttribute('content', viewportContent + ', user-scalable=no');
                    }
                });
                
                input.addEventListener('blur', function() {
                    if (viewport) {
                        viewport.setAttribute('content', viewportContent);
                    }
                });
            });
        }
        
        // Optimize modal for mobile
        const modal = document.getElementById('check-borrowing-modal');
        if (modal) {
            modal.addEventListener('touchstart', function(e) {
                // Prevent scrolling background when modal is open
                if (e.target === modal) {
                    e.preventDefault();
                }
            });
        }
    }
    
    // Handle orientation change for mobile
    window.addEventListener('orientationchange', function() {
        setTimeout(function() {
            // Recalculate layout after orientation change
            const modal = document.getElementById('check-borrowing-modal');
            if (modal && !modal.classList.contains('hidden')) {
                // Force recalculation of modal position
                modal.style.display = 'none';
                modal.offsetHeight; // Trigger reflow
                modal.style.display = '';
            }
        }, 100);
    });
    
    // Add swipe gesture support for mobile
    let touchStartX = 0;
    let touchStartY = 0;
    
    document.addEventListener('touchstart', function(e) {
        touchStartX = e.touches[0].clientX;
        touchStartY = e.touches[0].clientY;
    });
    
    document.addEventListener('touchend', function(e) {
        if (!touchStartX || !touchStartY) {
            return;
        }
        
        let touchEndX = e.changedTouches[0].clientX;
        let touchEndY = e.changedTouches[0].clientY;
        
        let diffX = touchStartX - touchEndX;
        let diffY = touchStartY - touchEndY;
        
        // Only handle horizontal swipes that are more significant than vertical
        if (Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 50) {
            // Optional: Add swipe functionality here if needed
            // For example, swipe to close modal or navigate
        }
        
        touchStartX = 0;
        touchStartY = 0;
    });
});
</script>

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