<div class="container mt-4">
    <div class="card modern-card shadow-sm border-0 rounded-4">
        <div class="card-body p-4 text-center">
            <h5 id="judulscan">Silahkan Scan QR <?= ucfirst($scan_type); ?></h5>
            <div id="reader" style="max-width: 50%; margin: 0 auto;"></div>
            <div id="result" class="mt-4">Hasil scan akan muncul di sini</div>
            <button class="btn btn-success btn-add mt-3" id="backBtn" style="display:none;">Ulangi Scan</button>
            <a href="<?= base_url(); ?>" class="btn btn-success btn-add mt-3">Kembali</a>
        </div>
    </div>
</div>

<style>
/* Modern Detail Card Style */
.detail-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    max-width: 450px;
    margin: 20px auto;
}
.detail-card img {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid #fb6340;
}
.detail-card h2 {
    margin-top: 15px;
    color: #333;
    font-weight: 700;
}
.detail-row {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
    color: #555;
}
.detail-row:last-child {
    border-bottom: none;
}
.detail-label {
    font-weight: 600;
    color: #fb6340;
}
</style>

<script>
let scanner;
const resultDiv = document.getElementById("result");
const backBtn = document.getElementById("backBtn");
const judul = document.getElementById("judulscan");

function startScanner() {
    scanner = new Html5Qrcode("reader");

    Html5Qrcode.getCameras().then(cameras => {
        if (cameras && cameras.length) {
            let cameraId = cameras[0].id;
            const backCamera = cameras.find(cam =>
                cam.label.toLowerCase().includes("back")
            );
            if (backCamera) cameraId = backCamera.id;

            scanner.start(
                cameraId,
                { fps: 10, qrbox: { width: 250, height: 250 } },
                qrCodeMessage => {

                    // Stop scanner
                    scanner.stop().then(() => {
                        scanner.clear();

                        // Kirim data ke server
                        fetch('<?= site_url("cameraqrscan/get_data"); ?>', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                            body: new URLSearchParams({
                                qr_code: qrCodeMessage,
                                scan_type: '<?= $scan_type ?>'
                            })
                        })
                        .then(res => res.json())
                        .then(data => {

                            // Jika sukses (status true)
                            if (data.status) {

                                // Jika ada peringatan 5 menit
                                if (data.message && data.message.includes("5 menit")) {
                                    showDetail(data.data, true, data.message);
                                } 
                                // Sukses normal
                                else {
                                    showDetail(data.data, false, "");
                                }

                            } else {
                                // Jika error lain
                                resultDiv.innerHTML = `
                                    <p class="text-danger">${data.message}</p>
                                `;
                                backBtn.style.display = "inline-block";
                            }
                        });

                    });
                },
                errorMessage => {
                    console.warn(errorMessage);
                }
            ).catch(err => {
                console.error("Start scanner error:", err);
                alert("Gagal membuka kamera: " + err);
            });

        } else {
            alert("Tidak ada kamera terdeteksi");
        }
    }).catch(err => {
        console.error("Camera error:", err);
        alert("Tidak bisa mengakses kamera: " + err);
    });
}


// ===========================================
// TAMPIL DETAIL DATA + WARNING JIKA PERLU
// ===========================================
function showDetail(data, isWarning = false, warningText = "") {

    const foto = data.foto 
        ? `<?= base_url('uploads/siswa/') ?>` + data.foto
        : 'https://storage.manjapro.net/file/users/avatar/default.jpg';

    let warningHtml = "";
    if (isWarning) {
        warningHtml = `
            <div class="alert alert-warning mt-3">
                ⚠️ ${warningText}
            </div>
        `;
    }

    let html = `
        ${warningHtml}

        <h2>Scan <?= ucfirst($scan_type) ?> Berhasil</h2>

        <div class="detail-card text-center">
            <img src="${foto}" alt="Foto Siswa">

            <h2>${data.nama}</h2>

            <div class="detail-row mt-3">
                <div class="detail-label">Kelas</div>
                <div>${data.nama_kelas}</div>
            </div>

            <div class="detail-row mt-3">
                <div class="detail-label">Kamar</div>
                <div>${data.nama_kamar} (${data.nama_gedung_kamar})</div>
            </div>

            <div class="detail-row">
                <div class="detail-label">Alamat</div>
                <div>${data.alamat}</div>
            </div>

            <div class="detail-row">
                <div class="detail-label">Nama Orang Tua</div>
                <div>${data.nama_wali}</div>
            </div>

            <div class="detail-row">
                <div class="detail-label">Waktu</div>
                <div>${data.created_at}</div>
            </div>
        </div>
    `;

    resultDiv.innerHTML = html;

    backBtn.style.display = "inline-block";
    judul.style.display = "none";
}


// ===========================================
// TOMBOL ULANGI SCAN
// ===========================================
backBtn.addEventListener("click", () => {
    resultDiv.innerText = "Hasil scan akan muncul di sini";
    backBtn.style.display = "none";
    judul.style.display = "block";
    startScanner();
});


// ===========================================
// MULAI SCANNER SAAT PAGE LOAD
// ===========================================
window.onload = startScanner;
</script>
