<?php
require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/middleware/auth.php';

require_login();

$pageTitle = 'Scan QR';
require_once __DIR__ . '/../app/views/partials/header.php';
?>

<div class="container">
  <div class="card p-4">
    <h5 class="mb-2">Scan QR (Camera)</h5>
    <div class="text-muted mb-3">
      Allow camera access. Use the back camera and point at the QR code.
    </div>

    <div id="reader" style="width:100%; max-width:520px;"></div>
    <div id="scanStatus" class="text-muted small mt-2">Loading scanner…</div>

    <hr class="my-4">

    <div class="row g-2 align-items-end">
      <div class="col-md-8">
        <label class="form-label">Manual token (t)</label>
        <input id="manualToken" class="form-control" placeholder="Paste token here" />
      </div>
      <div class="col-md-4">
        <button class="btn btn-primary w-100" type="button" onclick="manualGo()">Open</button>
      </div>
    </div>

    <div class="form-text mt-2">
      Tip: If your QR contains a full link, this page will still extract <code>?t=...</code>.
    </div>
  </div>
</div>

<script src="https://unpkg.com/html5-qrcode"></script>

<script>
const BASE_SCAN_URL = "<?= BASE_URL ?>/scan.php?t=";
const statusEl = document.getElementById("scanStatus");
let html5Qr = null;
let isStopping = false;

function setStatus(msg) {
  if (statusEl) statusEl.textContent = msg;
}

function redirectWithValue(decodedText) {
  if (!decodedText) return;

  // If QR code contains a full URL, try to extract t=...
  try {
    const url = new URL(decodedText);
    const token = url.searchParams.get("t") || url.searchParams.get("token");
    if (token) {
      window.location.href = BASE_SCAN_URL + encodeURIComponent(token);
      return;
    }
    // If it's a URL without token, just go to it
    window.location.href = decodedText;
    return;
  } catch (e) {
    // Not a URL => assume it's the token
    window.location.href = BASE_SCAN_URL + encodeURIComponent(decodedText);
  }
}

function manualGo() {
  const val = document.getElementById("manualToken").value.trim();
  if (!val) {
    setStatus("Paste a token first.");
    return;
  }
  redirectWithValue(val);
}

async function startScanner() {
  if (typeof Html5Qrcode === "undefined") {
    setStatus("Scanner library failed to load.");
    return;
  }

  html5Qr = new Html5Qrcode("reader");

  setStatus("Starting camera…");

  try {
    // Force rear camera with facingMode (better for QR scanning)
    await html5Qr.start(
      { facingMode: "environment" },
      { fps: 10, qrbox: { width: 260, height: 260 } },
      async (decodedText) => {
        if (isStopping) return;
        isStopping = true;

        setStatus("QR detected. Opening…");

        try { await html5Qr.stop(); } catch (e) {}
        try { html5Qr.clear(); } catch (e) {}

        redirectWithValue(decodedText);
      },
      () => {
        // ignore scan errors (normal while camera is searching)
      }
    );

    setStatus("Camera ready. Point at the QR code…");
  } catch (err) {
    console.error(err);
    setStatus("Camera failed to start. Check permissions / try HTTPS / try another device.");
  }
}

window.addEventListener("beforeunload", async () => {
  if (!html5Qr) return;
  try { await html5Qr.stop(); } catch (e) {}
});

startScanner();
</script>

<?php require_once __DIR__ . '/../app/views/partials/footer.php'; ?>
