<?php
// /lanchonete/public/app/index.php
require_once __DIR__ . "/../../includes/db.php"; // sem session_start aqui
require_once __DIR__ . "/../../includes/session_cliente.php"; // a mesma sessão do cliente

function base(): string { return "/lanchonete/public"; }
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, "UTF-8"); }

// Se já existe sessão/cookies válidos e você quiser mandar direto, pode manter.
// Mas como você quer "apenas QR", eu deixei comentado.
// if (!empty($_SESSION["cliente_id"]) && !empty($_SESSION["conta_id"]) && !empty($_SESSION["sessao_key"])) {
//   header("Location: " . base() . "/pedidos/index.php");
//   exit;
// }
?>
<!doctype html>
<html lang="pt-br">
<head>
  <meta charset="utf-8">
  <title>Pedidos</title>
  <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">

  <link rel="manifest" href="<?= h(base()."/app/manifest.json") ?>">
  <meta name="theme-color" content="#001322">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

  <style>
    :root{
      --bg:#1e1e1e; --card:#252526; --card2:#2d2d30; --text:#f3f3f3; --muted:#bdbdbd; --line: rgba(255,255,255,.10);
      --accent:#0078d4; --accent2:#2b88d8; --shadow: 0 10px 24px rgba(0,0,0,.45); --radius:14px;
      --btn:#2d2d30; --btnHover:#3a3a3d; --danger:#ff5a5f;
    }
    *{box-sizing:border-box}
    body{margin:0;font-family:"Segoe UI",system-ui;background:var(--bg);color:var(--text);padding:18px}
    .wrap{max-width:560px;margin:0 auto;display:grid;gap:12px}
    .top{display:flex;align-items:center;justify-content:space-between;gap:10px}
    .brand{display:flex;align-items:center;gap:10px}
    .logo{width:44px;height:44px;border-radius:12px;background:linear-gradient(135deg,var(--accent),var(--accent2));
      box-shadow:var(--shadow);display:grid;place-items:center;font-size:20px;border:1px solid rgba(255,255,255,.08)}
    .card{border:1px solid var(--line);background:var(--card);border-radius:var(--radius);box-shadow:var(--shadow);overflow:hidden}
    .head{padding:14px;background:var(--card2);border-bottom:1px solid var(--line)}
    .body{padding:14px;display:grid;gap:10px}
    .sub{color:var(--muted);font-size:12px;line-height:1.35}
    .btn{
      border:1px solid var(--line);
      background:var(--btn);
      color:var(--text);
      padding:12px 12px;
      border-radius:10px;
      cursor:pointer;
      font-weight:900;
    }
    .btn:hover{background:var(--btnHover)}
    .primary{
      border:none;
      background:linear-gradient(135deg,var(--accent),var(--accent2));
      color:#fff;
      padding:12px 12px;
      border-radius:10px;
      cursor:pointer;
      font-weight:950;
      box-shadow:var(--shadow);
    }
    .err{
      color: var(--danger);
      font-weight: 800;
      background: rgba(255,90,95,.10);
      border:1px solid rgba(255,90,95,.35);
      padding:10px 12px;
      border-radius: 10px;
    }
    video{width:100%;border-radius:12px;border:1px solid var(--line);background:#000}
    .row{display:flex;gap:10px;flex-wrap:wrap}
    .row > *{flex:1}
    .hide{display:none!important}
    /* ===== MODAL QR (Win10 dark) ===== */
.qrModal{
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,.55);
  display: none;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.qrModal.show{
  display: flex;
}

.qrModalCard{
  width: min(92vw, 420px);
  background: var(--card);
  color: var(--text);
  border: 1px solid var(--line);
  border-radius: 14px;
  box-shadow: var(--shadow);
  animation: modalIn .15s ease-out;
}

@keyframes modalIn{
  from{ transform: translateY(10px) scale(.97); opacity:0 }
  to{ transform: none; opacity:1 }
}

.qrModalHead{
  padding: 14px;
  display: flex;
  align-items: center;
  gap: 10px;
  background: var(--card2);
  border-bottom: 1px solid var(--line);
}

.qrModalIcon{
  font-size: 20px;
}

.qrModalBody{
  padding: 16px;
  font-size: 14px;
  line-height: 1.4;
}

.qrModalFooter{
  padding: 12px 14px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid var(--line);
}

.qrBtn{
  border: none;
  background: linear-gradient(135deg, var(--accent), var(--accent2));
  color: #fff;
  padding: 10px 16px;
  border-radius: 10px;
  font-weight: 900;
  cursor: pointer;
}

.qrBtn:active{
  transform: translateY(1px);
}

  </style>
</head>
<body>
<div class="wrap">
  <div class="top">
    <div class="brand">
      <div class="logo">🧾</div>
      <div>
        <div style="font-weight:950">Pedidos</div>
        <div class="sub">Escaneie o QR Code da mesa para entrar.</div>
      </div>
    </div>

    <button id="btnInstall" class="btn hide">📲 Instalar</button>
  </div>

  <div class="card">
    <div class="head">
      <div style="font-weight:950">Entrar pelo QR Code</div>
      <div class="sub" id="hintInstall"></div>
    </div>
    <div class="body">
      <div id="msgHttps" class="err hide">
        A câmera precisa de HTTPS. Abra usando <b>https://</b> (ou teste em localhost).
      </div>

      <div class="row">
        <button class="primary" id="btnScan">📷 Escanear QR da mesa</button>  
        <input type="hidden" id="btnStop" />
      </div>

      <!-- BarcodeDetector video -->
      <video id="video" class="hide" playsinline></video>

      <!-- html5-qrcode container -->
      <div id="qrBox" class="hide" style="border:1px solid var(--line);border-radius:12px;overflow:hidden"></div>

      <div class="sub">
        Dica: se você estiver no iPhone, para “instalar”, use:
        <b>Compartilhar → Adicionar à Tela de Início</b>.
      </div>
    </div>
  </div>
</div>

<script>
// ===== Service Worker =====
(async () => {
  if ("serviceWorker" in navigator) {
    try {
      await navigator.serviceWorker.register("<?= h(base()."/app/sw.js") ?>", { scope: "<?= h(base()."/") ?>" });
    } catch(e){}
  }
})();

// ===== Install button (Android/Chrome) =====
let deferredPrompt = null;
const btnInstall = document.getElementById("btnInstall");
const hintInstall = document.getElementById("hintInstall");

function isIOS(){
  return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
}

if (isIOS()){
  hintInstall.textContent = "No iPhone: Compartilhar → “Adicionar à Tela de Início”.";
} else {
  hintInstall.textContent = "No Android/Chrome: o botão “Instalar” aparece quando disponível.";
}

window.addEventListener("beforeinstallprompt", (e) => {
  e.preventDefault();
  deferredPrompt = e;
  btnInstall.classList.remove("hide");
});

btnInstall.addEventListener("click", async () => {
  if (!deferredPrompt) return;
  deferredPrompt.prompt();
  await deferredPrompt.userChoice;
  deferredPrompt = null;
  btnInstall.classList.add("hide");
});

// ===== QR Scanner =====
const btnScan = document.getElementById("btnScan");
const btnStop = document.getElementById("btnStop");
const video = document.getElementById("video");
const qrBox = document.getElementById("qrBox");
const msgHttps = document.getElementById("msgHttps");

const isSecure = (location.protocol === "https:" || location.hostname === "localhost" || location.hostname === "127.0.0.1");
if (!isSecure) msgHttps.classList.remove("hide");

let stream = null;
let scanning = false;
let detector = null;
let rafId = null;
let html5qr = null;

async function go(url){
  // 1) valida se parece uma URL
  let u;
  try {
    u = new URL(url, location.origin);
  } catch (e) {
    showError("QR Code inválido. Este código não é um link válido.");
    return;
  }

  // 2) valida se é do sistema
  if (!u.pathname.includes("/pedidos/identificar.php")) {
    showError("Este QR Code não pertence ao sistema de pedidos.");
    return;
  }

  // 3) valida no servidor (HEAD é rápido)
  try {
    const r = await fetch(u.href, { method: "HEAD", cache: "no-store" });
    if (!r.ok) {
      showError("Mesa não encontrada ou QR Code inválido.");
      return;
    }
  } catch (e) {
    showError("Não foi possível validar o QR Code. Verifique sua conexão.");
    return;
  }

  // 4) tudo ok → entra
  location.href = u.href;
}


async function stopAll(){
  scanning = false;
  btnStop.disabled = true;

  if (rafId) { cancelAnimationFrame(rafId); rafId = null; }

  if (html5qr){
    try { await html5qr.stop(); } catch(e){}
    try { await html5qr.clear(); } catch(e){}
    html5qr = null;
  }

  if (stream){
    for (const t of stream.getTracks()) t.stop();
    stream = null;
  }

  video.classList.add("hide");
  qrBox.classList.add("hide");
}

async function scanWithBarcodeDetector(){
  detector = new BarcodeDetector({ formats: ["qr_code"] });

  stream = await navigator.mediaDevices.getUserMedia({
    video: { facingMode: { ideal: "environment" } },
    audio: false
  });

  video.srcObject = stream;
  video.classList.remove("hide");
  await video.play();

  scanning = true;
  btnStop.disabled = false;

  const loop = async () => {
    if (!scanning) return;
    try {
      const codes = await detector.detect(video);
      if (codes && codes.length){
        const val = codes[0].rawValue || "";
        if (val){
          await stopAll();
          go(val);
          return;
        }
      }
    } catch(e){}
    rafId = requestAnimationFrame(loop);
  };
  loop();
}

function loadHtml5Qrcode(){
  return new Promise((resolve, reject) => {
    const s = document.createElement("script");
    s.src = "https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js";
    s.onload = resolve;
    s.onerror = reject;
    document.head.appendChild(s);
  });
}

async function scanWithHtml5Qrcode(){
  await loadHtml5Qrcode();
  qrBox.classList.remove("hide");

  html5qr = new Html5Qrcode("qrBox");
  btnStop.disabled = false;

  const config = { fps: 10, qrbox: { width: 260, height: 260 } };

  await html5qr.start(
    { facingMode: "environment" },
    config,
    async (decodedText) => {
      if (!decodedText) return;
      await stopAll();
      go(decodedText);
    },
    () => {}
  );
}

btnStop.addEventListener("click", stopAll);

btnScan.addEventListener("click", async () => {
  if (!isSecure){
    alert("A câmera precisa de HTTPS. Abra com https://");
    return;
  }
  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia){
    alert("Seu navegador não suporta câmera.");
    return;
  }

  await stopAll();

  try{
    // tenta BarcodeDetector primeiro (rápido e leve)
    if ("BarcodeDetector" in window){
      await scanWithBarcodeDetector();
    } else {
      await scanWithHtml5Qrcode();
    }
  }catch(e){
    // fallback final
    try{
      await scanWithHtml5Qrcode();
    }catch(e2){
      alert("Não foi possível abrir a câmera. Verifique permissões do navegador.");
    }
  }
});
function showError(msg){
  stopAll(); // para a câmera
  const modal = document.getElementById("qrModal");
  document.getElementById("qrModalMsg").textContent = msg;
  modal.classList.add("show");
}

function closeQrModal(){
  document.getElementById("qrModal").classList.remove("show");
}

</script>
<!-- MODAL ERRO QR -->
<div id="qrModal" class="qrModal">
  <div class="qrModalCard">
    <div class="qrModalHead">
      <span class="qrModalIcon">⚠️</span>
      <strong>QR Code inválido</strong>
    </div>
    <div class="qrModalBody" id="qrModalMsg">
      Mensagem
    </div>
    <div class="qrModalFooter">
      <button class="qrBtn" onclick="closeQrModal()">OK</button>
    </div>
  </div>
</div>

</body>
</html>
