<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scan QR Absen - SMKN 1 Prajekan</title>
    <link rel="icon" type="image/png" href="{{ asset('img/Capture__1_-removebg-preview.png') }}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <!-- html5-qrcode library for camera scanning -->
    <script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f8fafc;
            min-height: 100vh;
        }

        .scan-header {
            background-color: #0f172a;
            color: #ffffff;
            padding: 20px;
            text-align: center;
        }

        .scan-header img {
            width: 60px;
            margin-bottom: 10px;
        }

        .scan-container {
            max-width: 500px;
            margin: 30px auto;
            padding: 0 15px;
        }

        .scan-card {
            background-color: #ffffff;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
        }

        #reader {
            width: 100%;
            border-radius: 8px;
            overflow: hidden;
            border: 2px dashed #cbd5e1;
        }

        #reader video {
            border-radius: 8px;
        }

        .btn-scan-flat {
            background-color: #0284c7;
            color: #ffffff;
            border: none;
            border-radius: 8px;
            padding: 14px 20px;
            font-weight: 600;
            width: 100%;
            font-size: 16px;
            transition: all 0.2s;
        }

        .btn-scan-flat:hover {
            background-color: #0369a1;
            color: #ffffff;
        }

        .btn-secondary-flat {
            background-color: #334155;
            color: #ffffff;
            border: none;
            border-radius: 8px;
            padding: 14px 20px;
            font-weight: 600;
            width: 100%;
            font-size: 16px;
            transition: all 0.2s;
        }

        .btn-secondary-flat:hover {
            background-color: #1e293b;
            color: #ffffff;
        }

        .form-select-flat {
            background-color: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 12px;
            font-size: 14px;
        }

        .form-select-flat:focus {
            border-color: #0284c7;
            box-shadow: 0 0 0 0.2rem rgba(2, 132, 199, 0.2);
        }

        .result-card {
            display: none;
            background-color: #ffffff;
            border: 2px solid #0284c7;
            border-radius: 12px;
            padding: 25px;
            text-align: center;
        }

        .result-card.success {
            border-color: #10b981;
        }

        .result-card.error {
            border-color: #dc3545;
        }

        .result-icon {
            font-size: 48px;
            margin-bottom: 15px;
        }

        .result-icon.success {
            color: #10b981;
        }

        .result-icon.error {
            color: #dc3545;
        }

        .status-badge {
            display: inline-block;
            background-color: #0284c7;
            color: #fff;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 500;
        }

        .camera-status {
            text-align: center;
            padding: 15px;
            color: #64748b;
            font-size: 14px;
        }

        /* ===== MOBILE RESPONSIVE ===== */
        @media (max-width: 576px) {
            .scan-header {
                padding: 16px 12px;
            }

            .scan-header img {
                width: 50px;
                margin-bottom: 8px;
            }

            .scan-header h5 {
                font-size: 16px;
            }

            .scan-container {
                margin: 16px auto;
                padding: 0 12px;
            }

            .scan-card {
                padding: 16px 14px;
                margin-bottom: 14px;
                border-radius: 10px;
            }

            .scan-card h6 {
                font-size: 13px;
            }

            .btn-scan-flat,
            .btn-secondary-flat {
                padding: 12px 16px;
                font-size: 14px;
            }

            .result-card {
                padding: 18px 14px;
            }

            .result-icon {
                font-size: 40px;
                margin-bottom: 10px;
            }

            .d-flex.gap-2 {
                flex-direction: column;
            }

            .d-flex.gap-2 .btn {
                width: 100%;
            }
        }

        @media (max-width: 380px) {
            .scan-header h5 {
                font-size: 15px;
            }

            .scan-card {
                padding: 14px 12px;
            }
        }
    </style>
