

<?php $__env->startSection('title', 'Pemindai Absensi'); ?>

<?php
    // Jadwal kegiatan siswa hari ini
    \Carbon\Carbon::setLocale('id');
    $hariIniIndo = \Carbon\Carbon::now('Asia/Jakarta')->isoFormat('dddd');
    $jadwalHariIniSiswa = match ($hariIniIndo) {
        'Senin'                                   => ['Upacara', 'Dzuhur'],
        'Selasa', 'Rabu', 'Kamis', 'Sabtu'        => ['Duha', 'Dzuhur'],
        'Jumat'                                    => ['Tadarus', 'Pulang'],
        default                                    => [],
    };
?>

<?php $__env->startSection(auth()->user()->role == 'admin' ? 'admin-content' : 'petugas-content'); ?>

<style>
    /* ── Layout ── */
    .scan-wrapper {
        min-height: calc(100vh - 150px);
        display: flex;
        justify-content: center;
        align-items: center;
        background: #f1f5f9;
        padding: 16px;
    }

    .scan-card {
        width: 100%;
        max-width: 400px;
        background: #0f172a;
        border-radius: 28px;
        padding: 22px;
        border: 1px solid #1e293b;
    }

    /* ── Header ── */
    .scan-header {
        text-align: center;
        margin-bottom: 18px;
    }

    .scan-header h5 {
        color: #f1f5f9;
        font-weight: 700;
        font-size: 16px;
        margin-bottom: 4px;
    }

    .scan-time {
        font-size: 11px;
        color: #64748b;
        font-weight: 500;
        margin-bottom: 8px;
    }

    .badge-live {
        display: inline-flex;
        align-items: center;
        gap: 5px;
        background: rgba(22, 163, 74, 0.15);
        color: #4ade80;
        font-size: 10px;
        font-weight: 700;
        padding: 4px 12px;
        border-radius: 50px;
        letter-spacing: .04em;
    }

    .live-dot {
        width: 6px;
        height: 6px;
        border-radius: 50%;
        background: #4ade80;
        animation: blink 1.5s ease-in-out infinite;
    }

    @keyframes blink {
        0%, 100% { opacity: 1; }
        50%       { opacity: 0.2; }
    }

    /* ── Scanner Viewport ── */
    .scan-viewport {
        position: relative;
        width: 100%;
        aspect-ratio: 1 / 1;
        border-radius: 18px;
        overflow: hidden;
        background: #000;
    }

    #reader {
        width: 100% !important;
        height: 100% !important;
        border: none !important;
        background: #000 !important;
    }

    #reader video {
        width: 100% !important;
        height: 100% !important;
        object-fit: cover !important;
        image-rendering: -webkit-optimize-contrast;
        image-rendering: crisp-edges;
    }

    #reader img,
    #reader canvas,
    #reader__scan_region > img {
        display: none !important;
    }

    /* ── Frame Overlay ── */
    .scan-frame {
        position: absolute;
        inset: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        pointer-events: none;
        z-index: 10;
    }

    .scan-mask {
        position: absolute;
        inset: 0;
        background: rgba(0, 0, 0, 0.55);
        clip-path: polygon(
            0% 0%, 100% 0%, 100% 100%, 0% 100%,
            0% 0%,
            15% 15%, 15% 85%, 85% 85%, 85% 15%, 15% 15%
        );
    }

    .corner-box {
        position: absolute;
        width: 70%;
        aspect-ratio: 1/1;
    }

    .corner-box::before,
    .corner-box::after,
    .corner-inner::before,
    .corner-inner::after {
        content: '';
        position: absolute;
        width: 22px;
        height: 22px;
        border-color: #6366f1;
        border-style: solid;
    }

    .corner-box::before  { top: 0;    left: 0;  border-width: 3px 0 0 3px; border-radius: 6px 0 0 0; }
    .corner-box::after   { top: 0;    right: 0; border-width: 3px 3px 0 0; border-radius: 0 6px 0 0; }
    .corner-inner::before{ bottom: 0; left: 0;  border-width: 0 0 3px 3px; border-radius: 0 0 0 6px; }
    .corner-inner::after { bottom: 0; right: 0; border-width: 0 3px 3px 0; border-radius: 0 0 6px 0; }

    .scan-line {
        position: absolute;
        width: 70%;
        height: 2px;
        background: #6366f1;
        opacity: 0.9;
        animation: sweep 2.2s ease-in-out infinite;
    }

    @keyframes sweep {
        0%   { top: 15%; }
        50%  { top: 83%; }
        100% { top: 15%; }
    }

    /* ── Hint ── */
    .scan-hint {
        text-align: center;
        color: #475569;
        font-size: 12px;
        margin-top: 12px;
    }

    /* ── Notifikasi Fullscreen Overlay ── */
    .notify-overlay {
        display: none;
        position: fixed;
        inset: 0;
        z-index: 9999;
        align-items: center;
        justify-content: center;
        background: rgba(0, 0, 0, 0.75);
        backdrop-filter: blur(4px);
        animation: fadeIn .2s ease;
    }

    .notify-overlay.show {
        display: flex;
    }

    @keyframes fadeIn {
        from { opacity: 0; }
        to   { opacity: 1; }
    }

    .notify-box {
        width: 90%;
        max-width: 340px;
        border-radius: 24px;
        padding: 28px 24px;
        text-align: center;
        animation: popIn .25s cubic-bezier(0.175, 0.885, 0.32, 1.275);
    }

    .notify-box.sukses {
        background: #0a1f13;
        border: 1px solid rgba(74, 222, 128, 0.3);
    }

    .notify-box.gagal {
        background: #1f0a0a;
        border: 1px solid rgba(239, 68, 68, 0.3);
    }

    @keyframes popIn {
        from { opacity: 0; transform: scale(0.85); }
        to   { opacity: 1; transform: scale(1); }
    }

    .notify-icon {
        width: 64px;
        height: 64px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28px;
        margin: 0 auto 14px;
    }

    .notify-box.sukses .notify-icon {
        background: rgba(74, 222, 128, 0.15);
        color: #4ade80;
    }

    .notify-box.gagal .notify-icon {
        background: rgba(239, 68, 68, 0.15);
        color: #f87171;
    }

    .notify-foto {
        width: 72px;
        height: 72px;
        border-radius: 16px;
        object-fit: cover;
        border: 3px solid #6366f1;
        margin: 0 auto 14px;
        display: block;
    }

    .notify-nama {
        color: #f1f5f9;
        font-size: 20px;
        font-weight: 800;
        margin-bottom: 4px;
    }

    .notify-sub {
        color: #64748b;
        font-size: 13px;
        margin-bottom: 14px;
    }

    .notify-status {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        font-size: 13px;
        font-weight: 700;
        padding: 7px 16px;
        border-radius: 50px;
    }

    .notify-box.sukses .notify-status {
        background: rgba(74, 222, 128, 0.15);
        color: #4ade80;
    }

    .notify-box.gagal .notify-status {
        background: rgba(239, 68, 68, 0.15);
        color: #f87171;
    }

    /* Progress bar jeda */
    .notify-progress {
        height: 3px;
        border-radius: 10px;
        background: #1e293b;
        margin-top: 18px;
        overflow: hidden;
    }

    .notify-progress-bar {
        height: 100%;
        border-radius: 10px;
        width: 100%;
        transition: width linear;
    }

    .notify-box.sukses .notify-progress-bar { background: #4ade80; }
    .notify-box.gagal  .notify-progress-bar { background: #f87171; }

    /* ── Tombol Ganti Kamera ── */
    .btn-switch {
        width: 100%;
        margin-top: 14px;
        padding: 11px;
        border-radius: 12px;
        border: 1px solid #334155;
        background: #1e293b;
        color: #94a3b8;
        font-size: 13px;
        font-weight: 600;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        cursor: pointer;
        transition: background .15s, color .15s;
        font-family: inherit;
    }

    .btn-switch:hover {
        background: #334155;
        color: #cbd5e1;
    }

    /* ── Responsive ── */
    @media (max-width: 480px) {
        .scan-wrapper { padding: 10px; align-items: flex-start; padding-top: 20px; }
        .scan-card    { border-radius: 22px; padding: 18px; }
    }
</style>

<div class="scan-wrapper">
    <div class="scan-card">

        
        <div class="scan-header">
            <h5>Pindai QR Absensi</h5>
            <div class="scan-time" id="jamRealtime"></div>
            <div class="badge-live">
                <div class="live-dot"></div>
                Kamera Aktif
            </div>
        </div>

        
        <div class="scan-viewport">
            <div id="reader"></div>
            <div class="scan-frame">
                <div class="scan-mask"></div>
                <div class="corner-box">
                    <div class="corner-inner"></div>
                </div>
                <div class="scan-line"></div>
            </div>
        </div>

        <p class="scan-hint">Arahkan QR ke dalam bingkai</p>

        
        <button class="btn-switch" id="switchCamera">
            <i class="bi bi-camera-video-off"></i>
            Ganti Kamera
        </button>

        
        <button class="btn-switch" id="btnBukaManual" style="margin-top:8px;" data-bs-toggle="modal" data-bs-target="#modalInputManual">
            <i class="bi bi-pencil-square"></i>
            Input Manual (Hadir / Sakit / Izin / Haid)
        </button>

    </div>
</div>


<div class="modal fade" id="modalInputManual" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content" style="border-radius:20px; background:#0f172a; color:#f1f5f9; border:1px solid #1e293b;">
            <div class="modal-header border-0 pb-0">
                <h6 class="modal-title fw-bold">Input Manual Kehadiran</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Tutup"></button>
            </div>
            <div class="modal-body">
                <p style="font-size:12px; color:#94a3b8; margin-bottom:16px;">
                    Dipakai kalau siswa/guru tidak bisa scan QR karena lupa bawa, atau berhalangan (Sakit/Izin/Haid).
                </p>

                <label class="form-label small" style="color:#cbd5e1;">Tipe</label>
                <div class="btn-group w-100 mb-3" role="group">
                    <input type="radio" class="btn-check" name="manualTipe" id="tipeManualSiswa" value="siswa" checked>
                    <label class="btn btn-outline-light" for="tipeManualSiswa">Siswa</label>

                    <input type="radio" class="btn-check" name="manualTipe" id="tipeManualGuru" value="guru">
                    <label class="btn btn-outline-light" for="tipeManualGuru">Guru</label>
                </div>

                <div id="manualKelasWrapper">
                    <label class="form-label small" style="color:#cbd5e1;">Kelas</label>
                    <select id="manualKelas" class="form-select mb-3" style="background:#1e293b; border:1px solid #334155; color:#f1f5f9;">
                        <option value="">Semua Kelas</option>
                        <?php $__currentLoopData = ['VII-A','VII-B','VII-C','VII-D','VIII-A','VIII-B','VIII-C','VIII-D','IX-A','IX-B','IX-C','IX-D']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $kls): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($kls); ?>"><?php echo e($kls); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                <label class="form-label small" style="color:#cbd5e1;">
                    Nama <span style="color:#64748b;">(cuma yang belum tercatat hari ini)</span>
                </label>
                <select id="manualNama" class="form-select mb-3" style="background:#1e293b; border:1px solid #334155; color:#f1f5f9;">
                    <option value="">— Memuat... —</option>
                </select>

                <label class="form-label small" style="color:#cbd5e1;">Jenis Keterangan</label>
                <select id="manualJenis" class="form-select mb-3" style="background:#1e293b; border:1px solid #334155; color:#f1f5f9;">
                    <option value="Hadir">Hadir (Lupa QR)</option>
                    <option value="Izin">Izin</option>
                    <option value="Sakit">Sakit</option>
                    <option value="Haid" id="opsiHaid">Haid (khusus siswi)</option>
                </select>

                <div id="manualKategoriWrapper" style="display:block;">
                    <label class="form-label small" style="color:#cbd5e1;">
                        Pilih Kegiatan <span style="color:#64748b;">(hari ini: <?php echo e($hariIniIndo); ?>)</span>
                    </label>
                    <select id="manualKategori" class="form-select mb-2" style="background:#1e293b; border:1px solid #334155; color:#f1f5f9;">
                        <!-- Diisi via JS -->
                    </select>
                    <p style="font-size:11px; color:#64748b; margin-bottom:12px;">
                        Kategori wajib dipilih jika statusnya Hadir atau Haid.
                    </p>
                </div>

                <div id="manualPesanError" class="alert alert-danger py-2" style="display:none; font-size:13px;"></div>
            </div>
            <div class="modal-footer border-0 pt-0">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                <button type="button" class="btn btn-primary" id="btnSubmitManual">
                    <span id="btnSubmitManualText">Simpan</span>
                    <span id="btnSubmitManualSpinner" class="spinner-border spinner-border-sm ms-1" style="display:none;"></span>
                </button>
            </div>
        </div>
    </div>
</div>


<div class="notify-overlay" id="notifyOverlay">
    <div class="notify-box" id="notifyBox">

        
        <div id="notifySuksesContent">
            <img id="notifyFoto" class="notify-foto" src="" alt="">
            <div class="notify-nama" id="notifyNama"></div>
            <div class="notify-sub"  id="notifyKelas"></div>
            <div class="notify-status">
                <i class="bi bi-check-circle-fill"></i>
                <span id="notifyStatusText">Absensi Berhasil</span>
            </div>
        </div>

        
        <div id="notifyGagalContent" style="display:none;">
            <div class="notify-icon">
                <i class="bi bi-x-circle-fill"></i>
            </div>
            <div class="notify-nama" style="color:#f87171;">Absensi Gagal</div>
            <div class="notify-sub" id="notifyGagalPesan"></div>
            <div class="notify-status">
                <i class="bi bi-exclamation-circle-fill"></i> Gagal
            </div>
        </div>

        
        <div class="notify-progress">
            <div class="notify-progress-bar" id="notifyProgressBar"></div>
        </div>

    </div>
</div>

<script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    /* ── Real-time Clock ── */
    function updateJam() {
        const now  = new Date();
        const opts = {
            weekday: 'short', day: '2-digit', month: 'short',
            year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit'
        };
        document.getElementById('jamRealtime').textContent =
            now.toLocaleDateString('id-ID', opts).toUpperCase().replace('.', '');
    }
    setInterval(updateJam, 1000);
    updateJam();

    /* ── Toast ringan (untuk pesan teknis) ── */
    const Toast = Swal.mixin({
        toast: true, position: 'top-end',
        showConfirmButton: false, timer: 2500, timerProgressBar: true,
    });

    /* ── State ── */
    let scanner       = null;
    let currentCamId  = null;
    let isProcessing  = false;
    let lastScanAt    = 0;
    let notifyTimer   = null;
    let lastSuccessAt = Date.now();
    let hintShown     = false;
    const hintEl      = document.querySelector('.scan-hint');
    const HINT_DEFAULT = hintEl.textContent;

    /* ── Konfigurasi Kamera ── */
    function buildConfig() {
        return {
            fps: 15,
            qrbox: (w, h) => ({
                width:  Math.round(Math.min(w, h) * 0.7),
                height: Math.round(Math.min(w, h) * 0.7),
            }),
            aspectRatio: 1.0,
            experimentalFeatures: {
                useBarCodeDetectorIfSupported: true,
            },
            formatsToSupport: [Html5QrcodeSupportedFormats.QR_CODE],
            videoConstraints: {
                facingMode: { ideal: 'environment' },
                width:  { ideal: 1920 },
                height: { ideal: 1920 },
                advanced: [
                    { focusMode: 'continuous' },
                    { exposureMode: 'continuous' },
                    { whiteBalanceMode: 'continuous' },
                ],
            },
            rememberLastUsedCamera: true,
            showTorchButtonIfSupported: true,
        };
    }

    /* ── Start Scanner ── */
    function startScanner(camId) {
        currentCamId = camId;
        lastSuccessAt = Date.now();
        scanner = new Html5Qrcode('reader', { verbose: false });
        scanner.start(camId, buildConfig(), onScanSuccess)
            .catch(() => Toast.fire({ icon: 'error', title: 'Akses kamera ditolak' }));
    }

    /* ── Scan Callback ── */
    function onScanSuccess(text) {
        const now = Date.now();
        if (isProcessing || now - lastScanAt < 3000) return;

        isProcessing = true;
        lastScanAt   = now;
        if (navigator.vibrate) navigator.vibrate(80);

        fetch("<?php echo e(route('absen.proses')); ?>", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
            },
            body: JSON.stringify({ qr_code: text }),
        })
        .then(res => res.json())
        .then(data => {
            if (data.status === 'success') {
                new Audio('https://assets.mixkit.co/active_storage/sfx/2019/2019-preview.mp3')
                    .play().catch(() => {});
                showNotifySukses(data);
            } else {
                showNotifyGagal(data.message || 'QR tidak dikenali');
            }
        })
        .catch(() => showNotifyGagal('Koneksi bermasalah, coba lagi'))
        .finally(() => {
            setTimeout(() => { isProcessing = false; }, 2000);
        });
    }

    /* ── Tampilkan Notifikasi Sukses ── */
    function showNotifySukses(data) {
        lastSuccessAt = Date.now();
        if (hintShown) { hintShown = false; hintEl.textContent = HINT_DEFAULT; }

        const overlay = document.getElementById('notifyOverlay');
        const box     = document.getElementById('notifyBox');
        const bar     = document.getElementById('notifyProgressBar');

        document.getElementById('notifySuksesContent').style.display = 'block';
        document.getElementById('notifyGagalContent').style.display  = 'none';
        box.className = 'notify-box sukses';

        document.getElementById('notifyNama').textContent  = data.nama;
        document.getElementById('notifyKelas').textContent = (data.kelas || '') + (data.kategori ? ' — ' + data.kategori : '');
        document.getElementById('notifyFoto').src =
            data.foto || `https://ui-avatars.com/api/?name=${encodeURIComponent(data.nama)}&background=4f46e5&color=fff&bold=true&size=80`;

        overlay.classList.add('show');
        animasiProgress(bar, 3000);

        clearTimeout(notifyTimer);
        notifyTimer = setTimeout(() => overlay.classList.remove('show'), 3000);
    }

    /* ── Tampilkan Notifikasi Gagal ── */
    function showNotifyGagal(pesan) {
        const overlay = document.getElementById('notifyOverlay');
        const box     = document.getElementById('notifyBox');
        const bar     = document.getElementById('notifyProgressBar');

        document.getElementById('notifySuksesContent').style.display = 'none';
        document.getElementById('notifyGagalContent').style.display  = 'block';
        box.className = 'notify-box gagal';

        document.getElementById('notifyGagalPesan').textContent = pesan;

        overlay.classList.add('show');
        animasiProgress(bar, 2500);

        clearTimeout(notifyTimer);
        notifyTimer = setTimeout(() => overlay.classList.remove('show'), 2500);
    }

    /* ── Animasi Progress Bar ── */
    function animasiProgress(bar, durasi) {
        bar.style.transition = 'none';
        bar.style.width      = '100%';
        setTimeout(() => {
            bar.style.transition = `width ${durasi}ms linear`;
            bar.style.width      = '0%';
        }, 30);
    }

    /* ── Klik overlay untuk tutup lebih awal ── */
    document.getElementById('notifyOverlay').addEventListener('click', () => {
        document.getElementById('notifyOverlay').classList.remove('show');
        clearTimeout(notifyTimer);
    });

    setInterval(() => {
        if (!isProcessing && Date.now() - lastSuccessAt > 6000 && !hintShown) {
            hintShown = true;
            hintEl.textContent = 'Belum terbaca? Nyalakan flash atau dekatkan HP ke QR';
        }
    }, 1000);

    /* ── Switch Camera ── */
    document.getElementById('switchCamera').addEventListener('click', () => {
        if (!scanner) {
            Toast.fire({ icon: 'info', title: 'Kamera belum siap, tunggu sebentar' });
            return;
        }
        Html5Qrcode.getCameras().then(cams => {
            if (cams.length <= 1) {
                Toast.fire({ icon: 'info', title: 'Hanya satu kamera tersedia' });
                return;
            }
            scanner.stop().then(() => {
                const next = cams.find(c => c.id !== currentCamId) || cams[0];
                startScanner(next.id);
            });
        });
    });

    /* ── Input Manual ── */
    const manualJenisEl     = document.getElementById('manualJenis');
    const manualNamaEl      = document.getElementById('manualNama');
    const manualKelasEl     = document.getElementById('manualKelas');
    const manualKelasWrapEl = document.getElementById('manualKelasWrapper');
    const manualKategoriEl  = document.getElementById('manualKategori');
    const manualWrapperEl   = document.getElementById('manualKategoriWrapper');
    const manualErrorEl     = document.getElementById('manualPesanError');
    const opsiHaidEl        = document.getElementById('opsiHaid');
    const btnSubmitManual   = document.getElementById('btnSubmitManual');
    const btnSubmitTextEl   = document.getElementById('btnSubmitManualText');
    const btnSubmitSpinEl   = document.getElementById('btnSubmitManualSpinner');
    const modalManualEl     = document.getElementById('modalInputManual');
    const radioTipeManual   = document.querySelectorAll('input[name="manualTipe"]');

    function tipeTerpilih() {
        return document.querySelector('input[name="manualTipe"]:checked')?.value || 'siswa';
    }

    function updateKategoriOptions() {
        const tipe = tipeTerpilih();
        manualKategoriEl.innerHTML = '';
        
        if (tipe === 'guru') {
            manualKategoriEl.innerHTML = '<option value="Masuk">Masuk</option><option value="Pulang">Pulang</option>';
        } else {
            const jadwalSiswa = <?php echo json_encode($jadwalHariIniSiswa, 15, 512) ?>;
            if (jadwalSiswa.length === 0) {
                manualKategoriEl.innerHTML = '<option value="" disabled>Tidak ada jadwal kegiatan hari ini</option>';
            } else {
                jadwalSiswa.forEach(kat => {
                    manualKategoriEl.innerHTML += `<option value="${kat}">${kat}</option>`;
                });
            }
        }
    }

    function muatDaftarBelumHadir() {
        const tipe  = tipeTerpilih();
        manualKelasWrapEl.style.display = tipe === 'siswa' ? 'block' : 'none';

        manualNamaEl.innerHTML = '<option value="">— Memuat... —</option>';
        manualNamaEl.disabled  = true;

        const params = new URLSearchParams({ tipe });
        if (tipe === 'siswa' && manualKelasEl.value) params.set('kelas', manualKelasEl.value);

        fetch("<?php echo e(route('absen.belumHadir')); ?>?" + params.toString())
            .then(res => res.json())
            .then(list => {
                manualNamaEl.disabled = false;
                if (!Array.isArray(list) || list.length === 0) {
                    manualNamaEl.innerHTML = '<option value="">Semua sudah tercatat hari ini 🎉</option>';
                    updateOpsiHaidVisibility();
                    return;
                }
                manualNamaEl.innerHTML = list.map(p =>
                    `<option value="${p.kode}" data-jk="${p.jenis_kelamin || ''}">${p.nama}${tipe === 'siswa' ? ' — ' + p.kelas : ''}</option>`
                ).join('');
                updateOpsiHaidVisibility();
            })
            .catch(() => {
                manualNamaEl.innerHTML = '<option value="">Gagal memuat daftar</option>';
            });
    }

    function updateOpsiHaidVisibility() {
        const tipe = tipeTerpilih();
        const opt  = manualNamaEl.options[manualNamaEl.selectedIndex];
        const jk   = opt?.dataset?.jk;
        const boleh = tipe === 'siswa' && jk === 'P';

        opsiHaidEl.hidden = !boleh;
        if (!boleh && manualJenisEl.value === 'Haid') {
            manualJenisEl.value = 'Hadir'; // Fallback ke default 'Hadir'
            manualWrapperEl.style.display = 'block';
        }
    }

    radioTipeManual.forEach(r => r.addEventListener('change', () => {
        muatDaftarBelumHadir();
        updateKategoriOptions();
    }));
    
    manualKelasEl.addEventListener('change', muatDaftarBelumHadir);
    manualNamaEl.addEventListener('change', updateOpsiHaidVisibility);

    manualJenisEl.addEventListener('change', () => {
        const butuhKategori = ['Haid', 'Hadir'].includes(manualJenisEl.value);
        manualWrapperEl.style.display = butuhKategori ? 'block' : 'none';
    });

    modalManualEl.addEventListener('show.bs.modal', () => {
        muatDaftarBelumHadir();
        updateKategoriOptions();
    });

    modalManualEl.addEventListener('hidden.bs.modal', resetManualForm);

    function resetManualForm() {
        document.getElementById('tipeManualSiswa').checked = true;
        manualKelasEl.value = '';
        manualJenisEl.value = 'Hadir'; // Default ke Hadir
        manualWrapperEl.style.display = 'block';
        manualErrorEl.style.display = 'none';
        manualErrorEl.textContent = '';
        setManualLoading(false);
        updateKategoriOptions();
    }

    function setManualLoading(loading) {
        btnSubmitManual.disabled = loading;
        btnSubmitTextEl.textContent = loading ? 'Menyimpan...' : 'Simpan';
        btnSubmitSpinEl.style.display = loading ? 'inline-block' : 'none';
    }

    btnSubmitManual.addEventListener('click', () => {
        const kode = manualNamaEl.value.trim();
        if (!kode) {
            manualErrorEl.textContent = 'Pilih nama siswa/guru terlebih dahulu.';
            manualErrorEl.style.display = 'block';
            return;
        }

        manualErrorEl.style.display = 'none';
        setManualLoading(true);

        fetch("<?php echo e(route('absen.manual')); ?>", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
            },
            body: JSON.stringify({
                kode:     kode,
                jenis:    manualJenisEl.value,
                kategori: (manualJenisEl.value === 'Haid' || manualJenisEl.value === 'Hadir') ? manualKategoriEl.value : null,
            }),
        })
        .then(res => res.json())
        .then(data => {
            setManualLoading(false);
            if (data.status === 'success') {
                bootstrap.Modal.getInstance(modalManualEl).hide();
                showNotifySukses({ nama: data.nama, kelas: data.kelas, kategori: data.kategori || manualKategoriEl.value });
            } else {
                manualErrorEl.textContent = data.message || 'Gagal menyimpan data.';
                manualErrorEl.style.display = 'block';
            }
        })
        .catch(() => {
            setManualLoading(false);
            manualErrorEl.textContent = 'Koneksi bermasalah, coba lagi.';
            manualErrorEl.style.display = 'block';
        });
    });

    /* ── Init: Deteksi Kamera ── */
    Html5Qrcode.getCameras()
        .then(cams => {
            if (!cams.length) {
                Toast.fire({ icon: 'error', title: 'Kamera tidak terdeteksi' });
                return;
            }
            const back = cams.find(c => /back|rear|environment/i.test(c.label));
            startScanner((back || cams[cams.length - 1]).id);
        })
        .catch(() => Toast.fire({ icon: 'error', title: 'Gagal mengakses kamera' }));
        
    // Panggil sekali untuk mengisi select di awal muat
    updateKategoriOptions();
</script>

<?php $__env->stopSection(); ?>
<?php echo $__env->make(auth()->user()->role == 'admin' ? 'layouts.admin' : 'layouts.petugas', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\absensi_muttaqin_v2\resources\views/absensi/scan.blade.php ENDPATH**/ ?>