<?php
require_once '../config/connection.php';
checkUserType(['admin']);

$message = '';
$message_type = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'];
    
    if ($action == 'add_to_cart') {
        $asset_number = $_POST['asset_number'];
        $borrower_id = $_POST['borrower_id'];
        $session_id = $_POST['session_id'];
        
        try {
            // Check if asset exists and available
            $stmt = $pdo->prepare("
                SELECT id, asset_name, status_borrower, kondisi 
                FROM assets 
                WHERE asset_number = ?
            ");
            $stmt->execute([$asset_number]);
            $asset = $stmt->fetch();
            
            if (!$asset) {
                throw new Exception("Asset dengan nomor $asset_number tidak ditemukan!");
            }
            
            if ($asset['status_borrower'] != 'available') {
                throw new Exception("Asset sedang tidak tersedia!");
            }
            
            if ($asset['kondisi'] == 'hilang') {
                throw new Exception("Asset dalam kondisi hilang!");
            }
            
            // Check if already in cart
            $stmt = $pdo->prepare("
                SELECT COUNT(*) as count 
                FROM borrow_cart 
                WHERE session_id = ? AND asset_id = ?
            ");
            $stmt->execute([$session_id, $asset['id']]);
            if ($stmt->fetch()['count'] > 0) {
                throw new Exception("Asset sudah ada di keranjang!");
            }
            
            // Add to cart
            $stmt = $pdo->prepare("
                INSERT INTO borrow_cart (session_id, borrower_employee_id, asset_id) 
                VALUES (?, ?, ?)
            ");
            $stmt->execute([$session_id, $borrower_id, $asset['id']]);
            
            $message = "Asset berhasil ditambahkan ke keranjang!";
            $message_type = 'success';
            
        } catch (Exception $e) {
            $message = $e->getMessage();
            $message_type = 'error';
        }
    }
    
    if ($action == 'remove_from_cart') {
        $cart_id = $_POST['cart_id'];
        
        $stmt = $pdo->prepare("DELETE FROM borrow_cart WHERE id = ?");
        $stmt->execute([$cart_id]);
        
        $message = "Item berhasil dihapus dari keranjang!";
        $message_type = 'success';
    }
    
    if ($action == 'submit_borrow') {
        $session_id = $_POST['session_id'];
        $borrower_id = $_POST['borrower_id'];
        $workcenter = $_POST['workcenter'];
        $preference_pro = $_POST['preference_pro'];
        $notes = $_POST['notes'] ?? '';
        
        try {
            $pdo->beginTransaction();
            
            // Get cart items
            $stmt = $pdo->prepare("
                SELECT bc.*, a.asset_name 
                FROM borrow_cart bc 
                JOIN assets a ON bc.asset_id = a.id 
                WHERE bc.session_id = ?
            ");
            $stmt->execute([$session_id]);
            $cart_items = $stmt->fetchAll();
            
            if (empty($cart_items)) {
                throw new Exception("Keranjang kosong!");
            }
            
            // Get borrower info
            $stmt = $pdo->prepare("SELECT organization FROM borrowers WHERE employee_id = ?");
            $stmt->execute([$borrower_id]);
            $borrower = $stmt->fetch();
            
            if (!$borrower) {
                throw new Exception("Borrower tidak ditemukan!");
            }
            
            // Insert borrow history for each item
            foreach ($cart_items as $item) {
                $stmt = $pdo->prepare("
                    INSERT INTO borrow_history 
                    (asset_id, borrower_employee_id, borrow_date, notes, workcenter, organization, 
                     preference_pro, status, tanggal_peminjam, created_by) 
                    VALUES (?, ?, CURDATE(), ?, ?, ?, ?, 'pending_approval', NOW(), ?)
                ");
                $stmt->execute([
                    $item['asset_id'], 
                    $borrower_id, 
                    $notes, 
                    $workcenter, 
                    $borrower['organization'], 
                    $preference_pro, 
                    $_SESSION['user_id']
                ]);
                
                // Update asset status to pending
                $stmt = $pdo->prepare("UPDATE assets SET status = 'pending_approval' WHERE id = ?");
                $stmt->execute([$item['asset_id']]);
            }
            
            // Clear cart
            $stmt = $pdo->prepare("DELETE FROM borrow_cart WHERE session_id = ?");
            $stmt->execute([$session_id]);
            
            $pdo->commit();
            
            $message = "Permintaan peminjaman berhasil disubmit! Menunggu persetujuan admin.";
            $message_type = 'success';
            
        } catch (Exception $e) {
            $pdo->rollback();
            $message = $e->getMessage();
            $message_type = 'error';
        }
    }
}

// Generate session ID for cart
$session_id = $_SESSION['cart_session'] ?? uniqid();
$_SESSION['cart_session'] = $session_id;

// Get borrowers
$stmt = $pdo->prepare("SELECT employee_id, full_name, organization, jabatan FROM borrowers WHERE is_active = 1 ORDER BY full_name");
$stmt->execute();
$borrowers = $stmt->fetchAll();

// Get cart items
$stmt = $pdo->prepare("
    SELECT bc.*, a.asset_name, a.asset_number, a.asset_category, a.kondisi, b.full_name as borrower_name
    FROM borrow_cart bc 
    JOIN assets a ON bc.asset_id = a.id 
    JOIN borrowers b ON bc.borrower_employee_id = b.employee_id
    WHERE bc.session_id = ?
    ORDER BY bc.created_at DESC
");
$stmt->execute([$session_id]);
$cart_items = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Borrower - Peminjaman Tools Room</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'leaf-green': '#90EE90',
                        'dark-leaf': '#32CD32',
                        'soft-gray': '#F5F5F5'
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-soft-gray min-h-screen">
    <!-- Header -->
    <header class="bg-white shadow-sm border-b-2 border-leaf-green">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center py-4">
                <div class="flex items-center space-x-4">
                    <a href="dashboard.php" class="text-dark-leaf hover:text-green-600">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
                        </svg>
                    </a>
                    <img src="../images/logo.png" alt="Logo" class="h-10 w-10" onerror="this.style.display='none'">
                    <div>
                        <h1 class="text-xl font-bold text-gray-800">Borrower</h1>
                        <p class="text-sm text-gray-500">Proses peminjaman asset</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <span class="text-sm text-gray-600"><?php echo $_SESSION['user_name']; ?></span>
                    <a href="../logout.php" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg text-sm">
                        Logout
                    </a>
                </div>
            </div>
        </div>
    </header>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Message -->
        <?php if ($message): ?>
        <div class="mb-6 p-4 rounded-lg <?php echo $message_type == 'success' ? 'bg-green-100 border border-green-400 text-green-700' : 'bg-red-100 border border-red-400 text-red-700'; ?>">
            <div class="flex items-center">
                <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="<?php echo $message_type == 'success' ? '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' : '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"></path>
                </svg>
                <?php echo $message; ?>
            </div>
        </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <!-- Left Panel - Form -->
            <div class="space-y-6">
                <!-- Borrower Selection -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">Dipinjam Oleh</h3>
                    <div class="relative">
                        <input type="text" id="borrower-search" 
                               placeholder="Ketik nama atau employee ID..."
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf">
                        <div id="borrower-dropdown" class="hidden absolute z-10 w-full bg-white border border-gray-300 rounded-lg mt-1 max-h-60 overflow-y-auto">
                            <?php foreach ($borrowers as $borrower): ?>
                            <div class="borrower-option px-4 py-3 hover:bg-gray-50 cursor-pointer border-b border-gray-100"
                                 data-id="<?php echo $borrower['employee_id']; ?>"
                                 data-name="<?php echo $borrower['full_name']; ?>"
                                 data-org="<?php echo $borrower['organization']; ?>"
                                 data-jabatan="<?php echo $borrower['jabatan']; ?>">
                                <div class="font-medium text-gray-800"><?php echo $borrower['full_name']; ?></div>
                                <div class="text-sm text-gray-600"><?php echo $borrower['employee_id']; ?> • <?php echo $borrower['jabatan']; ?></div>
                                <div class="text-xs text-gray-500"><?php echo $borrower['organization']; ?></div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div id="selected-borrower" class="hidden mt-4 p-3 bg-green-50 rounded-lg border border-green-200">
                        <div class="flex justify-between items-start">
                            <div>
                                <div class="font-medium text-green-800" id="borrower-name"></div>
                                <div class="text-sm text-green-600" id="borrower-details"></div>
                            </div>
                            <button onclick="clearBorrower()" class="text-red-500 hover:text-red-700">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Asset Scanner -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">Scan Asset</h3>
                    
                    <!-- Manual Input -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Asset Number</label>
                        <div class="flex gap-2">
                            <input type="text" id="manual-asset" 
                                   placeholder="Masukkan asset number (contoh: T000160)"
                                   class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf">
                            <button onclick="searchAsset()" 
                                    class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg">
                                Cari
                            </button>
                        </div>
                    </div>

                    <!-- Scanner -->
                    <div class="text-center">
                        <button id="start-scan" onclick="startScanner()" 
                                class="bg-dark-leaf hover:bg-green-600 text-white px-6 py-3 rounded-lg font-semibold">
                            <svg class="w-5 h-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h2M4 4h5m3 0h6m4 0h2M4 20h5m3 0h6m4 0h2"></path>
                            </svg>
                            Scan QR/Barcode
                        </button>
                        <div id="qr-reader" class="hidden mt-4"></div>
                        <button id="stop-scan" onclick="stopScanner()" 
                                class="hidden bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg mt-2">
                            Stop Scan
                        </button>
                    </div>

                    <!-- Asset Details -->
                    <div id="asset-details" class="hidden mt-6 p-4 bg-blue-50 rounded-lg border border-blue-200">
                        <h4 class="font-semibold text-blue-800 mb-2">Detail Asset</h4>
                        <div id="asset-info"></div>
                        <button onclick="addToCart()" 
                                class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg mt-3">
                            Add to Cart
                        </button>
                    </div>
                </div>

                <!-- Loan Details -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">Detail Peminjaman</h3>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">workcenter *</label>
                            <input type="text" id="workcenter" required
                                   placeholder="Nama workcenter yang akan digunakan"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Preference Pro *</label>
                            <input type="text" id="preference-pro" required
                                   placeholder="Preference pro"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Catatan (Optional)</label>
                            <textarea id="notes" rows="3"
                                      placeholder="Catatan tambahan..."
                                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf"></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Right Panel - Cart -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-800">Keranjang Peminjaman</h3>
                    <span class="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm font-medium">
                        <?php echo count($cart_items); ?> items
                    </span>
                </div>

                <div id="cart-items" class="space-y-3 mb-6">
                    <?php if (empty($cart_items)): ?>
                    <div class="text-center py-8 text-gray-500">
                        <svg class="w-12 h-12 mx-auto mb-3 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5H3m4 8l2.05 5.04A1 1 0 0010.45 19H18M9 19a2 2 0 11-4 0 2 2 0 014 0zM20 19a2 2 0 11-4 0 2 2 0 014 0z"></path>
                        </svg>
                        <p>Keranjang kosong</p>
                        <p class="text-sm">Scan atau masukkan asset number untuk menambah item</p>
                    </div>
                    <?php else: ?>
                        <?php foreach ($cart_items as $item): ?>
                        <div class="border border-gray-200 rounded-lg p-3">
                            <div class="flex justify-between items-start">
                                <div class="flex-1">
                                    <h4 class="font-medium text-gray-800"><?php echo $item['asset_name']; ?></h4>
                                    <p class="text-sm text-gray-600"><?php echo $item['asset_number']; ?> • <?php echo $item['asset_category']; ?></p>
                                    <p class="text-xs text-gray-500">
                                        Kondisi: <span class="<?php echo $item['kondisi'] == 'baik' ? 'text-green-600' : 'text-yellow-600'; ?>">
                                            <?php echo ucfirst($item['kondisi']); ?>
                                        </span>
                                    </p>
                                    <p class="text-xs text-blue-600 mt-1">Peminjam: <?php echo $item['borrower_name']; ?></p>
                                </div>
                                <form method="POST" class="inline">
                                    <input type="hidden" name="action" value="remove_from_cart">
                                    <input type="hidden" name="cart_id" value="<?php echo $item['id']; ?>">
                                    <button type="submit" class="text-red-500 hover:text-red-700">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                        </svg>
                                    </button>
                                </form>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <!-- Submit Form -->
                <?php if (!empty($cart_items)): ?>
                <form method="POST" onsubmit="return validateSubmit()">
                    <input type="hidden" name="action" value="submit_borrow">
                    <input type="hidden" name="session_id" value="<?php echo $session_id; ?>">
                    <input type="hidden" name="borrower_id" id="form-borrower-id">
                    <input type="hidden" name="workcenter" id="form-workcenter">
                    <input type="hidden" name="preference_pro" id="form-preference-pro">
                    <input type="hidden" name="notes" id="form-notes">
                    
                    <button type="submit" 
                            class="w-full bg-dark-leaf hover:bg-green-600 text-white py-3 px-6 rounded-lg font-semibold transition duration-200">
                        <svg class="w-5 h-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                        </svg>
                        Submit Peminjaman
                    </button>
                </form>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        let html5QrCode;
        let selectedBorrower = null;
        let currentAsset = null;

        // Borrower search functionality
        document.getElementById('borrower-search').addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const dropdown = document.getElementById('borrower-dropdown');
            const options = dropdown.querySelectorAll('.borrower-option');
            
            if (searchTerm.length > 0) {
                dropdown.classList.remove('hidden');
                
                options.forEach(option => {
                    const name = option.querySelector('.font-medium').textContent.toLowerCase();
                    const id = option.dataset.id.toLowerCase();
                    
                    if (name.includes(searchTerm) || id.includes(searchTerm)) {
                        option.classList.remove('hidden');
                    } else {
                        option.classList.add('hidden');
                    }
                });
            } else {
                dropdown.classList.add('hidden');
            }
        });

        // Borrower selection
        document.querySelectorAll('.borrower-option').forEach(option => {
            option.addEventListener('click', function() {
                selectedBorrower = {
                    id: this.dataset.id,
                    name: this.dataset.name,
                    org: this.dataset.org,
                    jabatan: this.dataset.jabatan
                };
                
                document.getElementById('borrower-search').value = this.dataset.name;
                document.getElementById('borrower-dropdown').classList.add('hidden');
                
                // Show selected borrower
                document.getElementById('selected-borrower').classList.remove('hidden');
                document.getElementById('borrower-name').textContent = selectedBorrower.name;
                document.getElementById('borrower-details').textContent = 
                    `${selectedBorrower.id} • ${selectedBorrower.jabatan} • ${selectedBorrower.org}`;
            });
        });

        function clearBorrower() {
            selectedBorrower = null;
            document.getElementById('borrower-search').value = '';
            document.getElementById('selected-borrower').classList.add('hidden');
        }

        // Hide dropdown when clicking outside
        document.addEventListener('click', function(e) {
            if (!e.target.closest('#borrower-search') && !e.target.closest('#borrower-dropdown')) {
                document.getElementById('borrower-dropdown').classList.add('hidden');
            }
        });

        // Scanner functionality
        function startScanner() {
            const qrReader = document.getElementById('qr-reader');
            qrReader.classList.remove('hidden');
            document.getElementById('start-scan').classList.add('hidden');
            document.getElementById('stop-scan').classList.remove('hidden');

            html5QrCode = new Html5Qrcode("qr-reader");
            
            html5QrCode.start(
                { facingMode: "environment" },
                {
                    fps: 10,
                    qrbox: { width: 250, height: 250 }
                },
                (decodedText, decodedResult) => {
                    // Process scanned result
                    processScannedAsset(decodedText);
                    stopScanner();
                },
                (errorMessage) => {
                    // Handle scan error
                }
            ).catch(err => {
                console.error('Error starting scanner:', err);
                alert('Error starting camera. Please ensure camera permissions are granted.');
                stopScanner();
            });
        }

        function stopScanner() {
            if (html5QrCode) {
                html5QrCode.stop().then(() => {
                    html5QrCode.clear();
                }).catch(err => {
                    console.error('Error stopping scanner:', err);
                });
            }
            
            document.getElementById('qr-reader').classList.add('hidden');
            document.getElementById('start-scan').classList.remove('hidden');
            document.getElementById('stop-scan').classList.add('hidden');
        }

        function processScannedAsset(assetNumber) {
            // Extract asset number if it's a full URL or contains extra data
            const matches = assetNumber.match(/[A-Z]\d{6}/);
            if (matches) {
                assetNumber = matches[0];
            }
            
            document.getElementById('manual-asset').value = assetNumber;
            searchAsset();
        }

        function searchAsset() {
            const assetNumber = document.getElementById('manual-asset').value.trim();
            
            if (!assetNumber) {
                alert('Masukkan asset number terlebih dahulu');
                return;
            }

            // AJAX call to get asset details
            fetch('get_asset.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'asset_number=' + encodeURIComponent(assetNumber)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    currentAsset = data.asset;
                    showAssetDetails(data.asset);
                } else {
                    alert(data.message);
                    document.getElementById('asset-details').classList.add('hidden');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Terjadi kesalahan saat mencari asset');
            });
        }

        function showAssetDetails(asset) {
            const detailsDiv = document.getElementById('asset-details');
            const infoDiv = document.getElementById('asset-info');
            
            let statusClass = 'text-gray-600';
            let statusText = asset.status_borrower;
            let kondisiClass = asset.kondisi === 'baik' ? 'text-green-600' : (asset.kondisi === 'rusak' ? 'text-yellow-600' : 'text-red-600');
            let canBorrow = true;
            let warningMessage = '';

            if (asset.status_borrower === 'available') {
                if (asset.kondisi === 'hilang') {
                    statusClass = 'text-red-600';
                    canBorrow = false;
                    warningMessage = 'Asset dalam kondisi hilang dan tidak dapat dipinjam!';
                } else if (asset.kondisi === 'rusak') {
                    statusClass = 'text-yellow-600';
                    warningMessage = 'Asset dalam kondisi rusak, namun masih dapat dipinjam.';
                } else {
                    statusClass = 'text-green-600';
                }
            } else {
                statusClass = 'text-red-600';
                canBorrow = false;
                warningMessage = `Asset sedang ${asset.status_borrower === 'borrowed' ? 'dipinjam' : 'maintenance'} dan tidak dapat dipinjam!`;
            }

            infoDiv.innerHTML = `
                <div class="space-y-2">
                    <div><span class="font-medium">Nama:</span> ${asset.asset_name}</div>
                    <div><span class="font-medium">Nomor:</span> ${asset.asset_number}</div>
                    <div><span class="font-medium">Kategori:</span> ${asset.asset_category}</div>
                    <div><span class="font-medium">Status:</span> <span class="${statusClass}">${statusText}</span></div>
                    <div><span class="font-medium">Kondisi:</span> <span class="${kondisiClass}">${asset.kondisi}</span></div>
                    ${asset.description ? `<div><span class="font-medium">Deskripsi:</span> ${asset.description}</div>` : ''}
                    ${warningMessage ? `<div class="mt-3 p-2 rounded ${canBorrow ? 'bg-yellow-50 text-yellow-800' : 'bg-red-50 text-red-800'}">${warningMessage}</div>` : ''}
                </div>
            `;

            // Show/hide add button based on availability
            const addButton = detailsDiv.querySelector('button');
            if (canBorrow) {
                addButton.classList.remove('hidden');
                addButton.disabled = false;
            } else {
                addButton.classList.add('hidden');
                addButton.disabled = true;
            }

            detailsDiv.classList.remove('hidden');
        }

        function addToCart() {
            if (!selectedBorrower) {
                alert('Pilih borrower terlebih dahulu!');
                return;
            }

            if (!currentAsset) {
                alert('Tidak ada asset yang dipilih!');
                return;
            }

            // Create form and submit
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="action" value="add_to_cart">
                <input type="hidden" name="asset_number" value="${currentAsset.asset_number}">
                <input type="hidden" name="borrower_id" value="${selectedBorrower.id}">
                <input type="hidden" name="session_id" value="<?php echo $session_id; ?>">
            `;
            
            document.body.appendChild(form);
            form.submit();
        }

        function validateSubmit() {
            if (!selectedBorrower) {
                alert('Pilih borrower terlebih dahulu!');
                return false;
            }

            const workcenter = document.getElementById('workcenter').value.trim();
            const preferencePro = document.getElementById('preference-pro').value.trim();

            if (!workcenter) {
                alert('Nama workcenter harus diisi!');
                return false;
            }

            if (!preferencePro) {
                alert('Preference pro harus diisi!');
                return false;
            }

            // Set form values
            document.getElementById('form-borrower-id').value = selectedBorrower.id;
            document.getElementById('form-workcenter').value = workcenter;
            document.getElementById('form-preference-pro').value = preferencePro;
            document.getElementById('form-notes').value = document.getElementById('notes').value;

            return confirm('Yakin ingin submit peminjaman? Data akan dikirim untuk persetujuan admin.');
        }
    </script>
</body>
</html>