</head>
<body>

    <!-- Header -->
    <div class="scan-header">
        <img src="{{ asset('img/Capture__1_-removebg-preview.png') }}" class="img-fluid bg-white rounded-circle" style="padding:4px" alt="Logo">
        <h5 class="mb-0 fw-bold">SMKN 1 PRAJEKAN</h5>
        <small class="text-light opacity-75">Scan QR Code Absensi Kehadiran</small>
    </div>

    <div class="scan-container">

        <!-- Camera Scanner Card -->
        <div class="scan-card border-primary border-opacity-25 border-top-0 border-end-0 border-bottom-0" style="border-left-width: 4px;">
            <h6 class="fw-bold mb-3 text-primary"><i class="bi bi-person-check-fill me-2"></i>Arahkan Kamera ke QR Code</h6>
            <div id="reader"></div>
            <div class="camera-status" id="cameraStatus">
                <i class="bi bi-camera"></i> Memulai kamera...
            </div>
        </div>

        <!-- Keterangan Selection -->
        <div class="scan-card">
            <label class="form-label fw-bold" style="font-size: 14px;">Keterangan Absensi:</label>
            <select class="form-select form-select-flat" id="keterangan">
                <option value="Hadir" selected>Hadir</option>
                <option value="Sakit">Sakit</option>
                <option value="Izin">Izin</option>
                <option value="Alpha">Alpha</option>
                <option value="Terlambat">Terlambat</option>
            </select>
        </div>

        <!-- Result Card (Initially Hidden) -->
        <div class="result-card" id="resultCard">
            <div class="result-icon" id="resultIcon"></div>
            <h5 class="fw-bold" id="resultTitle"></h5>
            <p class="text-muted" id="resultMessage"></p>
            <div id="resultData"></div>
            <button class="btn btn-scan-flat mt-3" onclick="resetScan()">
                <i class="bi bi-qr-code-scan me-2"></i>Scan Lagi
            </button>
        </div>

        <!-- Navigation -->
        <div class="d-flex gap-2 mt-3">
            <a href="{{ route('scan.generate_qr') }}" class="btn btn-secondary-flat flex-fill text-center text-decoration-none">
                <i class="bi bi-qr-code me-2"></i>Generate QR
            </a>
            <a href="{{ url('/') }}" class="btn btn-scan-flat flex-fill text-center text-decoration-none">
                <i class="bi bi-house me-2"></i>Beranda
            </a>
        </div>
    </div>

    <script>
        let html5QrcodeScanner;
        let isProcessing = false;

        function onScanSuccess(decodedText, decodedResult) {
            if (isProcessing) return;
            isProcessing = true;

            console.log("QR Code detected:", decodedText);
            
            const keterangan = document.getElementById('keterangan').value;
            
            // Stop scanner
            html5QrcodeScanner.clear();

            // Show loading
            document.getElementById('cameraStatus').innerHTML = '<i class="bi bi-hourglass-split"></i> Memproses absensi...';

            // Send data to server
            fetch("{{ route('scan.proses') }}", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    id_siswa: decodedText,
                    keterangan: keterangan
                })
            })
            .then(response => response.json())
            .then(data => {
                const resultCard = document.getElementById('resultCard');
                const resultIcon = document.getElementById('resultIcon');
                const resultTitle = document.getElementById('resultTitle');
                const resultMessage = document.getElementById('resultMessage');
                const resultData = document.getElementById('resultData');
                
                resultCard.style.display = 'block';
                
                if (data.success) {
                    resultCard.className = 'result-card success';
                    resultIcon.className = 'result-icon success';
                    resultIcon.innerHTML = '<i class="bi bi-check-circle-fill"></i>';
                    resultTitle.textContent = 'Absen Berhasil!';
                    resultMessage.textContent = 'Data absensi sudah tersimpan dan notifikasi terkirim.';
                    resultData.innerHTML = `
                        <div class="text-start mt-3" style="background: #f8f9fa; padding: 15px; border-radius: 8px;">
                            <p class="mb-1"><strong>Nama:</strong> ${data.data.nama}</p>
                            <p class="mb-1"><strong>Kelas:</strong> ${data.data.kelas}</p>
                            <p class="mb-1"><strong>Keterangan:</strong> <span class="status-badge">${data.data.keterangan}</span></p>
                            <p class="mb-0"><strong>Tanggal:</strong> ${data.data.tanggal}</p>
                        </div>
                    `;
                } else {
                    resultCard.className = 'result-card error';
                    resultIcon.className = 'result-icon error';
                    resultIcon.innerHTML = '<i class="bi bi-x-circle-fill"></i>';
                    resultTitle.textContent = 'Absen Gagal';
                    resultMessage.textContent = data.message || 'Terjadi kesalahan.';
                    resultData.innerHTML = '';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                const resultCard = document.getElementById('resultCard');
                resultCard.style.display = 'block';
                resultCard.className = 'result-card error';
                document.getElementById('resultIcon').innerHTML = '<i class="bi bi-x-circle-fill"></i>';
                document.getElementById('resultIcon').className = 'result-icon error';
                document.getElementById('resultTitle').textContent = 'Error';
                document.getElementById('resultMessage').textContent = 'Gagal mengirim data. Periksa koneksi jaringan.';
                document.getElementById('resultData').innerHTML = '';
            });
        }

        function resetScan() {
            isProcessing = false;
            document.getElementById('resultCard').style.display = 'none';
            document.getElementById('cameraStatus').innerHTML = '<i class="bi bi-camera"></i> Memulai kamera...';
            startScanner();
        }

        function startScanner() {
            const isMobile = window.innerWidth < 500;
            const qrSize = isMobile ? 200 : 250;

            html5QrcodeScanner = new Html5QrcodeScanner(
                "reader", 
                { 
                    fps: 10, 
                    qrbox: { width: qrSize, height: qrSize },
                    rememberLastUsedCamera: true,
                    aspectRatio: 1.0
                }
            );
            html5QrcodeScanner.render(onScanSuccess, (errorMessage) => {
                // Ignore scan errors (no QR detected yet)
            });
            document.getElementById('cameraStatus').innerHTML = '<i class="bi bi-camera-video-fill text-primary"></i> Kamera aktif - Arahkan ke QR Code';
        }

        // Start scanner on page load
        startScanner();
    </script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
