<?php
require_once __DIR__ . "/_bootstrap.php";

/**
 * Estilo Win10 Dark (flat) alinhado ao "painel_melhorado_v3.php"
 * - Topbar sticky + menu desktop + drawer mobile
 * - Cards flat e consistentes
 */

// Imagem ao lado do "PDV" (240x48) - opcional
$brandRel = (defined('APP_BASE') ? APP_BASE : '') . "/assets/brand-240x48.png";
$brandFs  = __DIR__ . "/../assets/brand-240x48.png";
$hasBrand = is_file($brandFs);

// Link base (mantém seu padrão atual com BASE_URL)
$base = htmlspecialchars((string)BASE_URL, ENT_QUOTES, 'UTF-8');

// Links do menu (ajuste se quiser)
$menu = [
  ['href' => $base . '/public/garcom/pedidos.php', 'label' => 'Pedidos', 'ico' => '📋'],
  ['href' => $base . '/public/garcom/cartao.php',  'label' => 'Cartão',  'ico' => '💳'],
  ['href' => $base . '/lanchonete/public/garcom/index.php?logout=1', 'label' => 'Sair', 'ico' => '🚪'],
];
?>
<!doctype html>
<html lang="pt-br">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
  <title>Garçom • Painel</title>

  <style>
    :root{
      /* ===== Win10 Dark-ish ===== */
      --bg:#0f0f10;
      --bg2:#0a0a0b;

      --text:#f3f3f3;
      --muted: rgba(243,243,243,.70);

      --card: rgba(32,32,34,.72);
      --card2: rgba(26,26,28,.62);

      --line: rgba(255,255,255,.12);
      --line2: rgba(255,255,255,.08);

      --shadow: 0 18px 50px rgba(0,0,0,.55);
      --radius: 18px;

      --accent:#60cdff;
      --accent2:#2b88d8;

      --ok:#22c55e;
      --warn:#f59e0b;
      --danger:#ff5a5f;

      --tap: 48px;
    }

    *{ box-sizing:border-box }
    html,body{ height:100% }
    body{
      margin:0;
      font-family: system-ui,-apple-system,Segoe UI,Roboto,Arial;
      color:var(--text);
      background: var(--bg);
      min-height:100vh;
      overflow-x:hidden;
    }

    a{ color:inherit; text-decoration:none }
    button{ font-family:inherit }

    .wrap{ max-width:1100px; margin:0 auto; padding:14px 14px 28px; }

    /* ===== Topbar ===== */
    .topbar{
      position:sticky; top:0; z-index:50;
      padding:10px 0;
      backdrop-filter: blur(14px);
      -webkit-backdrop-filter: blur(14px);
      background: rgba(15,15,16,.92);
      border-bottom: 1px solid var(--line2);
    }
    .topbar-inner{
      max-width:1100px;
      margin:0 auto;
      padding:0 14px;
      display:flex;
      align-items:center;
      gap:12px;
    }

    .brand{
      display:flex;
      align-items:center;
      gap:10px;
      min-width: 190px;
    }
    .brand-badge{
      width:40px;height:40px;border-radius:14px;
      background: rgba(255,255,255,.06);
      border:1px solid var(--line);
      box-shadow: 0 12px 28px rgba(0,0,0,.35);
      display:grid;place-items:center;
      font-weight:900;
      color: rgba(243,243,243,.95);
      flex: 0 0 auto;
    }
    .brand-img{
      width:240px;
      height:48px;
      object-fit:contain;
      display:block;
      opacity:.95;
      max-width: 34vw;
    }

    .spacer{ flex:1 }

    .btn{
      height: var(--tap);
      padding:0 14px;
      display:inline-flex;
      align-items:center;
      gap:10px;
      border-radius: 14px;
      border:1px solid var(--line2);
      background: rgba(255,255,255,.05);
      text-decoration:none;
      color:var(--text);
      cursor:pointer;
      user-select:none;
      transition: transform .08s ease, border-color .12s ease, background .12s ease;
      white-space:nowrap;
    }
    .btn:hover{ background: rgba(255,255,255,.08); border-color: rgba(96,205,255,.18) }
    .btn:active{ transform: translateY(1px) }
    .btn-ghost{
      background: transparent;
      border-color: transparent;
    }
    .btn-ghost:hover{ background: rgba(255,255,255,.06); border-color: var(--line2) }

    .hamb{
      width: var(--tap);
      padding:0;
      display:none;
      justify-content:center;
      border-radius: 14px;
    }

    /* ===== Desktop menu ===== */
    .menu{
      display:flex;
      align-items:center;
      gap:8px;
    }

    /* ===== Mobile drawer ===== */
    .drawer-backdrop{
      position:fixed; inset:0;
      background: rgba(0,0,0,.55);
      backdrop-filter: blur(4px);
      -webkit-backdrop-filter: blur(4px);
      display:none;
      z-index:80;
    }
    .drawer{
      position:fixed;
      top:0; right:0;
      height:100%;
      width:min(420px, 92vw);
      background: rgba(18,18,20,.92);
      border-left: 1px solid var(--line2);
      box-shadow: -18px 0 55px rgba(0,0,0,.55);
      transform: translateX(105%);
      transition: transform .16s ease;
      z-index:90;
      padding:14px;
      display:flex;
      flex-direction:column;
      gap:10px;
    }
    .drawer.open{ transform: translateX(0) }
    .drawer-backdrop.open{ display:block }

    .drawer-head{
      display:flex;
      align-items:center;
      justify-content:space-between;
      gap:12px;
      padding:10px 10px;
      border:1px solid var(--line2);
      border-radius: 16px;
      background: rgba(255,255,255,.04);
    }

    .drawer-links{
      display:flex;
      flex-direction:column;
      gap:10px;
      padding-top:6px;
    }
    .drawer-links a{
      padding:14px 14px;
      border-radius: 16px;
      border:1px solid var(--line2);
      background: rgba(255,255,255,.05);
      text-decoration:none;
      display:flex;
      align-items:center;
      justify-content:space-between;
    }
    .drawer-links a:hover{ border-color: rgba(96,205,255,.18) }

    /* ===== Content ===== */
    .hero{
      margin-top:16px;
      background: rgba(32,32,34,.70);
      border:1px solid var(--line2);
      border-radius: 22px;
      box-shadow: var(--shadow);
      padding:16px;
    }
    .hero h1{ margin:0; font-size:18px; letter-spacing:.2px }
    .hero p{ margin:6px 0 0; color:var(--muted); font-size:13px }

    .grid{
      display:grid;
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap:12px;
      margin-top:12px;
    }

    .card{
      background: rgba(32,32,34,.70);
      border:1px solid var(--line2);
      border-radius: 22px;
      box-shadow: 0 16px 45px rgba(0,0,0,.45);
      padding:14px;
      overflow:hidden;
    }
    .card h2{ margin:0; font-size:15px; font-weight:900; letter-spacing:.2px }
    .sub{ color:var(--muted); font-size:12px; margin-top:6px; line-height:1.35 }

    .cta{
      width:100%;
      height:56px;
      border-radius: 18px;
      font-weight:950;
      border:1px solid rgba(255,255,255,.14);
      background: rgba(255,255,255,.06);
      color:var(--text);
      display:flex;
      align-items:center;
      justify-content:center;
      margin-top:12px;
      cursor:pointer;
      transition: transform .08s ease, background .12s ease, border-color .12s ease;
    }
    .cta:hover{ background: rgba(255,255,255,.09); border-color: rgba(96,205,255,.18) }
    .cta:active{ transform: translateY(1px) }

    .cta.primary{
      border-color: rgba(96,205,255,.22);
    }
    .cta.danger{
      border-color: rgba(255,90,95,.26);
    }

    .badge{
      display:inline-flex;
      align-items:center;
      justify-content:center;
      min-width: 22px;
      height: 22px;
      padding:0 8px;
      border-radius: 999px;
      background: rgba(255,90,95,.18);
      border:1px solid rgba(255,90,95,.26);
      font-size: 12px;
      font-weight: 900;
      margin-left:6px;
    }

    /* Chamados list */
    .list{
      margin-top:12px;
      display:flex;
      flex-direction:column;
      gap:10px;
    }
    .item{
      border-radius: 18px;
      border:1px solid var(--line2);
      background: rgba(255,255,255,.04);
      padding:12px;
    }
    .itemTop{
      display:flex;
      justify-content:space-between;
      align-items:flex-start;
      gap:10px;
    }
    .item b{ font-weight:950 }
    .muted{ color:var(--muted); font-size:12px; margin-top:6px; line-height:1.35 }

    .rowBtns{
      display:flex;
      gap:10px;
      flex-wrap:wrap;
      margin-top:10px;
    }

    .footer{
      margin-top:14px;
      color: rgba(243,243,243,.55);
      font-size:12px;
      text-align:center;
    }

    @media (max-width: 860px){
      .menu{ display:none; }
      .hamb{ display:inline-flex; }
      .brand{ min-width: 0; }
      .brand-img{ max-width: 52vw; }
      .grid{ grid-template-columns: 1fr; }
    }

    @media (prefers-reduced-motion: reduce){
      *{ transition:none !important; scroll-behavior:auto !important; }
    }
  </style>
