<?php
require_once __DIR__ . '/auth.php';
require_login();
check_csrf();

$id = (int)($_GET['id'] ?? 0);
$q = $pdo->prepare("SELECT e.*, et.name tipo FROM equipment e JOIN equipment_types et ON et.id=e.type_id WHERE e.id=?");
$q->execute([$id]); $eq = $q->fetch();
if (!$eq) { http_response_code(404); exit('Equipamento não encontrado'); }

if (empty($eq['tag_qr'])) {
  header('Location: '.base_url('equipment_generate_tag.php?id='.$id)); exit;
}
?>
<!doctype html><html lang="pt-br"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Etiqueta #<?= (int)$eq['id'] ?></title>
<style>
  body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif; }
  .label { width: 420px; border: 1px solid #000; padding: 12px; }
  .row { display:flex; gap:12px; }
  .qr { width:140px; height:140px; border:1px solid #000; }
  .meta { flex:1; font-size:14px; }
  .id   { font-weight:700; font-size:18px; }
  @media print { .noprint { display:none } body { margin:0 } .label { border:0 } }
</style>
</head><body>
<div class="label">
  <div class="row">
    <div id="qrcode" class="qr"></div>
    <div class="meta">
      <div class="id">#<?= (int)$eq['id'] ?> • <?= htmlspecialchars($eq['tipo']) ?></div>
      <div><?= htmlspecialchars($eq['modelo'] ?? '') ?></div>
      <div>PAT: <?= htmlspecialchars($eq['patrimonio'] ?? '—') ?></div>
      <div>SN: <?= htmlspecialchars($eq['serial'] ?? '—') ?></div>
      <div style="margin-top:8px"><small>TAG: <?= htmlspecialchars($eq['tag_qr']) ?></small></div>
    </div>
  </div>
</div>
<div class="noprint" style="margin-top:8px">
  <button onclick="window.print()">Imprimir</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
<script>
  // Conteúdo do QR: padrão TAG:<valor>
  new QRCode(document.getElementById("qrcode"), {
    text: "TAG:<?= htmlspecialchars($eq['tag_qr']) ?>",
    width: 140, height: 140, correctLevel: QRCode.CorrectLevel.M
  });
</script>
</body></html>
