<?php
// FILE: scan.php 
session_start();
require_once 'db.php'; 
date_default_timezone_set('Asia/Jakarta'); 

// =========================================================================
// FUNGSI BARU: QR Dinamis Kantor
// =========================================================================

// Buat tabel untuk token QR dinamis (jalankan sekali di phpMyAdmin)
/*
CREATE TABLE qr_tokens (
    id INT PRIMARY KEY AUTO_INCREMENT,
    token VARCHAR(100) UNIQUE NOT NULL,
    expiry_time DATETIME NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    is_used BOOLEAN DEFAULT FALSE
);
*/

function generateDynamicQR($pdo) {
    // TIDAK PERLU LOGIN - siapa saja bisa generate QR untuk kantor
    
    // Buat token unik (berubah setiap 60 detik untuk keamanan)
    $token = 'KANTOR_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4));
    
    // Simpan token ke database dengan expiry time
    $expiry_time = date('Y-m-d H:i:s', strtotime('+5 minutes')); // QR berlaku 5 menit
    
    try {
        // Hapus token lama yang expired
        $pdo->exec("DELETE FROM qr_tokens WHERE expiry_time < NOW()");
        
        $stmt = $pdo->prepare("INSERT INTO qr_tokens (token, expiry_time) VALUES (?, ?)");
        $stmt->execute([$token, $expiry_time]);
    } catch (PDOException $e) {
        return ['success' => false, 'message' => 'Gagal menyimpan token: ' . $e->getMessage()];
    }
    
    // Generate QR Code
    if (file_exists('phpqrcode/qrlib.php')) {
        require_once 'phpqrcode/qrlib.php';
        
        if (!file_exists('temp_qr')) {
            mkdir('temp_qr', 0777, true);
        }
        
        $qr_data = "https://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/scan.php?qr_token=" . $token;
        $qr_filename = 'temp_qr/dynamic_qr_' . date('Ymd_His') . '.png';
        
        QRcode::png($qr_data, $qr_filename, QR_ECLEVEL_L, 8);
        
        return [
            'success' => true,
            'qr_path' => $qr_filename,
            'qr_data' => $qr_data,
            'token' => $token,
            'expiry_time' => $expiry_time,
            'refresh_time' => 60 // detik
        ];
    }
    
    return ['success' => false, 'message' => 'Library QR tidak ditemukan'];
}

// Fungsi untuk validasi token QR dinamis
function validateQRToken($token, $pdo) {
    try {
        $stmt = $pdo->prepare("SELECT token, expiry_time, is_used FROM qr_tokens WHERE token = ? AND expiry_time > NOW()");
        $stmt->execute([$token]);
        $token_data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$token_data) {
            return ['valid' => false, 'message' => 'QR Code sudah kadaluarsa atau tidak valid'];
        }
        
        if ($token_data['is_used']) {
            return ['valid' => false, 'message' => 'QR Code sudah digunakan'];
        }
        
        // Tandai token sebagai digunakan
        $stmt = $pdo->prepare("UPDATE qr_tokens SET is_used = TRUE WHERE token = ?");
        $stmt->execute([$token]);
        
        return ['valid' => true, 'message' => 'Token valid'];
        
    } catch (PDOException $e) {
        return ['valid' => false, 'message' => 'Error validasi token: ' . $e->getMessage()];
    }
}

/**
 * Fungsi untuk mengambil 5 siswa yang terakhir absen hari ini.
 * Menambahkan s.nisn ke dalam query.
 */
