<?php
require_once("auth.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scan QR Code</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../assets/css/mobile-premium.css">
</head>
<body>
<div class="mobile-shell">
    <div class="mobile-header">
        <h2>Scan QR Code</h2>
        <p><?= htmlspecialchars($admin_name) ?></p>
    </div>

    <div class="premium-card">
        <h3>Scan Visitor QR</h3>
        <p class="note">Allow camera access and scan the visitor QR code. If camera scanning is not supported, use your phone camera app to open the QR link.</p>
        <video id="qrVideo" style="width:100%;border-radius:18px;background:#0f172a;min-height:280px;" autoplay muted playsinline></video>
        <div id="scanStatus" class="alert">Starting camera...</div>
        <button class="btn" type="button" onclick="startQrScanner()">Start Scanner</button>
    </div>

    <?php require_once("includes/bottom-nav.php"); ?>
</div>

<script src="../assets/js/mobile-app.js"></script>
<script>
let qrStream;

async function startQrScanner() {
    const status = document.getElementById("scanStatus");
    const video = document.getElementById("qrVideo");

    if (!("BarcodeDetector" in window)) {
        status.className = "alert error";
        status.textContent = "This browser does not support in-app QR scanning. Please scan using the phone camera.";
        return;
    }

    try {
        qrStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } });
        video.srcObject = qrStream;
        const detector = new BarcodeDetector({ formats: ["qr_code"] });
        status.className = "alert success";
        status.textContent = "Camera ready. Point at visitor QR.";

        const tick = async () => {
            if (!video.srcObject) return;
            try {
                const codes = await detector.detect(video);
                if (codes.length && codes[0].rawValue) {
                    window.location.href = codes[0].rawValue;
                    return;
                }
            } catch (e) {}
            requestAnimationFrame(tick);
        };
        tick();
    } catch (error) {
        status.className = "alert error";
        status.textContent = "Camera permission denied or unavailable.";
    }
}

document.addEventListener("DOMContentLoaded", startQrScanner);
</script>
</body>
</html>
