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

<?= $this->section('content') ?>
<script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<audio id="beep-sound" src="<?= base_url('assets/beep.mp3') ?>" preload="auto"></audio>

<style>
    .scan-container {
        position: relative;
        overflow: hidden;
        border-radius: 20px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        background: #000;
    }

    #reader {
        width: 100%;
        border-radius: 20px;
    }

    #reader video {
        object-fit: cover;
        border-radius: 20px;
    }

    .scan-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        pointer-events: none;
        background: 
            linear-gradient(to right, #435ebe 4px, transparent 4px) 0 0,
            linear-gradient(to right, #435ebe 4px, transparent 4px) 0 100%,
            linear-gradient(to left, #435ebe 4px, transparent 4px) 100% 0,
            linear-gradient(to left, #435ebe 4px, transparent 4px) 100% 100%,
            linear-gradient(to bottom, #435ebe 4px, transparent 4px) 0 0,
            linear-gradient(to bottom, #435ebe 4px, transparent 4px) 100% 0,
            linear-gradient(to top, #435ebe 4px, transparent 4px) 0 100%,
            linear-gradient(to top, #435ebe 4px, transparent 4px) 100% 100%;
        background-repeat: no-repeat;
        background-size: 40px 40px;
        z-index: 10;
        border: 2px solid rgba(67, 94, 190, 0.3);
        border-radius: 20px;
    }

    .laser {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 2px;
        background: #435ebe;
        box-shadow: 0 0 10px #435ebe, 0 0 20px #435ebe;
        animation: scan 2s infinite;
        z-index: 11;
        opacity: 0.6;
    }

    @keyframes scan {
        0% { top: 0%; opacity: 0; }
        10% { opacity: 1; }
        90% { opacity: 1; }
        100% { top: 100%; opacity: 0; }
    }

    .status-card {
        background: rgba(255, 255, 255, 0.9);
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        border-radius: 15px;
        border: 1px solid rgba(255, 255, 255, 0.5);
        transition: all 0.3s;
    }

    .gps-indicator {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        background-color: #dc3545;
        display: inline-block;
        margin-right: 8px;
        box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.7);
        animation: pulse-red 2s infinite;
    }

    .gps-indicator.active {
        background-color: #198754;
        box-shadow: 0 0 10px rgba(25, 135, 84, 0.5);
        animation: none;
    }

    @keyframes pulse-red {
        0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.7); }
        70% { transform: scale(1); box-shadow: 0 0 0 10px rgba(220, 53, 69, 0); }
        100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(220, 53, 69, 0); }
    }

    .info-badge {
        font-size: 0.75rem;
        padding: 5px 12px;
        border-radius: 30px;
        background: #e9ecef;
        color: #495057;
        font-weight: 600;
        display: inline-flex;
        align-items: center;
        gap: 5px;
    }
</style>

<div class="page-heading">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="mb-1 text-primary fw-bold">Scan Kehadiran</h3>
            <p class="text-subtitle text-muted">Arahkan kamera ke QR Code untuk melakukan absensi.</p>
        </div>
        <div class="d-none d-md-block">
            <div class="info-badge">
                <i class="bi bi-clock"></i> <?= date('d M Y') ?>
            </div>
        </div>
    </div>
</div>

<div class="page-content">
    <div class="row justify-content-center">
        <div class="col-12 col-md-8 col-lg-6">
            
            <div class="card mb-3 border-0 shadow-sm" style="border-radius: 15px;">
                <div class="card-body p-3">
                    <label class="fw-bold mb-2 text-primary">Pilih Jenis Absensi:</label>
                    <select id="jenis_absen" class="form-select form-select-lg fw-bold" style="border-radius: 10px; border: 2px solid #435ebe;">
                        <option value="sekolah" selected>🏫 Absen Sekolah (Masuk/Pulang)</option>
                        
                        <?php if(!empty($list_sholat)): ?>
                            <optgroup label="Jadwal Sholat">
                                <?php foreach($list_sholat as $s): ?>
                                    <option value="sholat_<?= $s['id'] ?>">🕌 <?= $s['nama_sholat'] ?> (<?= substr($s['jam_mulai'],0,5) ?>-<?= substr($s['jam_akhir'],0,5) ?>)</option>
                                <?php endforeach; ?>
                            </optgroup>
                        <?php endif; ?>

                        <?php if(!empty($list_ekskul)): ?>
                            <optgroup label="Ekstrakurikuler Hari Ini">
                                <?php foreach($list_ekskul as $e): ?>
                                    <option value="ekskul_<?= $e['id'] ?>">⚽ <?= $e['nama_ekskul'] ?> (<?= substr($e['jam_mulai'],0,5) ?>-<?= substr($e['jam_akhir'],0,5) ?>)</option>
                                <?php endforeach; ?>
                            </optgroup>
                        <?php endif; ?>
                    </select>
                </div>
            </div>

            <div class="card status-card mb-4 shadow-sm">
                <div class="card-body py-3 px-4 d-flex justify-content-between align-items-center">
                    <div class="d-flex align-items-center">
                        <div id="gps-dot" class="gps-indicator"></div>
                        <div>
                            <h6 class="mb-0 fw-bold text-dark" id="gps-text">Mencari Lokasi...</h6>
                            <small class="text-muted" id="gps-coords">Menunggu sinyal GPS</small>
                        </div>
                    </div>
                    <i class="bi bi-geo-alt-fill fs-3 text-primary opacity-25"></i>
                </div>
            </div>

            <div class="scan-container">
                <div id="reader"></div>
                <div class="scan-overlay"></div>
                <div class="laser"></div>
            </div>

            <div class="text-center mt-4">
                <p class="text-muted small">Pastikan Anda berada di dalam radius sekolah.</p>
                <div id="scan-result" class="d-none alert alert-success mt-3"></div>
            </div>

        </div>
    </div>
</div>

<input type="hidden" id="latitude">
<input type="hidden" id="longitude">

<script>
    let currentLat = null;
    let currentLong = null;
    let isProcessing = false;

    function playBeep() {
        var audio = document.getElementById("beep-sound");
        if(audio) {
            audio.play().catch(error => console.log('Autoplay blocked:', error));
        }
    }

    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.watchPosition(showPosition, showError, {
                enableHighAccuracy: true,
                timeout: 5000,
                maximumAge: 0
            });
        } else {
            document.getElementById("gps-text").innerHTML = "GPS Tidak Didukung";
        }
    }

    function showPosition(position) {
        currentLat = position.coords.latitude;
        currentLong = position.coords.longitude;

        document.getElementById("latitude").value = currentLat;
        document.getElementById("longitude").value = currentLong;
        
        const gpsDot = document.getElementById("gps-dot");
        const gpsText = document.getElementById("gps-text");
        const gpsCoords = document.getElementById("gps-coords");

        gpsDot.classList.add('active');
        gpsText.innerHTML = "Lokasi Terkunci";
        gpsText.classList.add('text-success');
        gpsCoords.innerHTML = currentLat.toFixed(6) + ", " + currentLong.toFixed(6);
    }

    function showError(error) {
        const gpsText = document.getElementById("gps-text");
        const gpsDot = document.getElementById("gps-dot");
        
        gpsDot.classList.remove('active');
        
        switch(error.code) {
            case error.PERMISSION_DENIED:
                gpsText.innerHTML = "Akses GPS Ditolak";
                break;
            case error.POSITION_UNAVAILABLE:
                gpsText.innerHTML = "Info Lokasi Tidak Tersedia";
                break;
            case error.TIMEOUT:
                gpsText.innerHTML = "Waktu Habis (GPS)";
                break;
            case error.UNKNOWN_ERROR:
                gpsText.innerHTML = "Error GPS Tidak Diketahui";
                break;
        }
    }

    getLocation();

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

        let jenisAbsen = document.getElementById('jenis_absen').value;

        if (currentLat === null || currentLong === null) {
            Swal.fire({
                icon: 'warning',
                title: 'Menunggu GPS',
                text: 'Mohon tunggu sampai lokasi terkunci (titik hijau).',
                timer: 2000,
                showConfirmButton: false
            });
            return;
        }

        isProcessing = true;
        playBeep();

        let formData = new FormData();
        formData.append('qr_content', decodedText);
        formData.append('latitude', currentLat);
        formData.append('longitude', currentLong);
        formData.append('jenis_absen', jenisAbsen);
        formData.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');

        Swal.fire({
            title: 'Memproses...',
            html: 'Mohon tunggu sebentar',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        fetch('<?= base_url('absensi/process-scan') ?>', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 200) {
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil!',
                    html: `<b>${data.nama}</b><br>${data.message}<br>Jam: ${data.jam}`,
                    timer: 4000,
                    showConfirmButton: false,
                    timerProgressBar: true
                }).then(() => {
                    isProcessing = false;
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal',
                    text: data.messages ? JSON.stringify(data.messages) : (data.error || 'Terjadi kesalahan.'),
                    timer: 4000,
                    showConfirmButton: false,
                    timerProgressBar: true
                }).then(() => {
                    isProcessing = false;
                });
            }
        })
        .catch(error => {
            Swal.fire({
                icon: 'error',
                title: 'Error Server',
                text: 'Tidak dapat terhubung ke server. Coba lagi.',
                timer: 4000,
                showConfirmButton: false
            }).then(() => {
                isProcessing = false;
            });
        });
    }

    let html5QrcodeScanner = new Html5QrcodeScanner(
        "reader",
        { 
            fps: 10, 
            qrbox: {width: 250, height: 250},
            aspectRatio: 1.0
        },
        false
    );
    
    html5QrcodeScanner.render(onScanSuccess);
</script>

<?= $this->endSection() ?>