<?php
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/helpers.php';

require_login();
if (($_SESSION['tipo'] ?? '') !== 'operador') {
  header('Location:/arapiraca/vereador.php'); exit;
}

/* ==== filtros ==== */
$q      = trim($_GET['q'] ?? '');
$tipo   = $_GET['tipo']   ?? 'todos';   // todos | vereador | operador
$status = $_GET['status'] ?? 'todos';   // todos | ativos | inativos

$w = [];
$p = [];
if ($tipo === 'vereador' || $tipo === 'operador') { $w[] = "tipo_usuario = :tipo"; $p[':tipo'] = $tipo; }
if ($status === 'ativos')   { $w[] = "ativo = 1"; }
if ($status === 'inativos') { $w[] = "ativo = 0"; }
if ($q !== '') {
  $w[] = "(nome LIKE :q OR email LIKE :q OR partido LIKE :q)";
  $p[':q'] = "%{$q}%";
}
$whereSql = $w ? ('WHERE '.implode(' AND ', $w)) : '';

/* ==== dados ==== */
$sql = "
  SELECT id, nome, email, tipo_usuario, partido, ativo, foto, COALESCE(eh_presidente,0) AS eh_presidente
  FROM usuarios
  $whereSql
  ORDER BY nome ASC
";
$st = $pdo->prepare($sql);
$st->execute($p);
$usuarios = $st->fetchAll();

/* ==== cards ==== */
$total            = (int)$pdo->query("SELECT COUNT(*) FROM usuarios")->fetchColumn();
$vereadoresAtivos = (int)$pdo->query("SELECT COUNT(*) FROM usuarios WHERE tipo_usuario='vereador' AND ativo=1")->fetchColumn();
$operadores       = (int)$pdo->query("SELECT COUNT(*) FROM usuarios WHERE tipo_usuario='operador'")->fetchColumn();
$inativos         = (int)$pdo->query("SELECT COUNT(*) FROM usuarios WHERE ativo=0")->fetchColumn();