function fetchLastFiveAttendance($pdo) {
    $tanggal_hari_ini = date('Y-m-d');
    
    // Query mengambil 5 entri kehadiran 'H' (Hadir) terbaru hari ini
    try {
        $stmt = $pdo->prepare("
            SELECT 
                s.nama, 
                s.siswa_id,
                s.nisn,
                k.tanggal -- Ditambahkan untuk memastikan ORDER BY bekerja
            FROM kehadiran k
            JOIN siswa s ON k.siswa_id = s.siswa_id
            WHERE k.tanggal = ? AND k.status = 'H'
            -- Jika kolom kehadiran_id tidak ada, urutkan berdasarkan tanggal dan siswa_id
            ORDER BY k.tanggal DESC, s.siswa_id DESC 
            LIMIT 5
        ");
        $stmt->execute([$tanggal_hari_ini]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        // Jika error, kembalikan array kosong.
        // echo "Error: " . $e->getMessage(); // Uncomment jika perlu debugging
        return [];
    }
}

/**
 * Fungsi untuk memproses hasil scan.
 * Diubah agar memprioritaskan pencarian berdasarkan NISN, lalu fallback ke siswa_id.
 */
function processScan($barcode_value, $pdo) {
    $tanggal_hari_ini = date('Y-m-d');
    $bulan_hari_ini = date('Y-m');
    $siswa_id_scanned = null;
    $scanned_identifier = trim($barcode_value);

    // 1. Dapatkan Data Siswa dari Barcode/QR Code
    // Cek jika barcode berupa URL (untuk kompatibilitas)
    if (filter_var($barcode_value, FILTER_VALIDATE_URL)) {
        $url_parts = parse_url($barcode_value);
        parse_str($url_parts['query'] ?? '', $query_params);
        // Prioritaskan 'nisn' jika ada, fallback ke 'id'
        if (isset($query_params['nisn'])) {
            $scanned_identifier = $query_params['nisn'];
        } elseif (isset($query_params['id'])) {
            $scanned_identifier = $query_params['id'];
        }
    }
    
    try {
        // 2. Cari data siswa berdasarkan NISN, ID Siswa, atau ID Kartu (tap card)
        $stmt_siswa = $pdo->prepare("
            SELECT siswa_id, nama, kelas_id, foto_path, nisn 
            FROM siswa 
            WHERE nisn = ? OR siswa_id = ? OR id_card = ?
        ");

        // Coba cari sebagai NISN (string), sebagai Siswa ID (integer), atau sebagai ID Kartu
        // Jika barcode_value adalah string non-numeric, siswa_id akan diisi null
        $siswa_id_to_check = is_numeric($scanned_identifier) ? (int)$scanned_identifier : null;
        $stmt_siswa->execute([$scanned_identifier, $siswa_id_to_check, $scanned_identifier]);
        $siswa_profile_data = $stmt_siswa->fetch(PDO::FETCH_ASSOC);

        if (!$siswa_profile_data) {
            // SISWA TIDAK DITEMUKAN
            return ['is_error' => true, 'message' => "Error: Siswa dengan kode '{$scanned_identifier}' (NISN/ID) tidak ditemukan."];
        }
        
        $siswa_id_scanned = $siswa_profile_data['siswa_id']; // Ambil ID siswa yang valid

        // 3. Cek apakah siswa sudah absen hari ini
        $stmt_cek = $pdo->prepare("SELECT status FROM kehadiran WHERE siswa_id = ? AND tanggal = ?");
        $stmt_cek->execute([$siswa_id_scanned, $tanggal_hari_ini]);
        $status_kehadiran = $stmt_cek->fetchColumn();
        
        $nisn_display = $siswa_profile_data['nisn'] ? " (NISN: {$siswa_profile_data['nisn']})" : "";

        if ($status_kehadiran) {
            // Sudah Absen (Status dianggap error/perhatian)
            return [
                'is_error' => true, 
                'status_hadir' => $status_kehadiran,
                'message' => "Perhatian! {$siswa_profile_data['nama']}{$nisn_display} sudah absen hari ini ({$status_kehadiran}).",
                'profile' => $siswa_profile_data
            ];
        } else {
            // 4. Jika belum, masukkan data kehadiran
            $stmt_insert = $pdo->prepare("INSERT INTO kehadiran (siswa_id, tanggal, status, bulan) VALUES (?, ?, 'H', ?)");
            if ($stmt_insert->execute([$siswa_id_scanned, $tanggal_hari_ini, $bulan_hari_ini])) {
                // ABSEN BERHASIL
                return [
                    'is_error' => false, 
                    'status_hadir' => 'H',
                    'message' => "Berhasil! Kehadiran {$siswa_profile_data['nama']}{$nisn_display} tercatat Hadir.",
                    'profile' => $siswa_profile_data
                ];
            } else {
                // GAGAL INSERT
                return ['is_error' => true, 'message' => "Gagal! Terjadi kesalahan saat menyimpan data kehadiran."];
            }
        }
    } catch (PDOException $e) {
        // DATABASE ERROR
        return ['is_error' => true, 'message' => "Terjadi kesalahan pada database: " . $e->getMessage()];
    }
}

// =========================================================================
// LOGIKA UTAMA HALAMAN
// =========================================================================

// Hapus data sesi scan jika ada parameter clear
if (isset($_GET['clear_scan'])) {
    unset($_SESSION['last_scan']);
    header('Location: scan.php');
    exit;
}

// Generate QR dinamis jika parameter generate ada
$qr_dinamis = [];
if (isset($_GET['generate_qr'])) {
    $qr_dinamis = generateDynamicQR($pdo);
}

// Proses scan QR dinamis jika ada parameter token
if (isset($_GET['qr_token'])) {
    $token_validation = validateQRToken($_GET['qr_token'], $pdo);
    
    if ($token_validation['valid']) {
        // Redirect ke halaman login siswa untuk absensi
        $_SESSION['qr_token_valid'] = $_GET['qr_token'];
        header('Location: login_siswa.php?qr_scan=true');
        exit;
    } else {
        $_SESSION['qr_error'] = $token_validation['message'];
        header('Location: scan.php?qr_result=0');
        exit;
    }
}

// MENGIRIM JSON DENGAN POST (UNTUK AJAX)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['barcode_value'])) {
    $result = processScan($_POST['barcode_value'], $pdo);
    $result['waktu_scan'] = date('H:i:s');

    header('Content-Type: application/json');
    echo json_encode($result);
    exit; 
}

// Ambil 5 data absensi terbaru untuk ditampilkan di kolom kanan
$last_five_scans = fetchLastFiveAttendance($pdo);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SCAN ABSENSI - Mode Pop-up</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* Animasi untuk modal */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .fade-in {
            animation: fadeIn 0.5s ease-out;
        }
        .list-transition {
            transition: all 0.3s ease;
        }
        
        /* Style untuk QR Dinamis */
        .qr-dinamis-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 12px;
            padding: 15px;
            margin-top: 20px;
            color: white;
        }
        .qr-dinamis-box {
            width: 200px;
            height: 200px;
            background: white;
            padding: 10px;
            border-radius: 8px;
            margin: 0 auto;
        }
        .countdown-timer {
            font-size: 14px;
            font-weight: bold;
            background: rgba(0,0,0,0.3);
            padding: 5px 10px;
            border-radius: 20px;
            display: inline-block;
        }
    </style>
</head>
<body class="bg-gradient-to-br from-indigo-700 to-blue-800 min-h-screen flex items-center justify-center p-8">
    
    <audio id="success-sound" src="sound/success.mp3" preload="auto"></audio>
    <audio id="error-sound" src="sound/warning.mp3" preload="auto"></audio>

    <div class="bg-white p-8 rounded-2xl shadow-2xl w-full max-w-5xl">
        <h1 class="text-3xl font-extrabold text-indigo-700 mb-6 text-center">Sistem Absensi QR Code</h1>

        <!-- Tombol Generate QR Dinamis -->
        <div class="text-center mb-6">
            <a href="scan.php?generate_qr=1" class="bg-purple-600 text-white px-6 py-3 rounded-lg font-bold hover:bg-purple-700 transition duration-300">
                <i class="fas fa-qrcode mr-2"></i> Generate QR Code
            </a>
            <p class="text-sm text-gray-600 mt-2">Untuk ditampilkan di layar monitor kantor</p>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <div class="p-4 border-r lg:border-r-2 border-gray-200">
                <h2 class="text-2xl font-bold text-gray-800 mb-4 text-center">Area Pemindai 📸</h2>
                <p class="text-sm text-gray-500 mb-4 text-center">Pastikan kamera aktif dan arahkan QR Code ke bingkai.</p>
                
                <div id="qr-reader" class="rounded-lg overflow-hidden shadow-xl" style="width: 100%;"></div>
                <form id="scan-form" action="scan.php" method="POST" class="hidden"><input type="hidden" name="barcode_value" id="barcode-value-input"></form>
                
                <div id="loading-spinner" class="hidden text-center mt-4">
                    <div class="inline-block h-6 w-6 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
                    <p class="text-indigo-600 font-medium">Memproses data...</p>
                </div>

                <!-- ================================================ -->
                <!-- BAGIAN BARU: QR DINAMIS KANTOR -->
                <!-- ================================================ -->
                <?php if (!empty($qr_dinamis) && $qr_dinamis['success']): ?>
                <div class="qr-dinamis-section text-center fade-in">
                    <h3 class="text-xl font-bold mb-2">🏢 QR Dinamis Kantor</h3>
                    <p class="text-sm opacity-90 mb-3">Tampilkan QR ini di layar untuk di-scan siswa</p>
                    
                    <div class="qr-dinamis-box">
                        <img src="<?= $qr_dinamis['qr_path'] ?>" 
                             alt="QR Dinamis Kantor" 
                             class="w-full h-full">
                    </div>
                    
                    <div class="mt-3">
                        <p class="text-xs font-mono bg-black bg-opacity-20 p-2 rounded mb-2">
                            Token: <?= substr($qr_dinamis['token'], 0, 20) ?>...
                        </p>
                        <p class="text-xs mb-2">
                            <i class="fas fa-clock"></i> Berlaku hingga: 
                            <?= date('H:i:s', strtotime($qr_dinamis['expiry_time'])) ?>
                        </p>
                        
                        <div class="countdown-timer">
                            <i class="fas fa-sync-alt mr-1"></i>
                            Auto refresh dalam: <span id="countdown">60</span> detik
                        </div>
                    </div>
                    
                    <p class="text-xs mt-3 opacity-80">
                        <i class="fas fa-info-circle"></i> Siswa scan QR ini dengan kamera HP mereka
                    </p>
                </div>
                <?php elseif (isset($_GET['generate_qr']) && !$qr_dinamis['success']): ?>
                <div class="qr-dinamis-section text-center bg-red-500">
                    <h3 class="text-xl font-bold mb-2">❌ Error</h3>
                    <p class="text-sm"><?= $qr_dinamis['message'] ?></p>
                </div>
                <?php endif; ?>

            </div>
            
            <div class="p-4">
                <h2 class="text-2xl font-bold text-gray-800 mb-6 text-center">5 Absensi Terbaru Hari Ini</h2>
                
                <div id="last-scanned-list" class="space-y-3">
                    <?php if (!empty($last_five_scans)): ?>
                        <?php foreach ($last_five_scans as $index => $scan): ?>
                            <div class="flex items-center p-3 bg-gray-50 border border-gray-200 rounded-lg shadow-sm list-transition">
                                <div class="bg-indigo-500 text-white w-6 h-6 flex items-center justify-center rounded-full text-xs font-bold mr-3">
                                    <?= $index + 1 ?>
                                </div>
                                <div class="flex-1">
                                    <p class="text-sm font-semibold text-gray-800"><?= htmlspecialchars($scan['nama']) ?></p>
                                    <p class="text-xs text-gray-500">
                                        NISN: <?= htmlspecialchars($scan['nisn'] ?? 'N/A') ?> 
                                        (ID: #<?= htmlspecialchars($scan['siswa_id']) ?>)
                                    </p>
                                </div>
                                <span class="text-green-500 text-xs font-bold"><i class="fas fa-check-circle"></i> HADIR</span>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div id="initial-card" class="p-8 bg-gray-100 border-2 border-gray-300 rounded-xl shadow-inner text-center">
                            <i class="fas fa-list-alt text-6xl text-gray-400 mb-4"></i>
                            <p class="text-xl font-medium text-gray-600">Belum ada data absensi hari ini.</p>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Notifikasi Hasil Scan QR Dinamis -->
                <?php if (isset($_GET['qr_result'])): ?>
                    <?php if ($_GET['qr_result'] == '0' && isset($_SESSION['qr_error'])): ?>
                        <div class="mt-4 p-4 bg-red-100 border border-red-400 rounded-lg fade-in">
                            <p class="text-red-800 font-bold">
                                <i class="fas fa-times-circle mr-2"></i>
                                <?= $_SESSION['qr_error'] ?>
                            </p>
                        </div>
                        <?php unset($_SESSION['qr_error']); ?>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <div id="scan-modal" class="fixed inset-0 bg-black bg-opacity-75 hidden flex items-center justify-center p-4 z-50">
        <div id="modal-content" class="bg-white rounded-2xl shadow-2xl w-full max-w-sm transform transition-all duration-300 scale-95 opacity-0">
            <div class="p-6 text-center">
                <div id="modal-icon" class="text-6xl mb-4"></div>
                
                <p id="modal-message" class="text-lg font-semibold text-gray-700 mb-4"></p>
                
                <div id="modal-profile-data" class="mt-4 pt-4 border-t border-gray-300 hidden">
                    <p class="text-xs text-gray-500 mb-4">Menutup otomatis dalam <span id="modal-countdown" class="font-bold text-indigo-600">5</span> detik...</p>
                    
                    <div id="modal-photo-container" class="mb-4">
                        <img id="modal-photo" alt="Foto Siswa" class="w-40 h-40 object-cover rounded-full mx-auto border-4 border-indigo-300 shadow-md">
                    </div>
                    
                    <h3 id="modal-name" class="text-3xl font-extrabold text-indigo-700 mb-2"></h3>
                    <p id="modal-id" class="text-md text-gray-600 mb-4"></p>
                    
                    <span id="modal-status-badge" class="inline-block px-4 py-1 text-sm font-bold rounded-full text-white"></span>
                    
                    <p id="modal-time" class="text-sm text-gray-500 mt-2"></p>
                </div>

                <button onclick="closeModal()" class="mt-6 px-6 py-2 bg-indigo-600 text-white font-semibold rounded-lg shadow-md hover:bg-indigo-700 transition duration-300">
                    <i class="fas fa-undo mr-2"></i> Lanjutkan Pemindaian
                </button>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const loadingSpinner = document.getElementById('loading-spinner');
            const lastScannedList = document.getElementById('last-scanned-list');
            
            // Modal/Pop-up Elements
            const modal = document.getElementById('scan-modal');
            const modalContent = document.getElementById('modal-content');
            const modalIcon = document.getElementById('modal-icon');
            const modalMessage = document.getElementById('modal-message');
            const modalProfileData = document.getElementById('modal-profile-data');
            const modalPhoto = document.getElementById('modal-photo');
            const modalName = document.getElementById('modal-name');
            const modalId = document.getElementById('modal-id');
            const modalStatusBadge = document.getElementById('modal-status-badge');
            const modalTime = document.getElementById('modal-time');
            const modalCountdown = document.getElementById('modal-countdown');
            
            // Audio Elements
            const successSound = document.getElementById('success-sound');
            const errorSound = document.getElementById('error-sound');

            let html5QrcodeScanner;
            let countdownInterval;
            
            /**
             * Fungsi untuk memperbarui daftar 5 absensi terakhir di kolom kanan.
             * Diperbarui untuk menyertakan NISN.
             */
            function updateLastFiveList(data) {
                // Hanya perbarui daftar jika absensi berhasil dicatat (bukan jika sudah absen/error lain)
                if (!data.is_error && data.status_hadir === 'H' && data.profile) {
                    // Tentukan NISN untuk tampilan
                    const nisnDisplay = data.profile.nisn ? `NISN: ${data.profile.nisn}` : 'NISN: N/A';

                    const newEntry = `
                        <div class="flex items-center p-3 bg-indigo-50 border border-indigo-200 rounded-lg shadow-md fade-in list-transition">
                            <div class="bg-indigo-600 text-white w-6 h-6 flex items-center justify-center rounded-full text-xs font-bold mr-3">
                                1
                            </div>
                            <div class="flex-1">
                                <p class="text-sm font-semibold text-gray-800">${data.profile.nama}</p>
                                <p class="text-xs text-gray-500">
                                    ${nisnDisplay} (ID: #${data.profile.siswa_id})
                                </p>
                            </div>
                            <span class="text-green-600 text-xs font-bold"><i class="fas fa-check-circle"></i> HADIR</span>
                        </div>
                    `;

                    // Hapus pesan inisial jika ada
                    const initialCard = document.getElementById('initial-card');
                    if (initialCard) {
                        initialCard.remove();
                    }

                    // Tambahkan entri baru di bagian atas
                    lastScannedList.insertAdjacentHTML('afterbegin', newEntry);

                    // Hapus entri terlama jika jumlahnya melebihi 5
                    const listItems = lastScannedList.children;
                    if (listItems.length > 5) {
                        listItems[listItems.length - 1].remove();
                    }
                    
                    // Perbarui nomor urut
                    Array.from(listItems).forEach((item, index) => {
                        // Cari div yang berisi nomor urut (berdasarkan kelas bg-indigo)
                        const numberDiv = item.querySelector('.bg-indigo-500, .bg-indigo-600');
                        if(numberDiv) {
                            numberDiv.textContent = index + 1;
                        }
                    });
                }
            }

            // Fungsi untuk menutup Pop-up
            window.closeModal = function() {
                clearInterval(countdownInterval);
                modalContent.classList.remove('scale-100', 'opacity-100');
                modalContent.classList.add('scale-95', 'opacity-0');
                
                setTimeout(() => {
                    modal.classList.add('hidden');
                    // Lanjutkan scanner setelah modal ditutup
                    if (html5QrcodeScanner) {
                        html5QrcodeScanner.resume();
                    }
                }, 300); // Tunggu animasi transisi selesai
            }
            
            // Fungsi untuk memulai timer 5 atau 3 detik
            function startModalCountdown(isSuccess) {
                const initialTime = isSuccess ? 5 : 3;
                let timeLeft = initialTime;
                modalCountdown.textContent = timeLeft;

                countdownInterval = setInterval(() => {
                    timeLeft--;
                    modalCountdown.textContent = timeLeft;
                    if (timeLeft <= 0) {
                        clearInterval(countdownInterval);
                        closeModal();
                    }
                }, 1000);
            }
            
            /**
             * Fungsi untuk menampilkan Pop-up dengan data.
             * Diperbarui untuk menampilkan NISN.
             */
            function showModal(data) {
                const isSuccess = !data.is_error && data.status_hadir === 'H';
                
                // Tentukan warna dan ikon
                const cardColor = isSuccess ? 'text-green-500' : 'text-red-500';
                const iconClass = isSuccess ? 'fas fa-check-circle' : 'fas fa-times-circle';
                const statusBadgeColor = (data.profile && data.status_hadir === 'H') ? 'bg-green-500' : 'bg-orange-500';

                // Play sound
                if (isSuccess) {
                    successSound.play();
                } else {
                    errorSound.play();
                }

                // Isi konten
                modalIcon.className = `${iconClass} ${cardColor}`;
                modalMessage.textContent = data.message;
                
                // Tampilkan/Sembunyikan Data Profil
                if (data.profile) {
                    modalProfileData.classList.remove('hidden');
                    modalName.textContent = data.profile.nama;
                    
                    // MENAMPILKAN NISN
                    const nisnText = data.profile.nisn ? `NISN: ${data.profile.nisn}` : 'ID:';
                    modalId.textContent = `${nisnText} (#${data.profile.siswa_id})`;

                    modalStatusBadge.textContent = `STATUS: ${data.status_hadir || 'N/A'}`;
                    modalStatusBadge.className = `inline-block px-4 py-1 text-sm font-bold rounded-full text-white ${statusBadgeColor}`;
                    modalTime.textContent = `Pukul: ${data.waktu_scan}`;
                    
                    // Foto
                    if (data.profile.foto_path) {
                        modalPhoto.src = data.profile.foto_path;
                        modalPhoto.alt = `Foto ${data.profile.nama}`;
                        document.getElementById('modal-photo-container').classList.remove('hidden');
                    } else {
                        // Ganti dengan placeholder jika perlu, atau sembunyikan
                        document.getElementById('modal-photo-container').classList.add('hidden');
                    }
                } else {
                    modalProfileData.classList.add('hidden');
                }

                // Set timer text
                if (isSuccess) {
                    modalCountdown.textContent = '5';
                } else {
                    modalCountdown.textContent = '3';
                }

                // Show Modal with transition
                modal.classList.remove('hidden');
                setTimeout(() => {
                    modalContent.classList.remove('scale-95', 'opacity-0');
                    modalContent.classList.add('scale-100', 'opacity-100');
                }, 10);
                
                // Mulai Countdown
                startModalCountdown(isSuccess);
            }
            
            // Kirim nilai hasil scan (QR atau tap kartu) ke server
            async function submitScannedValue(scannedValue) {
                if (html5QrcodeScanner) {
                    html5QrcodeScanner.pause(true);
                }
                loadingSpinner.classList.remove('hidden');
                try {
                    const response = await fetch('scan.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: `barcode_value=${encodeURIComponent(scannedValue)}`
                    });
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    const result = await response.json();
                    showModal(result);
                    updateLastFiveList(result);
                } catch (error) {
                    showModal({
                        is_error: true,
                        message: `Error pemrosesan: Gagal menghubungi server atau terjadi kesalahan jaringan.`,
                        waktu_scan: new Date().toLocaleTimeString()
                    });
                } finally {
                    loadingSpinner.classList.add('hidden');
                }
            }

            // Dipanggil saat QR berhasil di-scan
            async function onScanSuccess(decodedText, decodedResult) {
                submitScannedValue(decodedText);
            }

            function onScanFailure(error) {
                // Biarkan kosong agar error scanner tidak mengganggu UX
            }
            
            // Inisialisasi Scanner
            html5QrcodeScanner = new Html5QrcodeScanner(
                "qr-reader", { fps: 10, qrbox: {width: 250, height: 250}, facingMode: "environment" }, false
            );
            html5QrcodeScanner.render(onScanSuccess, onScanFailure);

            // Listener untuk Tap Kartu (keyboard wedge dari card reader/NFC)
            // Mengumpulkan input cepat dan kirim saat Enter ditekan
            let cardBuffer = '';
            let lastKeyTime = 0;
            document.addEventListener('keydown', (e) => {
                // Abaikan jika modal sedang terbuka untuk menghindari input saat pop-up
                if (!modal.classList.contains('hidden')) return;

                const now = Date.now();
                // Reset buffer jika jeda antar input terlalu lama (> 100ms)
                if (now - lastKeyTime > 100) {
                    cardBuffer = '';
                }
                lastKeyTime = now;

                if (e.key === 'Enter') {
                    const code = cardBuffer.trim();
                    cardBuffer = '';
                    if (code) {
                        submitScannedValue(code);
                    }
                } else if (e.key.length === 1) {
                    cardBuffer += e.key;
                }
            });

            // Auto refresh untuk QR Dinamis
            <?php if (!empty($qr_dinamis) && $qr_dinamis['success']): ?>
            let countdown = 60;
            const countdownElement = document.getElementById('countdown');
            
            const countdownInterval = setInterval(() => {
                countdown--;
                countdownElement.textContent = countdown;
                
                if (countdown <= 0) {
                    clearInterval(countdownInterval);
                    window.location.href = 'scan.php?generate_qr=1';
                }
            }, 1000);
            <?php endif; ?>
        });
    </script>
</body>
</html>