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

if (!defined('BASE')) define('BASE', '/arapiraca');

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

/** Caminho da logomarca (ajuste se necessário) */
$LOGO = BASE . '/assets/logo1.png';

/* Sessões + status de ata */
$sessoes = $pdo->query("
  SELECT
    s.*,
    a.id            AS ata_id,
    a.pdf_path      AS ata_pdf_path,
    a.texto_html    AS ata_html,
    a.publicar_site AS ata_publicar
  FROM sessoes s
  LEFT JOIN atas a ON a.sessao_id = s.id
  ORDER BY s.data_sessao DESC, s.id DESC
")->fetchAll();

/* Resumos */
$total = $ativas = $preparacao = $encerradas = 0;
$total = count($sessoes);
foreach ($sessoes as $s) {
  if ($s['status'] === 'ativa') $ativas++;
  elseif ($s['status'] === 'encerrada') $encerradas++;
  else $preparacao++;
}
?>
<!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>Arapiraca - Legislativo</title>
  <link rel="stylesheet" href="<?= BASE ?>/assets/style.css">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
  <style>
    *,
    *::before,
    *::after {
      box-sizing: border-box
    }

    :root {
      --primary: #4f7be8;
      --primary-2: #3a6ddf;
      --success: #16a34a;
      --danger: #ef4444;
      --danger-2: #dc2626;
      --amber: #f59e0b;

      --gray-50: #f3f6fb;
      --gray-100: #e9eef6;
      --gray-200: #d9dee7;
      --gray-300: #c9cfd9;
      --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);
    }

    body {
      margin: 0;
      color: var(--gray-900);
      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;
      overflow-x: hidden;
    }

    /* ===== Header ===== */
    .header {
      background: rgba(255, 255, 255, .92);
      backdrop-filter: blur(10px);
      border-bottom: 1px solid var(--gray-200);
      box-shadow: var(--shadow-sm);
      position: sticky;
      top: 0;
      z-index: 30;
    }

    .header-content {
      max-width: 1200px;
      margin: 0 auto;
      padding: 10px 14px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      flex-wrap: nowrap;
    }

    .brand {
      display: flex;
      align-items: center;
      gap: 10px;
      font-weight: 800;
      font-size: 1.1rem;
      color: #1f2937;
    }

    .brand img {
      height: 48px;
      width: auto;
      object-fit: contain;
      display: block
    }

    .brand span {
      white-space: nowrap
    }

    .menu-btn {
      display: none;
      align-items: center;
      gap: 8px;
      padding: 10px 12px;
      border-radius: 12px;
      border: 2px solid var(--gray-200);
      background: #fff;
      color: #1f2a44;
      font-weight: 800;
      box-shadow: var(--shadow-sm);
      cursor: pointer;
    }

    .menu-btn i {
      font-size: 1.05rem
    }

    .header-actions {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
      align-items: center
    }

    .btn {
      --btn-bg: #fff;
      --btn-fg: #1f2a44;
      --btn-bd: var(--gray-200);
      display: inline-flex;
      align-items: center;
      gap: 8px;
      text-decoration: none;
      background: var(--btn-bg);
      color: var(--btn-fg);
      border: 2px solid var(--btn-bd);
      border-radius: 12px;
      padding: 10px 14px;
      font-weight: 800;
      cursor: pointer;
      box-shadow: var(--shadow-sm);
      transition: .15s;
    }

    .btn:hover {
      transform: translateY(-1px);
      filter: brightness(.98)
    }

    .btn.small {
      padding: .45rem .7rem;
      font-size: .88rem
    }

    .btn-primary {
      --btn-bg: var(--primary);
      --btn-fg: #fff;
      --btn-bd: var(--primary);
      box-shadow: 0 8px 18px rgba(79, 123, 232, .18);
    }

    .btn-primary:hover {
      background: var(--primary-2);
      border-color: var(--primary-2);
    }

    .btn-success {
      --btn-bg: var(--success);
      --btn-fg: #fff;
      --btn-bd: var(--success);
    }

    .btn-danger {
      --btn-bg: var(--danger);
      --btn-fg: #fff;
      --btn-bd: var(--danger);
    }

    .btn-warning {
      --btn-bg: var(--amber);
      --btn-fg: #fff;
      --btn-bd: var(--amber);
    }

    .btn-secondary {
      --btn-bg: #fff;
      --btn-fg: #1f2a44;
      --btn-bd: var(--gray-200);
    }

    .btn-secondary:hover {
      background: #f8fafc;
    }

    .btn-outline-primary {
      --btn-bg: #fff;
      --btn-fg: var(--primary-2);
      --btn-bd: var(--primary-2);
    }

    .btn-outline-primary:hover {
      background: #eff3ff;
    }

    /* ===== Drawer (mobile) ===== */
    .drawer {
      position: fixed;
      inset: 0;
      display: none;
      z-index: 40;
    }

    .drawer.open {
      display: block;
    }

    .drawer .overlay {
      position: absolute;
      inset: 0;
      background: rgba(15, 23, 42, .45);
    }

    .drawer .panel {
      position: absolute;
      right: 0;
      top: 0;
      height: 100%;
      width: min(86vw, 380px);
      background: #fff;
      border-left: 1px solid var(--gray-200);
      box-shadow: var(--shadow-lg);
      transform: translateX(100%);
      transition: transform .22s ease-in-out;
      display: flex;
      flex-direction: column;
    }

    .drawer.open .panel {
      transform: translateX(0);
    }

    .drawer .phd {
      padding: 12px 14px;
      border-bottom: 1px solid var(--gray-200);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .drawer .pbd {
      padding: 14px;
      overflow: auto;
    }

    .drawer .close {
      background: #fff;
      border: 2px solid var(--gray-200);
      border-radius: 10px;
      padding: 6px 10px;
      cursor: pointer;
      font-weight: 800;
    }

    .drawer .stack {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .drawer .stack .btn {
      width: 100%;
      justify-content: flex-start;
    }

    /* ===== Main ===== */
    .main {
      max-width: 1200px;
      margin: 18px auto;
      padding: 0 14px;
    }

    .grid-resumo {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
      gap: 14px;
      margin-bottom: 16px;
    }

    .card {
      background: #fff;
      border: 1px solid var(--gray-200);
      border-radius: 16px;
      padding: 16px;
      box-shadow: var(--shadow-lg);
      position: relative;
      overflow: hidden;
    }

    .card h4 {
      margin: 0 0 6px;
      color: #1f2937;
      font-size: .95rem;
    }

    .card .big {
      font-size: 1.6rem;
      font-weight: 900;
    }

    .muted {
      color: #596377;
      font-size: .9rem;
    }

    .kpi {
      border: 0;
      color: #0f172a;
    }

    .kpi .icon {
      position: absolute;
      right: 14px;
      top: 12px;
      font-size: 1.35rem;
      opacity: .22;
      color: #0f172a;
    }

    .kpi.total {
      background: linear-gradient(135deg, #c9d9ff 0%, #9ec0ff 100%);
    }

    .kpi.prep {
      background: linear-gradient(135deg, #d8ceff 0%, #bdb8ff 100%);
    }

    .kpi.ativa {
      background: linear-gradient(135deg, #b3f0ce 0%, #7ee6a7 100%);
    }

    .kpi.enc {
      background: linear-gradient(135deg, #ffc8cf 0%, #f8a4b0 100%);
    }

    .filters {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
      margin: 6px 0 16px;
    }

    .input,
    .select {
      background: #fff;
      border: 2px solid var(--gray-200);
      border-radius: 12px;
      padding: 10px 12px;
      min-width: 220px;
      outline: 0;
      transition: .2s;
      box-shadow: var(--shadow-sm);
      color: #1b2230;
    }

    .input:focus,
    .select:focus {
      border-color: #7aa2f7;
      box-shadow: 0 0 0 3px rgba(122, 162, 247, .35);
    }

    .table-wrap {
      background: #fff;
      border: 1px solid var(--gray-200);
      border-radius: 16px;
      overflow: hidden;
      box-shadow: var(--shadow-lg);
    }

    table {
      width: 100%;
      border-collapse: collapse;
    }

    thead th {
      text-align: left;
      background: linear-gradient(180deg, #f1f4f9, #e6ebf3);
      color: #2f3a4a;
      padding: 12px;
      font-size: .9rem;
      border-bottom: 1px solid var(--gray-200);
    }

    tbody td {
      padding: 12px;
      border-bottom: 1px solid var(--gray-200);
    }

    tbody tr:hover {
      background: #eef3ff;
    }

    .actions {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
    }

    .badge {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: .28rem .65rem;
      border-radius: 999px;
      font-weight: 800;
      font-size: .78rem;
      border: 1px solid var(--gray-300);
      color: #2f3a4a;
      background: #fff;
    }

    .b-ativa {
      background: #c9f3d7;
      color: #065f46;
      border-color: #9feab8;
    }

    .b-encerrada {
      background: #ffd5da;
      color: #931a2f;
      border-color: #ffc0c9;
    }

    .b-prep {
      background: #e2e6ff;
      color: #2b2fa3;
      border-color: #c2c9ff;
    }

    .b-pub {
      background: #dcfce7;
      color: #166534;
      border-color: #a7f3d0;
    }

    .b-draft {
      background: #fff7ed;
      color: #9a3412;
      border-color: #fed7aa;
    }

    .b-none {
      background: #f1f5f9;
      color: #334155;
      border-color: #cbd5e1;
    }

    .table-container {
      overflow-x: auto;
    }

    /* ===== Responsive ===== */
    @media (max-width: 980px) {
      .brand img {
        height: 42px
      }

      .header-actions {
        display: none;
      }

      /* escondemos ações na barra */
      .menu-btn {
        display: inline-flex;
      }

      /* mostramos sanduíche */
    }

    @media (max-width: 700px) {
      thead {
        display: none;
      }

      table,
      tbody,
      tr,
      td {
        display: block;
        width: 100%;
      }

      tbody tr {
        border-bottom: 1px solid var(--gray-200);
        padding: 8px 12px;
      }

      tbody td {
        border: 0;
        padding: 6px 0;
      }

      tbody td[data-label]::before {
        content: attr(data-label) ": ";
        font-weight: 700;
        color: #475569;
      }

      .actions {
        margin-top: 8px;
      }
    }

    @media (max-width:480px) {
      .brand img {
        height: 36px
      }

      .brand span {
        font-size: 1rem
      }

      .main {
        padding: 0 12px
      }
    }
  </style>
</head>

<body>

  <!-- HEADER -->
  <div class="header">
    <div class="header-content">
      <div class="brand">
        <img src="<?= htmlspecialchars($LOGO, ENT_QUOTES) ?>" alt="Logo" onerror="this.style.display='none'">
        <span></span>
      </div>

      <!-- Botão Sanduíche (mobile) -->
      <button class="menu-btn" id="openMenu" aria-label="Abrir menu">
        <i class="fa-solid fa-bars"></i> Menu
      </button>

      <!-- Ações (desktop) -->
      <div class="header-actions" id="headerActions">
        <a class="btn btn-secondary" href="<?= BASE ?>/admin_usuarios.php"><i class="fas fa-users"></i> Usuários</a>
        <a class="btn btn-primary" href="<?= BASE ?>/admin_sessao_nova.php"><i class="fas fa-calendar-plus"></i> Sessão</a>
        <a class="btn btn-primary" href="<?= BASE ?>/admin_legislatura.php"><i class="fas fa-landmark"></i> Legislatura</a>
        <a class="btn btn-primary" href="<?= BASE ?>/admin_comissao.php"><i class="fas fa-people-group"></i> Comissão</a>
        <a class="btn btn-primary" href="<?= BASE ?>/admin_legislacao.php"><i class="fas fa-scale-balanced"></i> Legislação</a>
        <a class="btn btn-primary" href="<?= BASE ?>/admin_materias.php"><i class="fas fa-file-lines"></i> Matérias</a>
        <a class="btn btn-primary" href="<?= BASE ?>/admin_atas.php"><i class="fas fa-book-open"></i> Atas</a>
        <form action="/arapiraca/actions.php?op=logout" method="post" style="display:inline;">
          <button type="submit" class="btn btn-outline-danger btn-sm">
            Sair
          </button>
        </form>

      </div>
    </div>
  </div>

  <!-- DRAWER MOBILE -->
  <div class="drawer" id="drawer" aria-hidden="true">
    <div class="overlay" data-close></div>
    <div class="panel" role="dialog" aria-modal="true" aria-labelledby="menuTitle">
      <div class="phd">
        <strong id="menuTitle">Menu</strong>
        <button class="close" type="button" data-close><i class="fa-solid fa-xmark"></i> Fechar</button>
      </div>
      <div class="pbd">
        <div class="stack" id="drawerContent"><!-- ações copiadas via JS --></div>
      </div>
    </div>
  </div>

  <div class="main">

    <!-- CARDS RESUMO -->
    <div class="grid-resumo">
      <div class="card kpi total">
        <div class="icon"><i class="fa-solid fa-layer-group"></i></div>
        <h4>Total de sessões</h4>
        <div class="big"><?= $total ?></div>
        <div class="muted">Todas as sessões cadastradas</div>
      </div>
      <div class="card kpi prep">
        <div class="icon"><i class="fa-solid fa-wand-magic-sparkles"></i></div>
        <h4>Em preparação</h4>
        <div class="big"><?= $preparacao ?></div>
        <div class="muted">Status “preparação”</div>
      </div>
      <div class="card kpi ativa">
        <div class="icon"><i class="fa-solid fa-play"></i></div>
        <h4>Ativas</h4>
        <div class="big"><?= $ativas ?></div>
        <div class="muted">Sessões em andamento</div>
      </div>
      <div class="card kpi enc">
        <div class="icon"><i class="fa-solid fa-flag-checkered"></i></div>
        <h4>Encerradas</h4>
        <div class="big"><?= $encerradas ?></div>
        <div class="muted">Sessões concluídas</div>
      </div>
    </div>

    <!-- FILTROS -->
    <div class="card" style="margin-bottom:14px;">
      <div class="filters">
        <input id="q" class="input" type="search" placeholder="Buscar por número, tipo ou data…">
        <select id="status" class="select">
          <option value="">Todos os status</option>
          <option value="preparacao">Preparação</option>
          <option value="ativa">Ativa</option>
          <option value="encerrada">Encerrada</option>
        </select>
        <button class="btn btn-secondary" id="clear"><i class="fas fa-eraser"></i> Limpar</button>
      </div>
    </div>

    <!-- TABELA -->
    <div class="table-wrap">
      <?php if (!$sessoes): ?>
        <div style="padding:18px" class="muted">Nenhuma sessão cadastrada.</div>
      <?php else: ?>
        <div class="table-container">
          <table id="tbl">
            <thead>
              <tr>
                <th style="width:110px">Número</th>
                <th>Tipo</th>
                <th style="width:140px">Data</th>
                <th style="width:140px">Status</th>
                <th style="width:180px">Ata</th>
                <th style="width:520px">Ações</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($sessoes as $s):
                $st = $s['status'];
                $badgeClass = $st === 'ativa' ? 'b-ativa' : ($st === 'encerrada' ? 'b-encerrada' : 'b-prep');
                $badgeText  = $st === 'ativa' ? 'Ativa' : ($st === 'encerrada' ? 'Encerrada' : 'Preparação');

                $temAta     = !empty($s['ata_id']);
                $pubFlag    = (int)($s['ata_publicar'] ?? 0) === 1;
                $linkPublic = null;
                if ($temAta) {
                  if (!empty($s['ata_pdf_path'])) {
                    $linkPublic = BASE . '/' . ltrim($s['ata_pdf_path'], '/');
                  } elseif (!empty($s['ata_html'])) {
                    $linkPublic = BASE . '/publico/ata_view.php?id=' . $s['ata_id'];
                  }
                }
                $ataBadgeClass = $temAta ? ($pubFlag ? 'b-pub' : 'b-draft') : 'b-none';
                $ataBadgeText  = $temAta ? ($pubFlag ? 'Publicado' : 'Rascunho') : 'Sem ata';
              ?>
                <tr
                  data-status="<?= h($s['status']) ?>"
                  data-busca="<?= strtolower(h($s['numero'] . ' ' . $s['tipo'] . ' ' . $s['data_sessao'])) ?>">
                  <td data-label="Número"><strong><?= h($s['numero']) ?></strong></td>
                  <td data-label="Tipo"><?= h($s['tipo']) ?></td>
                  <td data-label="Data"><?= h($s['data_sessao']) ?></td>
                  <td data-label="Status"><span class="badge <?= $badgeClass ?>"><i class="fas fa-circle"></i> <?= $badgeText ?></span></td>
                  <td data-label="Ata"><span class="badge <?= $ataBadgeClass ?>"><i class="fas fa-file"></i> <?= $ataBadgeText ?></span></td>
                  <td data-label="Ações">
                    <div class="actions">
                      <a class="btn btn-outline-primary" href="<?= BASE ?>/admin_sessao_nova.php?id=<?= $s['id'] ?>"><i class="fas fa-pen"></i> Editar</a>
                      <a class="btn btn-primary" href="<?= BASE ?>/admin_materia_nova.php?sessao=<?= $s['id'] ?>"><i class="fas fa-list-ul"></i> Matérias</a>
                      <a class="btn btn-warning" href="<?= BASE ?>/actions.php?op=atas_gerar_html&amp;sessao=<?= $s['id'] ?>">
                        <i class="fas fa-print"></i> Gerar (salvar)
                      </a>
                      <?php if ($temAta): ?>
                        <?php if ($pubFlag): ?>
                          <a class="btn btn-secondary" href="<?= BASE ?>/actions.php?op=atas_publicar&amp;sessao=<?= $s['id'] ?>&amp;flag=0">
                            <i class="fas fa-eye-slash"></i> Despublicar
                          </a>
                        <?php else: ?>
                          <a class="btn btn-secondary" href="<?= BASE ?>/actions.php?op=atas_publicar&amp;sessao=<?= $s['id'] ?>&amp;flag=1">
                            <i class="fas fa-eye"></i> Publicar
                          </a>
                        <?php endif; ?>
                      <?php endif; ?>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>
  </div>

  <script>
    // Copia ações do header para o drawer mobile e faz o toggle
    (function() {
      const drawer = document.getElementById('drawer');
      const panel = drawer.querySelector('.panel');
      const overlay = drawer.querySelector('.overlay');
      const openBtn = document.getElementById('openMenu');
      const content = document.getElementById('drawerContent');
      const src = document.getElementById('headerActions');

      if (src && content) {
        content.innerHTML = src.innerHTML; // clona ações
      }

      const closeEls = drawer.querySelectorAll('[data-close], .overlay');

      function open() {
        drawer.classList.add('open');
        drawer.setAttribute('aria-hidden', 'false');
        document.body.style.overflow = 'hidden';
      }

      function close() {
        drawer.classList.remove('open');
        drawer.setAttribute('aria-hidden', 'true');
        document.body.style.overflow = '';
      }

      openBtn?.addEventListener('click', open);
      closeEls.forEach(el => el.addEventListener('click', close));
      document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && drawer.classList.contains('open')) close();
      });
      panel.addEventListener('click', (e) => e.stopPropagation());
      overlay.addEventListener('click', close);
    })();

    // Filtro rápido por texto e status
    (function() {
      const q = document.getElementById('q');
      const status = document.getElementById('status');
      const clearBtn = document.getElementById('clear');
      const rows = Array.from(document.querySelectorAll('#tbl tbody tr'));

      function apply() {
        const txt = (q.value || '').trim().toLowerCase();
        const st = (status.value || '').trim();
        rows.forEach(tr => {
          const m1 = !txt || (tr.getAttribute('data-busca') || '').includes(txt);
          const m2 = !st || (tr.getAttribute('data-status') === st);
          tr.style.display = (m1 && m2) ? '' : 'none';
        });
      }
      q.addEventListener('input', apply);
      status.addEventListener('change', apply);
      clearBtn.addEventListener('click', () => {
        q.value = '';
        status.value = '';
        apply();
      });
    })();
  </script>
</body>

</html>