<?php
require_once __DIR__.'/../../config/app.php';
$user = requireAuth(['officer']);
$pageTitle  = t('scan_qr');
$activePage = BASE_URL.'/officer/scan.php';
require __DIR__.'/../../app/Views/shared/layout.php';
?>

<div style="max-width:500px;margin:0 auto">
  <div class="card">
    <div class="card-header"><span class="card-title">📷 <?= t('scan_qr') ?></span></div>
    <div class="card-body" style="text-align:center">

      <p style="color:var(--text-muted);margin-bottom:20px;font-size:14px">
        <?= lang()==='ar' ? 'وجّه الكاميرا نحو رمز QR الخاص بالسيارة' : (lang()==='fr' ? 'Pointez la caméra vers le QR code du véhicule' : 'Point the camera at the vehicle QR code') ?>
      </p>

      <div id="reader" style="width:100%;max-width:340px;margin:0 auto;border-radius:var(--radius-md);overflow:hidden;border:2px solid var(--border)"></div>

      <div id="scanResult" style="display:none;margin-top:16px">
        <div class="alert alert-success">✓ <?= lang()==='ar'?'تم المسح':'QR Scanned' ?></div>
        <div id="scannedPlate" style="font-family:monospace;font-size:20px;font-weight:800;margin:10px 0"></div>
        <a id="verifyLink" href="#" class="btn btn-primary btn-lg" style="width:100%">🔍 <?= t('search_btn') ?></a>
      </div>

      <div style="margin-top:20px">
        <hr>
        <p style="font-size:13px;color:var(--text-muted);margin:12px 0"><?= lang()==='ar'?'أو أدخل رقم اللوحة يدوياً:':'Or enter plate manually:' ?></p>
        <form method="GET" action="<?= BASE_URL ?>/officer/search.php" style="display:flex;gap:10px">
          <input type="text" name="plate" class="form-control"
                 placeholder="16-ABC-01" style="text-transform:uppercase;text-align:center;font-size:16px;letter-spacing:.06em;flex:1" required>
          <button type="submit" class="btn btn-primary">🔍</button>
        </form>
      </div>
    </div>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.3.8/html5-qrcode.min.js"></script>
<script>
const searchBase = <?= json_encode(BASE_URL.'/officer/search.php?plate=') ?>;

function onScanSuccess(decodedText) {
  // Try to extract plate from URL or use text directly
  let plate = decodedText;
  try {
    const url = new URL(decodedText);
    plate = url.searchParams.get('plate') || decodedText;
  } catch(e) {}
  plate = plate.toUpperCase();

  document.getElementById('scanResult').style.display = 'block';
  document.getElementById('scannedPlate').textContent = plate;
  document.getElementById('verifyLink').href = searchBase + encodeURIComponent(plate);
  html5QrcodeScanner.clear();
  // Auto-redirect after 1.5s
  setTimeout(() => { window.location.href = searchBase + encodeURIComponent(plate); }, 1500);
}

const html5QrcodeScanner = new Html5QrcodeScanner("reader", {
  fps: 10,
  qrbox: { width: 240, height: 240 },
  aspectRatio: 1.0
}, false);
html5QrcodeScanner.render(onScanSuccess);
</script>

<?php require __DIR__.'/../../app/Views/shared/layout_end.php'; ?>
