<?php
declare(strict_types=1);
require_once __DIR__ . "/_bootstrap.php";
require_once __DIR__ . "/verifica_admin.php";
?>
<!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>Admin • Cardápio</title>
  <style>
    :root{
      --bg:#0f0f10; --text:#f3f3f3; --muted:rgba(243,243,243,.70);
      --card:rgba(32,32,34,.72); --line:rgba(255,255,255,.12);
      --shadow:0 18px 50px rgba(0,0,0,.45); --radius:16px;
      --accent:#60cdff; --ok:#22c55e; --warn:#f59e0b; --danger:#ff5a5f;
      --input: rgba(18,18,20,.78);
    }
    body{ margin:0; font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial; background:var(--bg); color:var(--text); }
    .wrap{ max-width:1100px; margin:0 auto; padding:18px; }
    .top{ display:flex; gap:12px; align-items:center; justify-content:space-between; margin-bottom:14px; }
    .card{ background:var(--card); border:1px solid var(--line); border-radius:var(--radius); box-shadow:var(--shadow); overflow:hidden; }
    .card h2{ margin:0; font-size:16px; padding:14px 16px; border-bottom:1px solid var(--line); }
    .pad{ padding:14px 16px; }
    .row{ display:flex; gap:10px; flex-wrap:wrap; }
    input, select, textarea{ background:var(--input); color:var(--text); border:1px solid var(--line); border-radius:12px; padding:10px 12px; outline:none; }
    textarea{ min-height:92px; resize:vertical; }
    button{ border:1px solid var(--line); background:rgba(255,255,255,.06); color:var(--text); border-radius:12px; padding:10px 12px; cursor:pointer; }
    button.primary{ border-color: rgba(96,205,255,.45); }
    table{ width:100%; border-collapse:collapse; }
    th,td{ padding:10px 12px; border-bottom:1px solid var(--line); font-size:14px; vertical-align:top; }
    th{ text-align:left; color:var(--muted); font-weight:600; }
    .badge{ padding:4px 10px; border-radius:999px; font-size:12px; border:1px solid var(--line); }
    .ok{ color:var(--ok); }
    .danger{ color:var(--danger); }
    .muted{ color:var(--muted); }
    .modalBack{ position:fixed; inset:0; background:rgba(0,0,0,.6); display:none; align-items:center; justify-content:center; padding:16px; }
    .modal{ width:min(720px, 100%); background:rgba(24,24,26,.92); border:1px solid var(--line); border-radius:18px; box-shadow:var(--shadow); overflow:hidden; }
    .modal .hd{ padding:14px 16px; border-bottom:1px solid var(--line); font-weight:800; }
    .modal .bd{ padding:14px 16px; }
    .modal .ft{ padding:14px 16px; border-top:1px solid var(--line); display:flex; gap:10px; justify-content:flex-end; }
    img.thumb{ width:54px; height:54px; object-fit:cover; border-radius:12px; border:1px solid var(--line); background:rgba(255,255,255,.06); }
  </style>
</head>
<body>
  <div class="wrap">
    <div class="top">
      <div>
        <div style="font-size:18px;font-weight:800">Admin • Cardápio</div>
        <div class="muted" style="font-size:13px">Inserir e editar produtos</div>
      </div>
      <div class="row">
        <button class="primary" onclick="openProd()">+ Novo produto</button>
        <button onclick="load()">Atualizar</button>
      </div>
    </div>

    <div class="card">
      <h2>Lista</h2>
      <div class="pad">
        <div class="row" style="margin-bottom:10px">
          <input id="q" placeholder="Buscar por nome/categoria..." style="flex:1; min-width:220px">
          <button onclick="load()">Buscar</button>
        </div>

        <div style="overflow:auto">
          <table>
            <thead>
              <tr>
                <th>ID</th>
                <th>Foto</th>
                <th>Produto</th>
                <th>Categoria</th>
                <th>Preço</th>
                <th>Status</th>
                <th style="width:180px">Ações</th>
              </tr>
            </thead>
            <tbody id="tbody"></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <!-- Modal -->
  <div class="modalBack" id="mb">
    <div class="modal">
      <div class="hd" id="mt">Produto</div>
      <div class="bd">
        <input type="hidden" id="id">
        <div class="row" style="margin-bottom:10px">
          <input id="nome" placeholder="Nome" style="flex:1; min-width:260px">
          <input id="categoria" placeholder="Categoria" style="flex:1; min-width:220px">
        </div>
        <div class="row" style="margin-bottom:10px">
          <input id="preco" placeholder="Preço (ex: 15.00)" inputmode="decimal" style="width:220px">
          <select id="ativo" style="width:220px">
            <option value="1">Ativo</option>
            <option value="0">Inativo</option>
          </select>
          <input type="file" id="foto_file" accept="image/*" style="flex:1; min-width:220px">
          <input type="hidden" id="foto">
        </div>
        <div class="row">
          <textarea id="descricao" placeholder="Descrição (opcional)" style="flex:1"></textarea>
        </div>
        <div class="muted" style="font-size:12px;margin-top:8px">
          Foto: por enquanto é só o nome do arquivo (igual seu menu atual). Se você quiser upload, eu adiciono.
        </div>
      </div>
      <div class="ft">
        <button onclick="closeModal()">Cancelar</button>
        <button class="primary" onclick="save()">Salvar</button>
      </div>
    </div>
  </div>

