<?= $this->extend('layout/main') ?>

<?= $this->section('content') ?>
<div class="space-y-8">
    
    <!-- Header -->
    <div>
        <h2 class="text-2xl font-bold text-on-surface">Validasi Gerbang Satpam (QR Scanner)</h2>
        <p class="text-sm text-secondary">Scan QR Code surat izin digital santri atau masukkan kode token secara manual.</p>
    </div>

    <!-- Core Grid -->
    <div class="max-w-xl mx-auto space-y-6">
        
        <!-- Column 1: QR Camera Scanner & Fallback input -->
        <div class="space-y-6">
            
            <!-- QR Camera Card -->
            <div class="bg-surface p-6 rounded-xl border border-outline shadow-sm overflow-hidden">
                <div class="flex items-center space-x-2 pb-4 mb-4 border-b border-outline">
                    <span class="material-symbols-outlined text-primary text-2xl">qr_code_scanner</span>
                    <h3 class="text-lg font-bold text-on-surface">Scan QR Code Kamera</h3>
                </div>

                <!-- Camera Container -->
                <div class="bg-slate-900 aspect-square w-full rounded-lg overflow-hidden border border-slate-800 flex flex-col items-center justify-center relative">
                    <div id="reader" class="w-full h-full"></div>
                    <div id="scanner-placeholder" class="absolute inset-0 flex flex-col items-center justify-center text-outline p-4 text-center space-y-2">
                        <span class="material-symbols-outlined text-5xl animate-pulse">videocam_off</span>
                        <span class="text-xs font-semibold">Kamera Belum Aktif</span>
                        <button onclick="startScanner()" class="mt-2 px-3 py-1.5 bg-primary hover:bg-primary-hover text-on-surface text-xs font-bold rounded-lg transition">
                            Aktifkan Kamera
                        </button>
                    </div>
                </div>

                <!-- Action Button inside scanner card -->
                <div class="mt-4 flex justify-between items-center text-xs text-secondary font-medium">
                    <span>Status: <strong id="scanner-status" class="text-red-500 uppercase">Non-Aktif</strong></span>
                    <button onclick="stopScanner()" id="btn-stop-scanner" class="hidden text-red-600 hover:text-red-800 font-bold">
                        Matikan Kamera
                    </button>
                </div>
            </div>

            <!-- Manual Token Form -->
            <div class="bg-surface p-6 rounded-xl border border-outline shadow-sm">
                <div class="flex items-center space-x-2 pb-4 mb-4 border-b border-outline">
                    <span class="material-symbols-outlined text-primary text-2xl">keyboard</span>
                    <h3 class="text-lg font-bold text-on-surface">Input Kode Manual</h3>
                </div>

                <form id="scan-form" action="/satpam/scan" method="post" class="space-y-4">
                    <?= csrf_field() ?>
                    <div>
                        <label for="token_izin" class="block text-xs font-bold text-secondary uppercase mb-1">Kode Token Izin</label>
                        <input type="text" name="token_izin" id="token_izin" required placeholder="Contoh: IZN-A1B2C3D4"
                               class="block w-full rounded-lg border-outline-variant shadow-sm focus:border-primary focus:ring-primary text-sm font-mono placeholder-slate-400 uppercase"/>
                    </div>
                    <button type="submit" class="w-full flex justify-center py-2.5 px-4 border border-transparent rounded-lg shadow-sm text-sm font-semibold text-on-surface bg-primary hover:bg-primary-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition duration-150">
                        Validasi & Proses
                    </button>
                </form>
            </div>

        </div>

        </div>

        <div class="flex gap-4 mt-8">
            <a href="/satpam/log" class="flex-1 glass-card rounded-xl p-4 flex flex-col items-center justify-center text-center hover:bg-surface-container-low transition cursor-pointer">
                <span class="material-symbols-outlined text-primary text-3xl mb-2">list_alt</span>
                <span class="text-sm font-bold text-on-surface-variant">Lihat Semua Log Aktivitas Gerbang</span>
            </a>
        </div>
    </div>
</div>

<!-- html5-qrcode library script CDN -->
<script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
<script>
    let html5QrcodeScanner = null;

    function startScanner() {
        document.getElementById('scanner-placeholder').classList.add('hidden');
        document.getElementById('btn-stop-scanner').classList.remove('hidden');
        document.getElementById('scanner-status').innerText = 'Mencari Kamera...';
        document.getElementById('scanner-status').className = 'text-amber-500 uppercase font-bold';

        html5QrcodeScanner = new Html5Qrcode("reader");
        const qrCodeSuccessCallback = (decodedText, decodedResult) => {
            // Stop scanning on success
            stopScanner();
            
            // Populate form and submit
            document.getElementById('token_izin').value = decodedText;
            document.getElementById('scan-form').submit();
        };
        
        const config = { fps: 10, qrbox: { width: 250, height: 250 } };

        // Start scanning with environment camera (rear camera)
        html5QrcodeScanner.start({ facingMode: "environment" }, config, qrCodeSuccessCallback)
            .then(() => {
                document.getElementById('scanner-status').innerText = 'Aktif (Scanning)';
                document.getElementById('scanner-status').className = 'text-emerald-500 uppercase font-bold';
            })
            .catch((err) => {
                console.error("Camera access failed", err);
                document.getElementById('scanner-status').innerText = 'Gagal Akses Kamera';
                document.getElementById('scanner-status').className = 'text-red-500 uppercase font-bold';
                stopScanner();
            });
    }

    function stopScanner() {
        if (html5QrcodeScanner) {
            html5QrcodeScanner.stop().then(() => {
                html5QrcodeScanner = null;
                resetScannerUI();
            }).catch(err => {
                console.error("Failed to stop scanner", err);
                resetScannerUI();
            });
        } else {
            resetScannerUI();
        }
    }

    function resetScannerUI() {
        document.getElementById('scanner-placeholder').classList.remove('hidden');
        document.getElementById('btn-stop-scanner').classList.add('hidden');
        document.getElementById('scanner-status').innerText = 'Non-Aktif';
        document.getElementById('scanner-status').className = 'text-red-500 uppercase font-bold';
        document.getElementById('reader').innerHTML = '';
    }
</script>
<?= $this->endSection() ?>