/* helper badge */
function badgeStatus($a){
  return $a ? '<span class="badge b-green">Ativo</span>' : '<span class="badge b-gray">Inativo</span>';
}
?>
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Admin • Usuários</title>
<link rel="stylesheet" href="/arapiraca/assets/style.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
<style>
  :root{
    /* paleta do admin (um pouco mais escura) */
    --primary:#4f7be8; --primary-2:#3a6ddf;
    --ok:#22c55e; --danger:#ef4444; --amber:#f59e0b;

    --gray-50:#f3f6fb; --gray-100:#e9eef6; --gray-200:#d9dee7; --gray-300:#c9cfd9;
    --gray-400:#9aa3b2; --gray-500:#5b6472; --gray-700:#2e3643; --gray-800:#1b2230; --gray-900:#121827;

    --shadow-sm:0 2px 8px rgba(18,24,39,.08);
    --shadow-md:0 12px 22px rgba(18,24,39,.10);
    --shadow-lg:0 22px 48px rgba(18,24,39,.12);
  }

  html,body{height:100%}
  body{
    font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen,Ubuntu,Cantarell,sans-serif;
    background:
      radial-gradient(820px 420px at -10% -10%, #e2e8ff 0 60%, transparent 61%),
      radial-gradient(960px 480px at 110% 0%, #ffd6dd 0 55%, transparent 56%),
      linear-gradient(180deg,#edf2f7 0%, #e7ecf4 100%);
    min-height:100vh;
    color:var(--gray-900);
  }

  /* Header vítreo */
  .header{
    background:rgba(255,255,255,.92); backdrop-filter:blur(10px);
    border-bottom:1px solid var(--gray-200); position:sticky; top:0; z-index:10; box-shadow:var(--shadow-sm);
  }
  .header-in{max-width:1200px;margin:0 auto;padding:12px 16px;display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}
  .title{font-weight:900;font-size:1.15rem;display:flex;align-items:center;gap:10px;color:#1f2937}
  .actions{display:flex;gap:8px;flex-wrap:wrap}

  .btn{
    display:inline-flex;align-items:center;gap:8px;padding:.65rem 1rem;border-radius:12px;
    font-weight:800;text-decoration:none;border:1px solid var(--gray-200);background:#fff;color:#223047;
    box-shadow:var(--shadow-sm); transition:.18s;
  }
  .btn:hover{transform:translateY(-1px); background:#f4f7fb;}
  .btn-primary{background:var(--primary);color:#fff;border-color:transparent}
  .btn-primary:hover{background:var(--primary-2); box-shadow:var(--shadow-md)}
  .btn-red{background:#fff;color:#b91c1c;border-color:#ffc9c9}
  .btn-red:hover{background:#ffe3e6}

  .container{max-width:1200px;margin:22px auto;padding:0 16px}

  /* cards-resumo coloridos */
  .cards{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:18px}
  @media (max-width:900px){.cards{grid-template-columns:repeat(2,1fr)}}
  @media (max-width:520px){.cards{grid-template-columns:1fr}}
  .kpi{
    position:relative; border:1px solid var(--gray-200); border-radius:16px; padding:16px 16px 14px;
    color:#111; overflow:hidden; box-shadow:var(--shadow-lg);
  }
  .kpi .ico{
    position:absolute; right:12px; top:10px; font-size:1.3rem; opacity:.25;
  }
  .kpi h4{margin:0 0 6px;font-size:.95rem;font-weight:800}
  .kpi .big{font-size:1.7rem;font-weight:900}
  .kpi .muted{color:var(--gray-500);font-size:.9rem}

  .kpi.total{ background:linear-gradient(135deg,#e8f0ff,#dde7ff); }
  .kpi.ver  { background:linear-gradient(135deg,#efe6ff,#e2d8ff); }
  .kpi.op   { background:linear-gradient(135deg,#e7faef,#d9f3e6); }
  .kpi.inat { background:linear-gradient(135deg,#ffe9ee,#ffd8e1); }

  /* filtros */
  .filters{
    background:#fff;border:1px solid var(--gray-200); border-radius:16px; padding:12px;
    box-shadow:var(--shadow-lg); margin-bottom:16px
  }
  .filters .row{display:grid;grid-template-columns:1fr 240px 240px 140px;gap:10px}
  @media(max-width:980px){.filters .row{grid-template-columns:1fr 1fr}}
  @media(max-width:520px){.filters .row{grid-template-columns:1fr}}
  .input{
    width:100%;border:2px solid var(--gray-200);border-radius:12px;padding:.7rem 1rem;font-size:1rem;background:#fff;
    transition:.15s
  }
  .input:hover{border-color:var(--gray-300)}
  .input:focus{outline:none;border-color:#7aa2f7;box-shadow:0 0 0 3px rgba(122,162,247,.35)}

  /* tabela */
  .table-wrap{border-radius:16px; overflow:hidden;}
  table{width:100%;border-collapse:separate;border-spacing:0;background:#fff;border:1px solid var(--gray-200);border-radius:16px;box-shadow:var(--shadow-lg)}
  thead th{background:linear-gradient(180deg,#f8fafc,#f1f5f9);text-align:left;padding:12px;border-bottom:1px solid var(--gray-200);font-size:.9rem;color:#2f3a4a}
  tbody td{padding:12px;border-bottom:1px solid var(--gray-200);vertical-align:middle}
  tbody tr:last-child td{border-bottom:0}
  tbody tr:hover{ background:#f9fbff; }
  .avatar{width:44px;height:44px;border-radius:999px;object-fit:cover;background:#e5e7eb}
  .name{font-weight:900}
  .badge{display:inline-block;padding:.25rem .6rem;border-radius:.65rem;font-weight:800;font-size:.78rem}
  .b-green{background:#c9f3d7;color:#065f46;border:1px solid #9feab8}
  .b-gray{background:#eef2f7;color:#374151;border:1px solid #dde3ec}
  .chip{display:inline-flex;align-items:center;gap:.4rem;padding:.25rem .6rem;border-radius:.65rem;font-weight:800;font-size:.78rem}
  .chip-pres{background:#fff1cc;border:1px solid #ffe08a;color:#8a5a00}
  .actions-td a{margin-right:8px}
  .nowrap{white-space:nowrap}
</style>
</head>
<body>

  <div class="header">
    <div class="header-in">
      <div class="title"><i class="fa-solid fa-users-gear"></i> Admin • Usuários</div>
      <div class="actions">
        <a class="btn" href="/arapiraca/painel.php" target="_blank"><i class="fa-solid fa-display"></i> Painel Público</a>
        <a class="btn" href="/arapiraca/admin.php"><i class="fa-solid fa-table-list"></i> Sessões</a>
        <a class="btn btn-primary" href="/arapiraca/admin_usuario_form.php"><i class="fa-solid fa-user-plus"></i> Novo Usuário</a>
        <a class="btn btn-red" href="/arapiraca/actions.php?op=logout"><i class="fa-solid fa-right-from-bracket"></i> Sair</a>
      </div>
    </div>
  </div>

  <div class="container">

    <!-- cards-resumo -->
    <div class="cards">
      <div class="kpi total">
        <i class="fa-solid fa-database ico"></i>
        <h4>Total de usuários</h4>
        <div class="big"><?= $total ?></div>
        <div class="muted">Todos os perfis cadastrados</div>
      </div>
      <div class="kpi ver">
        <i class="fa-solid fa-landmark-flag ico"></i>
        <h4>Vereadores ativos</h4>
        <div class="big"><?= $vereadoresAtivos ?></div>
        <div class="muted">Podem votar e pedir fala</div>
      </div>
      <div class="kpi op">
        <i class="fa-solid fa-user-gear ico"></i>
        <h4>Operadores</h4>
        <div class="big"><?= $operadores ?></div>
        <div class="muted">Gestão do sistema</div>
      </div>
      <div class="kpi inat">
        <i class="fa-solid fa-user-slash ico"></i>
        <h4>Inativos</h4>
        <div class="big"><?= $inativos ?></div>
        <div class="muted">Sem acesso</div>
      </div>
    </div>

    <!-- filtros -->
    <form class="filters" method="get">
      <div class="row">
        <input class="input" type="text" name="q" placeholder="Buscar por nome, e-mail ou partido…" value="<?= h($q) ?>">
        <select class="input" name="tipo">
          <option value="todos"   <?= $tipo==='todos'?'selected':'' ?>>Todos os tipos</option>
          <option value="vereador"<?= $tipo==='vereador'?'selected':'' ?>>Vereador</option>
          <option value="operador"<?= $tipo==='operador'?'selected':'' ?>>Operador</option>
        </select>
        <select class="input" name="status">
          <option value="todos"   <?= $status==='todos'?'selected':'' ?>>Todos os status</option>
          <option value="ativos"  <?= $status==='ativos'?'selected':'' ?>>Ativos</option>
          <option value="inativos"<?= $status==='inativos'?'selected':'' ?>>Inativos</option>
        </select>
        <button class="btn btn-primary nowrap" type="submit"><i class="fa-solid fa-magnifying-glass"></i> Filtrar</button>
      </div>
    </form>

    <!-- tabela -->
    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>Nome</th>
            <th>E-mail</th>
            <th>Tipo / Função</th>
            <th>Partido</th>
            <th>Status</th>
            <th class="nowrap">Ações</th>
          </tr>
        </thead>
        <tbody>
          <?php if(!$usuarios): ?>
            <tr><td colspan="6" class="muted" style="padding:18px">Nenhum usuário encontrado com os filtros atuais.</td></tr>
          <?php else: foreach($usuarios as $u): ?>
            <?php $foto = $u['foto'] ? '/arapiraca/'.ltrim($u['foto'],'/') : '/arapiraca/assets/avatar.png'; ?>
            <tr>
              <td>
                <div style="display:flex;align-items:center;gap:10px;">
                  <img class="avatar" src="<?= h($foto) ?>" onerror="this.src='/arapiraca/assets/avatar.png'">
                  <div class="name"><?= h($u['nome']) ?></div>
                </div>
              </td>
              <td><?= h($u['email']) ?></td>
              <td>
                <?= h($u['tipo_usuario']) ?>
                <?php if((int)$u['eh_presidente'] === 1): ?>
                  <span class="chip chip-pres"><i class="fa-solid fa-gavel"></i> Presidente</span>
                <?php endif; ?>
              </td>
              <td><?= h($u['partido'] ?: '—') ?></td>
              <td><?= badgeStatus((int)$u['ativo']===1) ?></td>
              <td class="actions-td nowrap">
                <a class="btn" href="/arapiraca/admin_usuario_form.php?id=<?= (int)$u['id'] ?>"><i class="fa-solid fa-pen-to-square"></i> Editar</a>
                <?php if((int)$u['ativo']===1): ?>
                  <a class="btn btn-red" href="/arapiraca/actions.php?op=usuario_toggle&id=<?= (int)$u['id'] ?>&to=0"><i class="fa-solid fa-user-slash"></i> Desativar</a>
                <?php else: ?>
                  <a class="btn btn-primary" href="/arapiraca/actions.php?op=usuario_toggle&id=<?= (int)$u['id'] ?>&to=1"><i class="fa-solid fa-user-check"></i> Ativar</a>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</body>
</html>