<script>
const api = 'produtos_api.php';
function esc(s){ return String(s??'').replace(/[&<>"']/g, m=>({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;' }[m])); }
async function jget(url){ const r=await fetch(url,{credentials:'same-origin'}); return await r.json(); }
async function jpost(obj){
  const r = await fetch(api, {method:'POST', headers:{'Content-Type':'application/json'}, credentials:'same-origin', body:JSON.stringify(obj)});
  return await r.json();
}
function openProd(p=null){
  document.getElementById('mb').style.display='flex';
  document.getElementById('mt').textContent = p ? 'Editar produto' : 'Novo produto';
  document.getElementById('id').value = p?.id ?? '';
  document.getElementById('nome').value = p?.nome ?? '';
  document.getElementById('categoria').value = (p?.categoria ?? 'Geral');
  document.getElementById('preco').value = p?.preco ?? '';
  document.getElementById('ativo').value = String(p?.ativo ?? 1);
  document.getElementById('foto').value = p?.foto ?? '';
  document.getElementById('descricao').value = p?.descricao ?? '';
}
function closeModal(){ document.getElementById('mb').style.display='none'; }

async function load(){
  const q = document.getElementById('q').value.trim();
  const j = await jget(api + '?action=list&q=' + encodeURIComponent(q));
  const tb = document.getElementById('tbody');
  tb.innerHTML='';
  if(!j.ok){ tb.innerHTML = `<tr><td colspan="7" class="danger">${esc(j.error||'Erro')}</td></tr>`; return; }

  for(const p of j.produtos){
    const st = (p.ativo==1) ? `<span class="badge ok">ATIVO</span>` : `<span class="badge danger">INATIVO</span>`;
    const img = p.foto ? `<img class="thumb" src="../pedidos/fotos/${esc(p.foto)}" onerror="this.style.display='none'">` : '';
    tb.innerHTML += `
      <tr>
        <td>${esc(p.id)}</td>
        <td>${img}</td>
        <td><b>${esc(p.nome)}</b><div class="muted" style="font-size:12px">${esc(p.descricao||'')}</div></td>
        <td>${esc(p.categoria||'')}</td>
        <td>R$ ${esc(p.preco)}</td>
        <td>${st}</td>
        <td><button onclick='edit(${JSON.stringify(p)})'>Editar</button></td>
      </tr>
    `;
  }
}
function edit(p){ openProd(p); }

async function save(){
  const fd = new FormData();
  fd.append('action', 'save');
  fd.append('id', document.getElementById('id').value);
  fd.append('nome', document.getElementById('nome').value.trim());
  fd.append('categoria', document.getElementById('categoria').value.trim());
  fd.append('preco', document.getElementById('preco').value.trim());
  fd.append('ativo', document.getElementById('ativo').value);
  fd.append('descricao', document.getElementById('descricao').value.trim());

  const file = document.getElementById('foto_file').files[0];
  if (file) fd.append('foto_file', file);

  const r = await fetch(api, {
    method: 'POST',
    body: fd,
    credentials: 'same-origin'
  });

  const j = await r.json();
  if(!j.ok){ alert(j.error||'Erro'); return; }

  closeModal();
  await load();
}
load();
</script>
</body>
</html>
