<?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 • Usuários</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{ background:var(--input); color:var(--text); border:1px solid var(--line); border-radius:12px; padding:10px 12px; outline:none; }
    input::placeholder{ color:rgba(243,243,243,.45); }
    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); }
    button:hover{ filter:brightness(1.08); }
    table{ width:100%; border-collapse:collapse; }
    th,td{ padding:10px 12px; border-bottom:1px solid var(--line); font-size:14px; }
    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); }
    .muted{ color:var(--muted); }
    .danger{ color:var(--danger); }
    .modalBack{ position:fixed; inset:0; background:rgba(0,0,0,.6); display:none; align-items:center; justify-content:center; padding:16px; }
    .modal{ width:min(560px, 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:700; }
    .modal .bd{ padding:14px 16px; }
    .modal .ft{ padding:14px 16px; border-top:1px solid var(--line); display:flex; gap:10px; justify-content:flex-end; }
  </style>
</head>
<body>
  <div class="wrap">
    <div class="top">
      <div>
        <div style="font-size:18px;font-weight:800">Admin • Usuários</div>
        <div class="muted" style="font-size:13px">Criar/editar usuários do sistema</div>
      </div>
      <div class="row">
        <button class="primary" onclick="openUser()">+ Novo usuário</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/usuário..." style="flex:1; min-width:220px">
          <button onclick="load()">Buscar</button>
        </div>
        <div style="overflow:auto">
          <table>
            <thead>
              <tr>
                <th>ID</th>
                <th>Nome</th>
                <th>Usuário</th>
                <th>Role</th>
                <th>Status</th>
                <th style="width:240px">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">Usuário</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:220px">
          <input id="usuario" placeholder="Usuário (login)" style="flex:1; min-width:220px">
        </div>
        <div class="row" style="margin-bottom:10px">
          <select id="role" style="flex:1; min-width:220px">
            <option value="ADMIN">ADMIN</option>
            <option value="GARCOM">GARCOM</option>
            <option value="CAIXA">CAIXA</option>
            <option value="BALCAO">BALCAO</option>
          </select>

          <select id="ativo" style="flex:1; min-width:220px">
            <option value="1">Ativo</option>
            <option value="0">Inativo</option>
          </select>
        </div>
        <div class="row">
          <input id="senha" placeholder="Senha (deixe vazio para não alterar)" type="password" style="flex:1; min-width:220px">
        </div>
        <div class="muted" style="font-size:12px;margin-top:8px">
          Dica: para edição, senha em branco mantém a atual.
        </div>
      </div>
      <div class="ft">
        <button onclick="closeModal()">Cancelar</button>
        <button class="primary" onclick="save()">Salvar</button>
      </div>
    </div>
  </div>

<script>
const api = 'usuarios_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 openUser(u=null){
  document.getElementById('mb').style.display='flex';
  document.getElementById('mt').textContent = u ? 'Editar usuário' : 'Novo usuário';
  document.getElementById('id').value = u?.id ?? '';
  document.getElementById('nome').value = u?.nome ?? '';
  document.getElementById('usuario').value = u?.usuario ?? '';
  document.getElementById('role').value = u?.role ?? 'GARCOM';
  document.getElementById('ativo').value = String(u?.ativo ?? 1);
  document.getElementById('senha').value = '';
}
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="6" class="danger">${esc(j.error||'Erro')}</td></tr>`; return; }

  for (const u of j.users){
    const st = (u.ativo==1) ? `<span class="badge ok">ATIVO</span>` : `<span class="badge danger">INATIVO</span>`;
    tb.innerHTML += `
      <tr>
        <td>${esc(u.id)}</td>
        <td>${esc(u.nome)}</td>
        <td>${esc(u.usuario)}</td>
        <td>${esc(u.role)}</td>
        <td>${st}</td>
        <td>
          <button onclick='edit(${JSON.stringify(u)})'>Editar</button>
          <button onclick='resetPwd(${esc(u.id)})'>Reset senha</button>
        </td>
      </tr>
    `;
  }
}

function edit(u){ openUser(u); }

async function save(){
  const payload = {
    action:'save',
    id: document.getElementById('id').value,
    nome: document.getElementById('nome').value.trim(),
    usuario: document.getElementById('usuario').value.trim(),
    role: document.getElementById('role').value,
    ativo: Number(document.getElementById('ativo').value),
    senha: document.getElementById('senha').value
  };
  const j = await jpost(payload);
  if(!j.ok){ alert(j.error||'Erro'); return; }
  closeModal();
  await load();
}

async function resetPwd(id){
  const senha = prompt("Nova senha para o usuário ID " + id + ":");
  if(!senha) return;
  const j = await jpost({action:'reset_pwd', id:Number(id), senha});
  if(!j.ok){ alert(j.error||'Erro'); return; }
  alert('Senha atualizada.');
}

load();
</script>
</body>
</html>
