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

$message = '';
$message_type = '';
$asset_data = null;
$borrower_organization = getBorrowerOrganization($pdo, $_SESSION['employee_id']);

// Handle AJAX requests
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json');
    
    if ($_POST['action'] == 'scan_asset') {
        $asset_number = sanitize($_POST['asset_number']);
        
        $stmt = $pdo->prepare("
            SELECT a.*, 
                   CASE 
                       WHEN a.status_borrower = 'available' AND a.kondisi IN ('baik', 'rusak') THEN 1
                       ELSE 0
                   END as is_available
            FROM assets a 
            WHERE a.asset_number = ?
        ");
        $stmt->execute([$asset_number]);
        $asset = $stmt->fetch();
        
        if ($asset) {
            echo json_encode([
                'success' => true,
                'asset' => $asset,
                'message' => $asset['is_available'] ? 'Asset ditemukan dan tersedia!' : 'Asset ditemukan tapi tidak tersedia untuk dipinjam.'
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Asset tidak ditemukan!'
            ]);
        }
        exit;
    }
    
    if ($_POST['action'] == 'add_to_cart') {
        try {
            $asset_id = (int)$_POST['asset_id'];
            $session_id = session_id();
            
            // Check if asset is available
            if (isAssetAvailableForBorrow($pdo, $asset_id)) {
                // Check if already in cart
                $stmt = $pdo->prepare("
                    SELECT id FROM borrow_cart 
                    WHERE borrower_employee_id = ? AND asset_id = ?
                ");
                $stmt->execute([$_SESSION['employee_id'], $asset_id]);
                
                if (!$stmt->fetch()) {
                    // Add to cart
                    $stmt = $pdo->prepare("
                        INSERT INTO borrow_cart (session_id, borrower_employee_id, asset_id) 
                        VALUES (?, ?, ?)
                    ");
                    $stmt->execute([$session_id, $_SESSION['employee_id'], $asset_id]);
                    
                    echo json_encode(['success' => true, 'message' => 'Asset berhasil ditambahkan ke keranjang!']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Asset sudah ada di keranjang!']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'Asset tidak tersedia untuk dipinjam!']);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
        exit;
    }
    
    if ($_POST['action'] == 'remove_from_cart') {
        $cart_id = (int)$_POST['cart_id'];
        
        $stmt = $pdo->prepare("
            DELETE FROM borrow_cart 
            WHERE id = ? AND borrower_employee_id = ?
        ");
        $stmt->execute([$cart_id, $_SESSION['employee_id']]);
        
        echo json_encode(['success' => true, 'message' => 'Asset dihapus dari keranjang!']);
        exit;
    }
    
    if ($_POST['action'] == 'get_cart') {
        try {
            $stmt = $pdo->prepare("
                SELECT bc.id as cart_id, a.* 
                FROM borrow_cart bc
                JOIN assets a ON bc.asset_id = a.id
                WHERE bc.borrower_employee_id = ?
                ORDER BY bc.created_at DESC
            ");
            $stmt->execute([$_SESSION['employee_id']]);
            $cart_items = $stmt->fetchAll();
            
            echo json_encode(['success' => true, 'items' => $cart_items]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage(), 'items' => []]);
        }
        exit;
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !isset($_POST['ajax'])) {
    if (isset($_POST['submit_borrow'])) {
        $preference_pro = sanitize($_POST['preference_pro']);
        $mesin = sanitize($_POST['mesin']);
        $notes = sanitize($_POST['notes']);
        
        if (empty($preference_pro)) {
            $message = 'Preference Pro harus diisi!';
            $message_type = 'error';
        } elseif (empty($mesin)) {
            $message = 'Mesin harus diisi!';
            $message_type = 'error';
        } else {
            // Get cart items
            $stmt = $pdo->prepare("
                SELECT bc.id as cart_id, bc.asset_id, a.asset_name, a.asset_number
                FROM borrow_cart bc
                JOIN assets a ON bc.asset_id = a.id
                WHERE bc.borrower_employee_id = ?
            ");
            $stmt->execute([$_SESSION['employee_id']]);
            $cart_items = $stmt->fetchAll();
            
            if (empty($cart_items)) {
                $message = 'Keranjang kosong! Silakan tambahkan asset terlebih dahulu.';
                $message_type = 'error';
            } else {
                try {
                    $pdo->beginTransaction();
                    
                    $current_timestamp = date('Y-m-d H:i:s');
                    
                    foreach ($cart_items as $item) {
                        // Check availability one more time
                        if (!isAssetAvailableForBorrow($pdo, $item['asset_id'])) {
                            throw new Exception("Asset {$item['asset_name']} tidak lagi tersedia!");
                        }
                        
                        // Insert borrow request with status 'pending_approval'
                        $stmt = $pdo->prepare("
                            INSERT INTO borrow_history 
                            (asset_id, borrower_employee_id, borrow_date, notes, preference_pro, mesin, organization, created_by, status, created_at) 
                            VALUES (?, ?, CURDATE(), ?, ?, ?, ?, ?, 'pending_approval', ?)
                        ");
                        $stmt->execute([
                            $item['asset_id'],
                            $_SESSION['employee_id'],
                            $notes,
                            $preference_pro,
                            $mesin,
                            $borrower_organization,
                            $_SESSION['employee_id'],
                            $current_timestamp
                        ]);
                    }
                    
                    // Clear cart
                    clearBorrowCart($pdo, $_SESSION['employee_id']);
                    
                    $pdo->commit();
                    
                    $message = 'Permintaan peminjaman berhasil diajukan untuk ' . count($cart_items) . ' asset! Menunggu persetujuan admin.';
                    $message_type = 'success';
                    
                } catch (Exception $e) {
                    $pdo->rollback();
                    $message = 'Terjadi kesalahan: ' . $e->getMessage();
                    $message_type = 'error';
                }
            }
        }
    }
}

// Get available assets for display
$stmt = $pdo->prepare("
    SELECT * FROM assets 
    WHERE status_borrower = 'available' AND kondisi IN ('baik', 'rusak')
    ORDER BY asset_name
");
$stmt->execute();
$available_assets = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajukan Peminjaman - Peminjaman Tools Room</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'leaf-green': '#90EE90',
                        'dark-leaf': '#32CD32',
                        'soft-gray': '#F5F5F5',
                        'medium-gray': '#9CA3AF'
                    }
                }
            }
        }
    </script>
    <style>
        /* Styling untuk scanner yang lebih baik */
        #reader {
            border: 3px solid #90EE90;
            border-radius: 12px;
            overflow: hidden;
            background: #000;
            position: relative;
        }
        
        #reader video {
            width: 100% !important;
            height: auto !important;
            display: block;
        }
        
        #reader__scan_region {
            min-height: 300px !important;
        }
        
        #reader__dashboard_section {
            padding: 10px 0 !important;
        }
        
        #reader__dashboard_section_csr button {
            background: #32CD32 !important;
            color: white !important;
            border: none !important;
            padding: 8px 16px !important;
            border-radius: 6px !important;
            margin: 5px !important;
        }
        
        /* Loading indicator */
        .scanner-loading {
            text-align: center;
            padding: 20px;
            color: #32CD32;
        }
        
        /* Smooth transitions */
        #scanner-container {
            transition: all 0.3s ease-in-out;
        }
    </style>
</head>
<body class="bg-soft-gray min-h-screen">
    <!-- Header -->
    <header class="bg-white shadow-sm border-b-2 border-leaf-green sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-3 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center py-3 sm:py-4">
                <div class="flex items-center space-x-2 sm:space-x-4">
                    <a href="dashboard.php" class="text-dark-leaf hover:text-green-600">
                        <svg class="w-5 h-5 sm:w-6 sm: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-8 w-8 sm:h-10 sm:w-10" onerror="this.style.display='none'">
                    <div>
                        <h1 class="text-base sm:text-xl font-bold text-gray-800">Ajukan Peminjaman</h1>
                        <p class="text-xs sm:text-sm text-medium-gray hidden sm:block">Pinjam tools yang Anda butuhkan</p>
                    </div>
                </div>
                <div class="flex items-center space-x-2 sm:space-x-4">
                    <span class="text-xs sm:text-sm text-gray-600 hidden md:inline"><?php echo $_SESSION['user_name']; ?></span>
                    <a href="../logout.php" class="bg-red-500 hover:bg-red-600 text-white px-3 py-1.5 sm:px-4 sm:py-2 rounded-lg text-xs sm:text-sm transition duration-200">
                        Logout
                    </a>
                </div>
            </div>
        </div>
    </header>

    <div class="max-w-6xl mx-auto px-3 sm:px-6 lg:px-8 py-4 sm:py-8">
        <!-- Message -->
        <?php if ($message): ?>
        <div class="mb-4 sm:mb-6 p-3 sm:p-4 rounded-lg text-sm sm:text-base <?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'; ?>">
            <?php echo $message; ?>
        </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-8">
            <!-- Left Column: Scanner & Manual Input -->
            <div class="space-y-4 sm:space-y-6">
                <!-- Scanner Section -->
                <div class="bg-white rounded-xl shadow-lg p-4 sm:p-6">
                    <h3 class="text-base sm:text-lg font-semibold text-gray-800 mb-3 sm:mb-4 flex items-center">
                        <svg class="w-5 h-5 mr-2 text-dark-leaf" 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 16h4"></path>
                        </svg>
                        Scan Barcode/QR Code
                    </h3>
                    
                    <div class="mb-3 sm:mb-4 flex flex-wrap gap-2">
                        <button id="startScanBtn" onclick="startScanner()" 
                                class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 sm:px-6 sm:py-3 rounded-lg transition duration-200 text-sm sm:text-base flex-1 sm:flex-none shadow-md hover:shadow-lg">
                            <svg class="w-4 h-4 sm:w-5 sm:h-5 inline mr-1 sm: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 16h4"></path>
                            </svg>
                            Mulai Scan
                        </button>
                        <button id="stopScanBtn" onclick="stopScanner()" 
                                class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 sm:px-6 sm:py-3 rounded-lg transition duration-200 text-sm sm:text-base hidden flex-1 sm:flex-none shadow-md hover:shadow-lg">
                            <svg class="w-4 h-4 sm:w-5 sm:h-5 inline mr-1 sm:mr-2" 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>
                            Stop Scan
                        </button>
                    </div>
                    
                    <div id="scanner-container" class="hidden">
                        <div id="reader" class="w-full"></div>
                        <div class="scanner-loading">
                            <p class="text-sm text-gray-600 mt-2">📸 Arahkan kamera ke barcode/QR code</p>
                            <p class="text-xs text-gray-500 mt-1">💡 Pastikan pencahayaan cukup baik</p>
                        </div>
                    </div>
                    
                    <div id="scan-result" class="hidden mt-3 sm:mt-4 p-3 sm:p-4 bg-gradient-to-r from-green-50 to-blue-50 rounded-lg border border-green-200">
                        <h4 class="font-semibold text-gray-800 mb-2 text-sm sm:text-base flex items-center">
                            <svg class="w-5 h-5 mr-2 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                            Asset Ditemukan:
                        </h4>
                        <div id="scanned-asset-info" class="text-sm sm:text-base"></div>
                        <button id="addToCartBtn" onclick="addScannedAssetToCart()" 
                                class="mt-3 bg-dark-leaf hover:bg-green-600 text-white px-4 py-2 rounded-lg transition duration-200 w-full sm:w-auto text-sm sm:text-base shadow-md hover:shadow-lg">
                            <svg class="w-4 h-4 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>
                            Tambah ke Keranjang
                        </button>
                    </div>
                </div>

                <!-- Manual Input Section -->
                <div class="bg-white rounded-xl shadow-lg p-4 sm:p-6">
                    <h3 class="text-base sm:text-lg font-semibold text-gray-800 mb-3 sm:mb-4 flex items-center">
                        <svg class="w-5 h-5 mr-2 text-dark-leaf" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                        </svg>
                        Input Manual
                    </h3>
                    
                    <div class="space-y-3 sm:space-y-4">
                        <div>
                            <label for="manual_asset_number" class="block text-xs sm:text-sm font-medium text-gray-700 mb-2">
                                Nomor Asset
                            </label>
                            <div class="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-2">
                                <input type="text" id="manual_asset_number" 
                                       class="flex-1 px-3 py-2 sm:px-4 sm:py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf text-sm sm:text-base"
                                       placeholder="Contoh: T0000146333">
                                <button onclick="searchManualAsset()"
                                        class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 sm:px-6 sm:py-3 rounded-lg transition duration-200 text-sm sm:text-base whitespace-nowrap shadow-md hover:shadow-lg">
                                    <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                    </svg>
                                    Cari
                                </button>
                            </div>
                        </div>
                        
                        <div id="manual-result" class="hidden p-3 sm:p-4 bg-gradient-to-r from-green-50 to-blue-50 rounded-lg border border-green-200">
                            <div id="manual-asset-info" class="text-sm sm:text-base"></div>
                            <button onclick="addManualAssetToCart()" 
                                    class="mt-3 bg-dark-leaf hover:bg-green-600 text-white px-4 py-2 rounded-lg transition duration-200 w-full sm:w-auto text-sm sm:text-base shadow-md hover:shadow-lg">
                                <svg class="w-4 h-4 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>
                                Tambah ke Keranjang
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Right Column: Cart & Form -->
            <div class="space-y-4 sm:space-y-6">
                <!-- Cart Section -->
                <div class="bg-white rounded-xl shadow-lg p-4 sm:p-6">
                    <div class="flex justify-between items-center mb-3 sm:mb-4">
                        <h3 class="text-base sm:text-lg font-semibold text-gray-800 flex items-center">
                            <svg class="w-5 h-5 mr-2 text-dark-leaf" 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 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"></path>
                            </svg>
                            Keranjang Peminjaman
                        </h3>
                        <button onclick="loadCart()" class="text-xs sm:text-sm text-blue-600 hover:text-blue-800 flex items-center">
                            <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                            </svg>
                            Refresh
                        </button>
                    </div>
                    
                    <div id="cart-items" class="space-y-2 sm:space-y-3 mb-3 sm:mb-4 max-h-64 sm:max-h-96 overflow-y-auto">
                        <!-- Cart items will be loaded here -->
                        <div class="text-center py-8">
                            <svg class="w-16 h-16 mx-auto text-gray-300 mb-2" 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 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"></path>
                            </svg>
                            <p class="text-gray-500 text-sm">Memuat keranjang...</p>
                        </div>
                    </div>
                </div>

                <!-- Form Section -->
                <div class="bg-white rounded-xl shadow-lg p-4 sm:p-6">
                    <h3 class="text-base sm:text-lg font-semibold text-gray-800 mb-3 sm:mb-4 flex items-center">
                        <svg class="w-5 h-5 mr-2 text-dark-leaf" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                        </svg>
                        Detail Peminjaman
                    </h3>
                    
                    <form method="POST" class="space-y-3 sm:space-y-4">
                        <div>
                            <label for="preference_pro" class="block text-xs sm:text-sm font-medium text-gray-700 mb-2">
                                Preference Pro <span class="text-red-500">*</span>
                            </label>
                            <input type="text" id="preference_pro" name="preference_pro" required
                                   class="w-full px-3 py-2 sm:px-4 sm:py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf text-sm sm:text-base"
                                   placeholder="Masukkan preference pro">
                        </div>

                        <div>
                            <label for="mesin" class="block text-xs sm:text-sm font-medium text-gray-700 mb-2">
                                Mesin <span class="text-red-500">*</span>
                            </label>
                            <input type="text" id="mesin" name="mesin" required
                                   class="w-full px-3 py-2 sm:px-4 sm:py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf text-sm sm:text-base"
                                   placeholder="Masukkan nama mesin">
                        </div>

                        <div>
                            <label for="notes" class="block text-xs sm:text-sm font-medium text-gray-700 mb-2">
                                Catatan (Opsional)
                            </label>
                            <textarea id="notes" name="notes" rows="3"
                                      class="w-full px-3 py-2 sm:px-4 sm:py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-dark-leaf focus:border-dark-leaf text-sm sm:text-base"
                                      placeholder="Tambahkan catatan jika diperlukan..."></textarea>
                        </div>

                        <div class="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-4 pt-2">
                            <button type="submit" name="submit_borrow"
                                    class="bg-dark-leaf hover:bg-green-600 text-white px-4 py-2 sm:px-6 sm:py-3 rounded-lg transition duration-200 font-semibold text-sm sm:text-base shadow-md hover:shadow-lg">
                                <svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                </svg>
                                Ajukan Peminjaman
                            </button>
                            <a href="dashboard.php"
                               class="bg-medium-gray hover:bg-gray-600 text-white px-4 py-2 sm:px-6 sm:py-3 rounded-lg transition duration-200 font-semibold text-center text-sm sm:text-base shadow-md hover:shadow-lg">
                                <svg class="w-4 h-4 inline mr-2" 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>
                                Batal
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        let html5QrcodeScanner = null;
        let currentScannedAsset = null;
        let currentManualAsset = null;

        // Load cart on page load
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Page loaded, loading cart...');
            loadCart();
        });

        function startScanner() {
            console.log('Starting scanner...');
            const scannerContainer = document.getElementById('scanner-container');
            const startBtn = document.getElementById('startScanBtn');
            const stopBtn = document.getElementById('stopScanBtn');
            
            scannerContainer.classList.remove('hidden');
            startBtn.classList.add('hidden');
            stopBtn.classList.remove('hidden');
            
            html5QrcodeScanner = new Html5Qrcode("reader");
            
            // Konfigurasi scanner yang disederhanakan tapi berkualitas
            const config = {
                fps: 10,
                qrbox: { width: 250, height: 250 },
                aspectRatio: 1.0
            };
            
            // Coba dengan kamera belakang (environment)
            html5QrcodeScanner.start(
                { facingMode: "environment" },
                config,
                (decodedText, decodedResult) => {
                    console.log('Scan successful:', decodedText);
                    // Stop scanner and process result
                    stopScanner();
                    processScannedCode(decodedText);
                    
                    // Berikan feedback sukses dengan vibration (jika didukung)
                    if (navigator.vibrate) {
                        navigator.vibrate(200);
                    }
                },
                (errorMessage) => {
                    // Handle scan error (dapat diabaikan untuk continuous scanning)
                }
            ).catch(err => {
                console.error("Error starting scanner:", err);
                alert("Error: " + err + "\n\nPastikan Anda memberikan izin akses kamera.");
                stopScanner();
            });
        }

        function stopScanner() {
            console.log('Stopping scanner...');
            const scannerContainer = document.getElementById('scanner-container');
            const startBtn = document.getElementById('startScanBtn');
            const stopBtn = document.getElementById('stopScanBtn');
            
            if (html5QrcodeScanner) {
                html5QrcodeScanner.stop().then(() => {
                    console.log('Scanner stopped successfully');
                    html5QrcodeScanner.clear();
                    html5QrcodeScanner = null;
                }).catch(err => {
                    console.error("Error stopping scanner:", err);
                    html5QrcodeScanner = null;
                });
            }
            
            scannerContainer.classList.add('hidden');
            startBtn.classList.remove('hidden');
            stopBtn.classList.add('hidden');
        }

        function processScannedCode(decodedText) {
            console.log('Processing scanned code:', decodedText);
            // Extract asset number from scanned code
            let assetNumber = decodedText.trim();
            
            // If the scanned code contains additional data, try to extract asset number
            if (assetNumber.includes('|')) {
                assetNumber = assetNumber.split('|')[0];
            }
            
            searchAsset(assetNumber, 'scan');
        }

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

        function searchAsset(assetNumber, type) {
            console.log('Searching asset:', assetNumber, 'Type:', type);
            const formData = new FormData();
            formData.append('ajax', '1');
            formData.append('action', 'scan_asset');
            formData.append('asset_number', assetNumber);
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('Search result:', data);
                if (data.success) {
                    displayAssetInfo(data.asset, type);
                } else {
                    alert(data.message);
                    if (type === 'scan') {
                        document.getElementById('scan-result').classList.add('hidden');
                    } else {
                        document.getElementById('manual-result').classList.add('hidden');
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Terjadi kesalahan saat mencari asset');
            });
        }

        function displayAssetInfo(asset, type) {
            console.log('Displaying asset info:', asset);
            const isAvailable = asset.is_available == 1;
            const availabilityText = isAvailable ? 
                '<span class="text-green-600 font-medium">✓ Tersedia</span>' : 
                '<span class="text-red-600 font-medium">✗ Tidak Tersedia</span>';
            
            const kondisiColor = asset.kondisi === 'baik' ? 'text-green-600' : 
                                asset.kondisi === 'rusak' ? 'text-yellow-600' : 'text-red-600';
            
            const assetInfo = `
                <div class="space-y-2">
                    <div class="flex justify-between items-start">
                        <strong class="text-gray-700">Nama:</strong>
                        <span class="text-right ml-2">${asset.asset_name}</span>
                    </div>
                    <div class="flex justify-between items-start">
                        <strong class="text-gray-700">Nomor Asset:</strong>
                        <span class="text-right ml-2 font-mono">${asset.asset_number}</span>
                    </div>
                    <div class="flex justify-between items-start">
                        <strong class="text-gray-700">Kategori:</strong>
                        <span class="text-right ml-2">${asset.asset_category}</span>
                    </div>
                    <div class="flex justify-between items-start">
                        <strong class="text-gray-700">Kondisi:</strong>
                        <span class="text-right ml-2 ${kondisiColor} font-medium">${asset.kondisi.toUpperCase()}</span>
                    </div>
                    <div class="flex justify-between items-start">
                        <strong class="text-gray-700">Status:</strong>
                        <span class="text-right ml-2">${availabilityText}</span>
                    </div>
                    ${asset.description ? `<div class="flex justify-between items-start"><strong class="text-gray-700">Deskripsi:</strong><span class="text-right ml-2">${asset.description}</span></div>` : ''}
                </div>
            `;
            
            if (type === 'scan') {
                currentScannedAsset = asset;
                document.getElementById('scanned-asset-info').innerHTML = assetInfo;
                document.getElementById('scan-result').classList.remove('hidden');
                document.getElementById('addToCartBtn').style.display = isAvailable ? 'block' : 'none';
            } else {
                currentManualAsset = asset;
                document.getElementById('manual-asset-info').innerHTML = assetInfo;
                document.getElementById('manual-result').classList.remove('hidden');
                const addBtn = document.querySelector('#manual-result button');
                addBtn.style.display = isAvailable ? 'block' : 'none';
            }
        }

        function addScannedAssetToCart() {
            if (currentScannedAsset) {
                addToCart(currentScannedAsset.id);
            }
        }

        function addManualAssetToCart() {
            if (currentManualAsset) {
                addToCart(currentManualAsset.id);
            }
        }

        function addToCart(assetId) {
            console.log('Adding to cart:', assetId);
            const formData = new FormData();
            formData.append('ajax', '1');
            formData.append('action', 'add_to_cart');
            formData.append('asset_id', assetId);
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('Add to cart result:', data);
                if (data.success) {
                    // Show success message
                    showNotification(data.message, 'success');
                    loadCart();
                    // Clear forms
                    document.getElementById('scan-result').classList.add('hidden');
                    document.getElementById('manual-result').classList.add('hidden');
                    document.getElementById('manual_asset_number').value = '';
                    currentScannedAsset = null;
                    currentManualAsset = null;
                } else {
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('Terjadi kesalahan saat menambahkan ke keranjang', 'error');
            });
        }

        function removeFromCart(cartId) {
            if (!confirm('Hapus asset dari keranjang?')) return;
            
            console.log('Removing from cart:', cartId);
            const formData = new FormData();
            formData.append('ajax', '1');
            formData.append('action', 'remove_from_cart');
            formData.append('cart_id', cartId);
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('Remove from cart result:', data);
                if (data.success) {
                    loadCart();
                    showNotification('Asset dihapus dari keranjang', 'success');
                } else {
                    showNotification('Gagal menghapus dari keranjang', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('Terjadi kesalahan', 'error');
            });
        }

        function loadCart() {
            console.log('Loading cart...');
            const formData = new FormData();
            formData.append('ajax', '1');
            formData.append('action', 'get_cart');
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('Cart data:', data);
                const cartContainer = document.getElementById('cart-items');
                
                if (data.success && data.items && data.items.length > 0) {
                    cartContainer.innerHTML = data.items.map(item => `
                        <div class="flex items-start sm:items-center justify-between p-3 bg-gradient-to-r from-gray-50 to-blue-50 rounded-lg gap-2 border border-gray-200 hover:shadow-md transition duration-200">
                            <div class="flex-1 min-w-0">
                                <div class="font-medium text-gray-800 text-sm sm:text-base truncate">${item.asset_name}</div>
                                <div class="text-xs sm:text-sm text-gray-600 truncate">${item.asset_number} • ${item.asset_category}</div>
                                <div class="text-xs text-gray-500 mt-1">
                                    <span class="inline-flex items-center">
                                        <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                            <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"></path>
                                        </svg>
                                        Kondisi: ${item.kondisi}
                                    </span>
                                </div>
                            </div>
                            <button onclick="removeFromCart(${item.cart_id})" 
                                    class="text-red-600 hover:text-red-800 hover:bg-red-50 p-2 rounded-lg flex-shrink-0 transition duration-200" 
                                    title="Hapus dari keranjang">
                                <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="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>
                        </div>
                    `).join('');
                } else {
                    cartContainer.innerHTML = `
                        <div class="text-center py-8">
                            <svg class="w-16 h-16 mx-auto text-gray-300 mb-2" 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 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"></path>
                            </svg>
                            <p class="text-gray-500 text-sm">Keranjang kosong</p>
                            <p class="text-gray-400 text-xs mt-1">Scan atau cari asset untuk memulai</p>
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error loading cart:', error);
                const cartContainer = document.getElementById('cart-items');
                cartContainer.innerHTML = `
                    <div class="text-center py-8">
                        <svg class="w-16 h-16 mx-auto text-red-300 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                        <p class="text-red-500 text-sm">Error loading cart</p>
                        <button onclick="loadCart()" class="mt-2 text-xs text-blue-600 hover:text-blue-800 underline">Coba lagi</button>
                    </div>
                `;
            });
        }

        // Show notification
        function showNotification(message, type) {
            const notification = document.createElement('div');
            notification.className = `fixed top-20 right-4 z-50 p-4 rounded-lg shadow-lg max-w-sm ${
                type === 'success' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'
            } transform transition-all duration-300 ease-in-out`;
            notification.innerHTML = `
                <div class="flex items-center">
                    <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                        ${type === 'success' ? 
                            '<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"></path>' :
                            '<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"></path>'
                        }
                    </svg>
                    <span>${message}</span>
                </div>
            `;
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.style.opacity = '0';
                setTimeout(() => notification.remove(), 300);
            }, 3000);
        }

        // Form validation
        document.querySelector('form').addEventListener('submit', function(e) {
            const preference_pro = document.getElementById('preference_pro').value.trim();
            const mesin = document.getElementById('mesin').value.trim();
            
            if (!preference_pro) {
                e.preventDefault();
                showNotification('Preference Pro harus diisi!', 'error');
                return false;
            }
            
            if (!mesin) {
                e.preventDefault();
                showNotification('Mesin harus diisi!', 'error');
                return false;
            }
        });

        // Enter key handler for manual search
        document.getElementById('manual_asset_number').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                searchManualAsset();
            }
        });
    </script>
</body>
</html>