<?php
$title = 'Scanner';
require_once __DIR__ . '/auth.php';
require_login();
check_csrf();
include __DIR__ . '/header.php';
?>
<div class="container-fluid">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h2 class="h5 m-0">Scanner QR (beta)</h2>
    <a class="btn btn-outline-secondary" href="<?= base_url('equipment.php') ?>">Equipamentos</a>
  </div>

  <div class="card border-0 shadow-sm">
    <div class="card-body">
      <div id="reader" style="max-width:480px"></div>
      <div class="form-text">Aponte a câmera para a etiqueta. Também aceita texto manual:</div>
      <form class="d-flex gap-2 mt-2" onsubmit="goManual(event)">
        <input id="manual" class="form-control" placeholder="Ex.: TAG:EQP-1-ABC12345 ou EQP:1">
        <button class="btn btn-primary">Abrir</button>
      </form>
    </div>
  </div>
</div>
<script src="https://unpkg.com/html5-qrcode"></script>
<script>
function handle(text){
  // Formatos aceitos: "TAG:<valor>", "EQP:<id>"
  if (text.startsWith('TAG:')) {
    window.location.href = "<?= base_url('scan_resolve.php?code=') ?>"+encodeURIComponent(text.substring(4));
    return;
  }
  if (text.startsWith('EQP:')) {
    const id = text.substring(4).replace(/\\D/g,'');
    if (id) { window.location.href = "<?= base_url('equipment_history.php?id=') ?>"+id; return; }
  }
  alert("Código não reconhecido: " + text);
}

function goManual(e){ e.preventDefault(); const v=document.getElementById('manual').value.trim(); if(v) handle(v); }

const html5QrCode = new Html5Qrcode("reader");
Html5Qrcode.getCameras().then(cams => {
  if (!cams || !cams.length) return;
  html5QrCode.start(
    cams[0].id,
    { fps: 10, qrbox: 250 },
    decodedText => { html5QrCode.stop(); handle(decodedText); },
    err => {}
  );
});
</script>
<?php include __DIR__ . '/footer.php'; ?>