</head>

<body>
  <header class="topbar">
    <div class="topbar-inner">
      <div class="brand">
        <div class="brand-badge">PDV</div>

        <?php if ($hasBrand): ?>
          <img class="brand-img" src="<?= $brandRel ?>" alt="Marca">
        <?php else: ?>
          <div style="line-height:1.05">
            <div style="font-weight:900;font-size:14px">Garçom</div>
            <div style="font-size:12px;color:var(--muted)">Painel</div>
          </div>
        <?php endif; ?>
      </div>

      <nav class="menu" aria-label="Menu">
        <a class="btn btn-ghost" href="<?= $base ?>/public/garcom/pedidos.php">📋 Pedidos</a>
        <a class="btn btn-ghost" href="<?= $base ?>/public/garcom/cartao.php">💳 Cartão</a>
      </nav>

      <div class="spacer"></div>

      <a class="btn" href="<?= $base ?>/lanchonete/public/garcom/index.php?logout=1">Sair</a>
      <button class="btn hamb" id="btnMenu" type="button" aria-label="Abrir menu" aria-controls="drawer" aria-expanded="false">☰</button>
    </div>
  </header>

  <!-- Mobile drawer -->
  <div class="drawer-backdrop" id="backdrop" tabindex="-1" aria-hidden="true"></div>
  <aside class="drawer" id="drawer" aria-label="Menu mobile">
    <div class="drawer-head">
      <div style="display:flex;align-items:center;gap:10px;min-width:0">
        <div class="brand-badge" style="width:38px;height:38px;border-radius:14px">PDV</div>
        <div style="min-width:0">
          <div style="font-weight:900;font-size:14px">Garçom</div>
          <div style="font-size:12px;color:var(--muted)">Menu</div>
        </div>
      </div>
      <button class="btn" id="btnClose" type="button" aria-label="Fechar menu">✕</button>
    </div>

    <div class="drawer-links">
      <a href="<?= $base ?>/public/garcom/pedidos.php"><span>📋 Pedidos</span><span style="opacity:.7">›</span></a>
      <a href="<?= $base ?>/public/garcom/cartao.php"><span>💳 Cartão</span><span style="opacity:.7">›</span></a>
      <a href="<?= $base ?>/lanchonete/public/garcom/index.php?logout=1" style="border-color: rgba(255,90,95,.25);"><span>🚪 Sair</span><span style="opacity:.7">›</span></a>
    </div>

    <div style="margin-top:auto; padding:12px 6px; color:rgba(243,243,243,.55); font-size:12px">
      Dica: toque fora do menu para fechar.
    </div>
  </aside>

  <main class="wrap">
    <section class="hero">
      <h1>Garçom • Painel</h1>
      <p>Pedidos • Chamados • Débito no Cartão</p>
    </section>

    <section class="grid">
      <div class="card">
        <h2>📋 Pedidos</h2>
        <div class="sub">Abrir tela de pedidos do garçom.</div>

        <a class="cta primary" href="<?= $base ?>/public/garcom/pedidos.php">Abrir Pedidos</a>

        <div class="muted">
          Se você ainda não tem <span style="color:var(--accent)">/garcom/pedidos.php</span>, me envie o seu antigo index de pedidos que eu renomeio certinho.
        </div>
      </div>

      <div class="card">
        <h2>💳 Débito no Cartão</h2>
        <div class="sub">Ler QR do cartão, ver saldo e debitar consumo.</div>

        <a class="cta danger" href="<?= $base ?>/public/garcom/cartao.php">Debitar no Cartão</a>

        <div class="muted">Regras: só debita cartão <b>EM_USO</b> (sessão aberta) e com saldo suficiente.</div>
      </div>
    </section>

    <section class="card" style="margin-top:12px;">
      <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;">
        <div>
          <h2 style="display:flex;align-items:center;gap:6px;margin:0;">
            🔔 Chamados do Garçom
            <span id="chamadosCount" class="badge" style="display:none;"></span>
          </h2>
          <div class="sub">Pedidos de atendimento feitos pelo cliente.</div>
        </div>

        <button id="btnRefreshChamados" class="btn" type="button">Atualizar</button>
      </div>

      <div id="chamadosBox" class="list">
        <div class="muted">Carregando chamados…</div>
      </div>
    </section>

    <div class="footer">© <?=date('Y')?> • Garçom</div>
  </main>

  <script>
    // ===== Drawer =====
    (function(){
      const btnMenu = document.getElementById('btnMenu');
      const btnClose = document.getElementById('btnClose');
      const drawer = document.getElementById('drawer');
      const backdrop = document.getElementById('backdrop');

      function openDrawer(){
        backdrop.classList.add('open');
        drawer.classList.add('open');
        btnMenu?.setAttribute('aria-expanded', 'true');
      }
      function closeDrawer(){
        backdrop.classList.remove('open');
        drawer.classList.remove('open');
        btnMenu?.setAttribute('aria-expanded', 'false');
      }

      btnMenu?.addEventListener('click', openDrawer);
      btnClose?.addEventListener('click', closeDrawer);
      backdrop?.addEventListener('click', closeDrawer);
      document.addEventListener('keydown', (e)=>{
        if (e.key === 'Escape') closeDrawer();
      });
    })();

    // ===== Chamados =====
    const chamadosBox = document.getElementById('chamadosBox');
    const chamadosCount = document.getElementById('chamadosCount');
    const btnRefreshChamados = document.getElementById('btnRefreshChamados');

    function escHtml(s){
      return String(s ?? '').replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
    }

    async function apiGet(url){
      const r = await fetch(url, { cache:'no-store' });
      const t = await r.text();
      let j;
      try { j = JSON.parse(t); }
      catch(e){
        throw new Error('Resposta não-JSON do servidor: ' + t.slice(0, 200));
      }
      return j;
    }

    function renderChamados(list){
      if (!Array.isArray(list) || list.length === 0){
        chamadosBox.innerHTML = `<div class="muted">Nenhum chamado pendente.</div>`;
        chamadosCount.style.display = 'none';
        return;
      }

      chamadosCount.textContent = String(list.length);
      chamadosCount.style.display = 'inline-flex';

      chamadosBox.innerHTML = list.map(ch => {
        const mesa = escHtml(ch.mesa ?? ch.mesa_id ?? '');
        const nome = escHtml(ch.nome ?? ch.cliente_nome ?? '');
        const msg  = escHtml(ch.mensagem ?? ch.msg ?? ch.texto ?? 'Chamado');
        const em   = escHtml(ch.criado_em ?? ch.data ?? '');

        return `
          <div class="item">
            <div class="itemTop">
              <div>
                <b>Mesa ${mesa || '-'}</b>
                <div class="muted">${nome ? 'Cliente: ' + nome + '<br>' : ''}${msg}</div>
              </div>
              <div class="muted" style="white-space:nowrap">${em}</div>
            </div>
          </div>
        `;
      }).join('');
    }

    async function carregarChamados(){
      try{
        const j = await apiGet('api.php?action=listar_chamados&pendentes=1');
        if(!j.ok){
          chamadosBox.innerHTML = `<div class="muted" style="color:var(--warn)">Falha ao carregar chamados: ${escHtml(j.error || 'Erro')}</div>`;
          chamadosCount.style.display = 'none';
          return;
        }
        renderChamados(j.chamados || j.items || j.data || []);
      }catch(e){
        chamadosBox.innerHTML = `<div class="muted" style="color:var(--warn)">Erro: ${escHtml(e?.message || e)}</div>`;
        chamadosCount.style.display = 'none';
      }
    }

    btnRefreshChamados?.addEventListener('click', carregarChamados);
    carregarChamados();
    // refresh leve a cada 25s
    setInterval(carregarChamados, 25000);
  </script>
</body>
</html>
