<?php
// /arapiraca/publico/index.php
declare(strict_types=1);

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

// As dependências (db.php, helpers.php) são necessárias para o funcionamento completo.
// O código abaixo assume que elas existem e funcionam como no original.
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/helpers.php';

/* =======================================================================
   Helpers
   ======================================================================= */
if (!function_exists('h')) {
  function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}
function strp($k,$def=''){ return trim((string)($_GET[$k] ?? $def)); }
function nump($k,$def=0){ $n=(int)($_GET[$k] ?? 0); return $n?:$def; }
function ymd($d){
  if (!$d) return '';
  $ts = strtotime((string)$d);
  return $ts ? date('d/m/Y',$ts) : h($d);
}
function map_user_public(array $u): array {
  return [
    'id'      => (int)$u['id'],
    'nome'    => (string)$u['nome'],
    'partido' => $u['partido'] ?? null,
    'foto'    => !empty($u['foto']) ? (BASE.'/'.ltrim($u['foto'],'/')) : (BASE.'/assets/avatar.png'),
  ];
}
function table_exists(PDO $pdo, string $t): bool {
  try {
    $st = $pdo->prepare("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name=:t");
    $st->execute([':t'=>$t]); return (bool)$st->fetchColumn();
  } catch (Throwable $e) { return false; }
}
function column_exists(PDO $pdo, string $t, string $c): bool {
  try {
    $st = $pdo->prepare("SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name=:t AND column_name=:c");
    $st->execute([':t'=>$t,':c'=>$c]); return (bool)$st->fetchColumn();
  } catch (Throwable $e) { return false; }
}
function detect_quorum(PDO $pdo): ?array {
  static $det=null; if($det!==null) return $det;
  foreach (['sessoes_quorum','sessao_quorum','quorum','presencas','presenca_sessao'] as $t){
    if(!table_exists($pdo,$t)) continue;
    if (column_exists($pdo,$t,'sessao_id') && column_exists($pdo,$t,'vereador_id')){
      foreach(['presente','presenca','status'] as $c){
        if (column_exists($pdo,$t,$c)) return $det=['table'=>$t,'col'=>$c];
      }
    }
  }
  return $det=null;
}
function current_legislature(PDO $pdo): ?array {
  try {
    $st = $pdo->query("SELECT id,numero,periodo,data_inicio,data_fim,ativo FROM legislaturas WHERE ativo=1 ORDER BY data_inicio DESC, id DESC LIMIT 1");
    $row = $st->fetch();
    if ($row) return $row;
    $st = $pdo->query("SELECT id,numero,periodo,data_inicio,data_fim,ativo FROM legislaturas ORDER BY data_inicio DESC, id DESC LIMIT 1");
    return $st->fetch() ?: null;
  } catch (Throwable $e) { return null; }
}
function user_bio_col(PDO $pdo): ?string {
  foreach (['biografia','bio','descricao'] as $c) {
    if (column_exists($pdo,'usuarios',$c)) return $c;
  }
  return null;
}
function ata_link(int $sessao_id): ?string {
  try {
    global $pdo;
    if (table_exists($pdo,'atas')) {
      $q = $pdo->prepare("SELECT publicar_site FROM atas WHERE sessao_id=:s LIMIT 1");
      $q->execute([':s'=>$sessao_id]);
      $pub = $q->fetchColumn();
      if ((int)$pub === 1) return '?v=ata&sid='.$sessao_id;
    }
  } catch (Throwable $e) { /* ignora */ }
  $wrap = __DIR__ . '/ata_public.php';
  if (is_file($wrap)) return BASE . '/publico/ata_public.php?sessao=' . $sessao_id;
  $p1 = __DIR__ . '/ata.php';
  if (is_file($p1)) return BASE . '/publico/ata.php?sessao=' . $sessao_id . '&public=1';
  $p2 = dirname(__DIR__) . '/ata.php';
  if (is_file($p2)) return BASE . '/ata.php?sessao=' . $sessao_id . '&public=1';
  return null;
}

/* =======================================================================
   Layout + Logos (padrão visual)
   ======================================================================= */
function header_public(string $title='Atividades Legislativas'){
  $TOP_LOGO = BASE.'/assets/logo.png';
  ?>
  <!doctype html><html lang="pt-br"><head>
  <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
  <title><?=h($title)?></title>
  <link rel="stylesheet" href="<?=BASE?>/assets/style.css">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">
  <style>
    :root{
      --brand:#0b4da2; --brand-dark:#093d82;
      --bg:#f8fafc; --text:#0f172a; --muted:#65748b;
      --border:#e5e7eb; --card:#ffffff; --shadow:0 6px 18px rgba(2,6,23,.08 );
      --radius:16px; --btn:#0b4da2; --btn-hover:#093d82;
      --tile-red:#ef4444; --tile-blue:#2563eb; --tile-green:#10b981;
      --tile-orange:#f59e0b; --tile-cyan:#06b6d4; --tile-gray:#6b7280;
      --tile-dark:#111827; --tile-purple:#7c3aed;
    }
    html,body{background:var(--bg);color:var(--text);font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,Cantarell,sans-serif}
    a{color:inherit}
    .topbar{background:var(--brand);color:#fff;box-shadow:0 2px 6px rgba(2,6,23,.06)}
    .topbar .inner{max-width:1200px;margin:0 auto;padding:10px 16px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;box-sizing:border-box;position:relative}
    .top-logo img{height:44px;width:auto;object-fit:contain;display:block}
    .brand{font-weight:800;letter-spacing:.2px}
    .menu-btn{margin-left:auto;display:none;align-items:center;gap:8px;background:rgba(255,255,255,.14);color:#fff;border:0;border-radius:999px;padding:8px 12px;font-weight:800;cursor:pointer}
    .navwrap{flex:1 0 100%;display:flex;justify-content:center;align-items:center;background:transparent !important;border:0 !important;box-shadow:none !important;padding:0;margin-top:8px}
    .nav{display:flex;gap:8px;flex-wrap:wrap;justify-content:center;background:transparent !important;padding:0 !important}
    .nav .navlink{color:#fff !important;text-decoration:none;font-weight:800;display:flex;align-items:center;gap:8px;padding:8px 14px;border-radius:999px;background:rgba(255,255,255,.12) !important;border:1px solid rgba(255,255,255,.18) !important}
    .nav .navlink:hover{background:rgba(255,255,255,.22) !important}
    .nav .navlink.active{background:rgba(255,255,255,.28) !important;border-color:rgba(255,255,255,.35) !important}
    .wrap{max-width:1200px;margin:18px auto;padding:0 16px}

    /* ===== Cards – nova paleta ===== */
    .card{
      background:#ffffff;
      border:1px solid #cfe0ff; /* borda azul clarinha */
      border-radius: var(--radius);
      box-shadow: 0 10px 26px rgba(11,77,162,.10); /* sombra com tom da brand */
      overflow:hidden;
    }
    .card .hd{
      background: linear-gradient(135deg, #0b4da2, #093d82); /* topo no tom do menu */
      color:#ffffff;
      padding:12px 16px;
      font-weight:900;
      border-bottom:0;
      text-shadow: 0 1px 0 rgba(0,0,0,.12);
    }
    .card .bd{
      padding:16px;
      background: linear-gradient(180deg, #f7fbff, #ffffff); /* corpo levemente azulado */
    }
    /* Modificador para cards que precisam permanecer claros no topo */
    .card.card-plain .hd{
      background:#ffffff;
      color:var(--btn);
      border-bottom:1px solid var(--border);
      text-shadow:none;
    }
    .card.card-plain .bd{
      background:#ffffff;
    }

    .btn{display:inline-flex;align-items:center;gap:8px;padding:10px 16px;border-radius:12px;background:var(--btn);color:#fff;font-weight:800;text-decoration:none;border:0}
    .btn:hover{background:var(--btn-hover)}
    .btn.flat{background:#fff;color:var(--btn);border:2px solid var(--btn)}
    .muted{color:var(--muted)}
    .table-wrap{overflow-x:auto}
    table{width:100%;border-collapse:collapse}
    thead th{background:#eef2ff;color:#0b2b64;text-align:left;border-bottom:1px solid var(--border);padding:10px}
    tbody td{border-bottom:1px solid var(--border);padding:10px;vertical-align:top}
    .badge{display:inline-block;background:#eaf0ff;color:#0b2b64;padding:.25rem .6rem;border-radius:999px;font-weight:800;font-size:.8rem}
    .avatar{width:56px;height:56px;border-radius:999px;object-fit:cover;border:1px solid var(--border);background:#eee}
    .pill{display:inline-block;padding:.22rem .55rem;border-radius:999px;background:#edf2f7}
    .access{margin:10px 0 18px;text-align:center}
    .access h2{font-size:2rem;margin:8px 0 4px;font-weight:900}
    .access p{color:var(--muted);margin:0 0 14px}
    .tiles{display:grid;grid-template-columns:repeat(4,1fr);gap:18px}
    @media (max-width:1100px){.tiles{grid-template-columns:repeat(3,1fr)}}
    @media (max-width:900px){.tiles{grid-template-columns:repeat(2,1fr)}}
    @media (max-width:580px){.tiles{grid-template-columns:1fr}}
    .tile{display:block;text-decoration:none;color:#fff;border-radius:18px;box-shadow:var(--shadow);padding:26px 16px;min-height:150px;position:relative;overflow:hidden;transition:transform .12s ease,box-shadow .12s ease}
    .tile:hover{transform:translateY(-2px)}
    .tile .icon{font-size:40px;line-height:1;margin-bottom:14px;opacity:.95}
    .tile .t{font-weight:900;margin:0 0 6px}
    .tile .s{opacity:.95}
    .red{background:var(--tile-red)}.blue{background:var(--tile-blue)}.green{background:var(--tile-green)}.orange{background:var(--tile-orange)}.cyan{background:var(--tile-cyan)}.gray{background:var(--tile-gray)}.dark{background:var(--tile-dark)}.purple{background:var(--tile-purple)}
    .vereador-grid{display:grid;grid-template-columns:320px 1fr;gap:18px;align-items:start}
    @media (max-width:900px){.vereador-grid{grid-template-columns:1fr}}
    .foto-card{border:1px solid var(--border);border-radius:18px;overflow:hidden;box-shadow:var(--shadow);background:#fff}
    .foto-card img{width:100%;height:auto;display:block}
    .foto-legenda{background:#0b4da2;color:#fff;padding:10px 12px;font-weight:900;display:flex;justify-content:space-between;align-items:center}
    .tabs{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px}
    .tab-btn{background:#fff;color:var(--btn);border:2px solid var(--btn);padding:8px 12px;border-radius:999px;font-weight:800;cursor:pointer}
    .tab-btn.active{background:var(--btn);color:#fff}
    .tab-pane{display:none}
    .tab-pane.active{display:block}
    footer.site{margin-top:28px;color:#c7d2fe;background:var(--brand)}
    .foot-wrap{max-width:1200px;margin:0 auto;padding:28px 16px 18px}
    .fgrid{display:grid;grid-template-columns:2fr 1.5fr 1.5fr;gap:22px}
    .fbrand{display:flex;gap:12px;align-items:center}
    .fbrand .logo img{height:48px;width:auto;object-fit:contain;display:block}
    .fcol h4{margin:0 0 10px;color:#fff}
    .fcol a{display:block;color:#c7d2fe;text-decoration:none;margin:6px 0}
    .fcol a:hover{text-decoration:underline}
    .fsmall{border-top:1px solid rgba(255,255,255,.08);margin-top:18px;padding:12px 0;text-align:center;color:#aab6ee;font-size:.9rem}
    .social{display:flex;gap:10px;margin-top:8px}
    .social a{display:inline-flex;width:34px;height:34px;border-radius:999px;align-items:center;justify-content:center;background:#1b3570;color:#fff;text-decoration:none}
    @media (max-width:900px){.fgrid{grid-template-columns:1fr}}

    /* ===================================================================
       MENU MOBILE: BONITO E ORGANIZADO
       =================================================================== */
    @media (max-width: 1024px){
      .brand { flex: 1; }
      .menu-btn { display: inline-flex; }
      .navwrap {
        display: block;
        position: absolute;
        top: calc(100% + 5px);
        right: 16px;
        width: 280px;
        background: #fff !important;
        border-radius: var(--radius);
        box-shadow: 0 8px 24px rgba(2,6,23,.15);
        border: 1px solid var(--border);
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.3s ease-out;
        flex: none;
        margin-top: 0;
        z-index: 100;
      }
      .navwrap.show { max-height: 500px; }
      .nav {
        flex-direction: column;
        align-items: stretch;
        gap: 4px;
        padding: 8px !important;
      }
      .nav .navlink {
        color: var(--text) !important;
        background: transparent !important;
        border: none !important;
        border-radius: 8px;
        padding: 10px 12px;
        justify-content: flex-start;
      }
      .nav .navlink:hover { background: #f1f5f9 !important; }
      .nav .navlink.active {
        background: var(--brand) !important;
        color: #fff !important;
      }
    }
  </style>
  </head><body>

  <div class="topbar">
    <div class="inner">
      <a href="?v=home" class="top-logo"><img src="<?=$TOP_LOGO?>" alt="Logo da Câmara"></a>
      <div class="brand">Câmara Municipal de Arapiraca</div>
      <button class="menu-btn" id="menuBtn" aria-expanded="false"><i class="fa fa-bars"></i> Menu</button>

      <?php
        $v = trim((string)($_GET['v'] ?? 'home'));
        $links = [
          ['home','Início','fa-house'],
          ['vereadores','Vereadores','fa-user-group'],
          ['sessoes','Sessões','fa-gavel'],
          ['propostas','Propostas Legislativas','fa-folder-open'],
          ['presenca','Presença','fa-user-check'],
          ['comissoes','Comissões','fa-people-group'],
          ['legislacao','Legislação','fa-scale-balanced'],
          ['atas','Atas','fa-file-lines'],
        ];
      ?>
      <div class="navwrap" id="navwrap">
        <nav class="nav" aria-label="Navegação principal">
          <?php foreach($links as $it): ?>
            <a class="navlink <?=$v===$it[0]?'active':''?>" href="?v=<?=$it[0]?>"><i class="fa <?=$it[2]?>"></i> <?=$it[1]?></a>
          <?php endforeach; ?>
        </nav>
      </div>
    </div>
  </div>

  <script>
    // Script para o menu mobile
    (function(){
      const btn=document.getElementById('menuBtn');
      const nav=document.getElementById('navwrap');
      if(!btn||!nav) return;

      // Abre/fecha o menu ao clicar no botão
      btn.addEventListener('click', (e)=>{
        e.stopPropagation(); // Impede que o clique feche o menu imediatamente
        const open=nav.classList.toggle('show');
        btn.setAttribute('aria-expanded', open ? 'true' : 'false');
      });

      // Fecha o menu se clicar fora dele
      document.addEventListener('click', (e)=>{
        if (!nav.contains(e.target) && !btn.contains(e.target)) {
          if (nav.classList.contains('show')) {
            nav.classList.remove('show');
            btn.setAttribute('aria-expanded', 'false');
          }
        }
      });
    })();
  </script>

  <main class="wrap">
  <?php
}
function footer_public(){
  $FOOTER_LOGO = BASE.'/assets/logo.png';
  ?>
  </main>

  <footer class="site">
    <div class="foot-wrap">
      <div class="fgrid">
        <div class="fcol">
          <div class="fbrand">
            <div class="logo"><img src="<?=$FOOTER_LOGO?>" alt="Logomarca"></div>
            <div>
              <div class="name">Câmara Municipal de Arapiraca</div>
              <div>Portal de Atividades Legislativas</div>
            </div>
          </div>
          <div style="margin-top:10px;max-width:520px;color:#cbd5ff">
            Acompanhe proposições, sessões, presenças, comissões e legislação municipal de forma simples e transparente.
          </div>
          <div class="social">
            <a href="#" aria-label="Facebook"><i class="fa-brands fa-facebook-f"></i></a>
            <a href="#" aria-label="Instagram"><i class="fa-brands fa-instagram"></i></a>
            <a href="#" aria-label="YouTube"><i class="fa-brands fa-youtube"></i></a>
          </div>
        </div>

        <div class="fcol">
          <h4>Contatos</h4>
          <div>  Praça Luiz Pereira Lima, s/n — Arapiraca/AL</div>
          <div> (82) 0000-0000</div>
          <div> <a href="mailto:atendimento@arapiraca.al.leg.br">atendimento@arapiraca.al.leg.br</a></div>
          <div style="margin-top:8px"> Seg–Sex, 8h às 14h</div>
        </div>

        <div class="fcol">
          <h4>Acesso rápido</h4>
          <a href="?v=vereadores"><i class="fa fa-user-group"></i> Vereadores</a>
          <a href="?v=sessoes"><i class="fa fa-gavel"></i> Sessões</a>
          <a href="?v=propostas"><i class="fa fa-folder-open"></i> Propostas</a>
          <a href="?v=presenca"><i class="fa fa-user-check"></i> Presença</a>
          <a href="?v=legislacao"><i class="fa fa-scale-balanced"></i> Legislação</a>
          <a href="?v=atas"><i class="fa fa-file-lines"></i> Atas</a>
        </div>
      </div>

      <div class="fsmall">© <?=date('Y')?> Câmara Municipal de Arapiraca — Todos os direitos reservados</div>
    </div>
  </footer>
  </body></html>
  <?php
}

/* =======================================================================
   Router
   ======================================================================= */
$view = strp('v','home');
$id   = nump('id',0);

try {

/* -----------------------------------------------------------------------
   HOME — atalhos
   ----------------------------------------------------------------------- */
if ($view==='home') {
  $L = current_legislature($pdo);

  header_public('Início'); ?>
  <section class="access">
    <h2>Acesso Rápido</h2>
    <p>Navegue facilmente pelos principais serviços e informações da Câmara</p>

    <div class="tiles">
      <a class="tile red"    href="?v=sessoes"><div class="icon"><i class="fa-solid fa-gavel"></i></div><div class="t">Sessões</div><div class="s">Pautas e atas</div></a>
      <a class="tile blue"   href="?v=legislacao"><div class="icon"><i class="fa-solid fa-scale-balanced"></i></div><div class="t">Legislação</div><div class="s">Leis Municipais</div></a>
      <a class="tile green"  href="?v=propostas"><div class="icon"><i class="fa-solid fa-file-pen"></i></div><div class="t">Propostas</div><div class="s">Matéria legislativa</div></a>
      <a class="tile orange" href="?v=presenca"><div class="icon"><i class="fa-solid fa-user-check"></i></div><div class="t">Quórum</div><div class="s">Presenças em plenário</div></a>

      <a class="tile cyan"   href="?v=atas"><div class="icon"><i class="fa-solid fa-file-lines"></i></div><div class="t">Atas</div><div class="s">Relatórios públicos</div></a>
      <a class="tile gray"   href="?v=vereadores"><div class="icon"><i class="fa-solid fa-user-group"></i></div><div class="t">Vereadores</div><div class="s">Conheça cada gabinete</div></a>
      <a class="tile dark"   href="?v=mesa"><div class="icon"><i class="fa-solid fa-users-rectangle"></i></div><div class="t">Mesa Diretora</div><div class="s">Legislatura <?= $L ? h($L['periodo']) : '' ?></div></a>
      <a class="tile purple" href="?v=comissoes"><div class="icon"><i class="fa-solid fa-sitemap"></i></div><div class="t">Comissões</div><div class="s">Técnicas e permanentes</div></a>
    </div>
  </section>
  <?php
  footer_public(); exit;
}

/* -----------------------------------------------------------------------
   VEREADORES — lista
   ----------------------------------------------------------------------- */
if ($view==='vereadores') {
  $q = '%'.strp('q','').'%';
  $st = $pdo->prepare("SELECT id,nome,partido,foto
                       FROM usuarios
                       WHERE tipo_usuario='vereador' AND ativo=1
                         AND (nome LIKE :q OR COALESCE(partido,'') LIKE :q)
                       ORDER BY nome");
  $st->execute([':q'=>$q]); $rows = $st->fetchAll();

  header_public('Vereadores'); ?>
  <div class="card">
    <div class="hd">Vereadores</div>
    <div class="bd">
      <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px">
        <input type="hidden" name="v" value="vereadores">
        <input name="q" placeholder="Buscar por nome/partido" value="<?=h(strp('q',''))?>">
        <button class="btn flat"><i class="fa fa-search"></i> Buscar</button>
      </form>

      <div class="table-wrap">
        <table>
          <thead><tr><th>Vereador</th><th style="width:160px">Partido</th></tr></thead>
        <tbody>
          <?php foreach($rows as $r): $U = map_user_public($r); ?>
            <tr>
              <td>
                <a href="?v=vereador&id=<?=$U['id']?>" style="text-decoration:none;color:inherit">
                  <div style="display:flex;gap:12px;align-items:center">
                    <img class="avatar" src="<?=h($U['foto'])?>" onerror="this.src='<?=BASE?>/assets/avatar.png'">
                    <div><div style="font-weight:900"><?=h($U['nome'])?></div></div>
                  </div>
                </a>
              </td>
              <td><?=h($U['partido']?:'')?></td>
            </tr>
          <?php endforeach; if(!$rows): ?>
            <tr><td colspan="2" class="muted">Nenhum vereador encontrado.</td></tr>
          <?php endif; ?>
        </tbody>
        </table>
      </div>
    </div>
  </div>
  <?php footer_public(); exit;
}

/* perfil do vereador + biografia ao lado + matérias por abas */
if ($view==='vereador' && $id>0) {
  $bioCol = user_bio_col($pdo);
  $sel = "id,nome,partido,foto".($bioCol?(",{$bioCol} AS bio"):"");
  $st=$pdo->prepare("SELECT {$sel} FROM usuarios WHERE id=:id AND tipo_usuario='vereador' LIMIT 1");
  $st->execute([':id'=>$id]); $u=$st->fetch();

  header_public('Vereador');
  if(!$u){ ?><div class="muted">Vereador não encontrado.</div><?php footer_public(); exit; }
  $U=map_user_public($u);
  $bio = trim((string)($u['bio'] ?? ''));

  // Matérias finalizadas/publicadas do vereador (limite 300)
  $sql="SELECT m.id,m.numero,m.ano,m.tipo,m.titulo,sm.resultado,s.data_sessao
        FROM materias m
        JOIN sessao_materias sm ON sm.materia_id=m.id
        JOIN sessoes s ON s.id=sm.sessao_id
        WHERE m.autor_id=:v AND sm.status='finalizada' AND sm.publicar_site=1
        ORDER BY s.data_sessao DESC, m.id DESC LIMIT 300";
  $stm=$pdo->prepare($sql); $stm->execute([':v'=>$id]); $materias=$stm->fetchAll();

  // Agrupa por abas
  $tabs = ['indicacao'=>[],'lei'=>[],'requerimento'=>[],'outros'=>[]];
  foreach($materias as $m){
    $t = mb_strtolower((string)$m['tipo'],'UTF-8');
    if (strpos($t,'indica')!==false)       $tabs['indicacao'][] = $m;
    elseif (strpos($t,'lei')!==false)      $tabs['lei'][] = $m;
    elseif (strpos($t,'requer')!==false)   $tabs['requerimento'][] = $m;
    else                                   $tabs['outros'][] = $m;
  }
  ?>
  <div class="card">
    <div class="hd">Perfil do Vereador</div>
    <div class="bd">
      <div class="vereador-grid">
        <div class="foto-card">
          <img src="<?=h($U['foto'])?>" onerror="this.src='<?=BASE?>/assets/avatar.png'">
          <div class="foto-legenda">
            <span style="font-weight:900"><?=h($U['nome'])?></span>
            <span style="background:#fff;color:#0b4da2;border-radius:8px;padding:2px 8px;font-weight:900"><?=h($U['partido']?:'')?></span>
          </div>
        </div>

        <div>
          <h2 style="margin:0 0 8px 0; font-size:1.6rem;"><?=h($U['nome'])?></h2>

          <div class="card card-plain" style="border:1px dashed var(--border);">
            <div class="hd">Biografia</div>
            <div class="bd" style="white-space:pre-wrap">
              <?= $bio !== '' ? nl2br(h($bio)) : '<span class="muted">Biografia não informada.</span>' ?>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="card" style="margin-top:12px">
    <div class="hd">Matérias do Vereador</div>
    <div class="bd">
      <div class="tabs" role="tablist" aria-label="Tipos de matérias">
        <button class="tab-btn active" data-tab="tab-ind">Indicação (<?=count($tabs['indicacao'])?>)</button>
        <button class="tab-btn" data-tab="tab-lei">Lei (<?=count($tabs['lei'])?>)</button>
        <button class="tab-btn" data-tab="tab-req">Requerimento (<?=count($tabs['requerimento'])?>)</button>
        <button class="tab-btn" data-tab="tab-out">Outros (<?=count($tabs['outros'])?>)</button>
      </div>

      <?php
        $render = function($list){
          if(!$list){
            echo '<div class="muted">Sem registros.</div>'; return;
          }
          echo '<div class="table-wrap"><table><thead><tr><th style="width:110px">Data</th><th style="width:150px">Número</th><th style="width:220px">Tipo</th><th>Título</th><th style="width:140px">Resultado</th></tr></thead><tbody>';
          foreach($list as $m){
            echo '<tr>'.
                 '<td>'.ymd($m['data_sessao']).'</td>'.
                 '<td>'.h($m['numero']).'/'.h($m['ano']).'</td>'.
                 '<td>'.h($m['tipo']).'</td>'.
                 '<td>'.h($m['titulo']).'</td>'.
                 '<td><span class="badge">'.h($m['resultado'] ?: '—').'</span></td>'.
                 '</tr>';
          }
          echo '</tbody></table></div>';
        };
      ?>

      <div id="tab-ind" class="tab-pane active"><?php $render($tabs['indicacao']); ?></div>
      <div id="tab-lei" class="tab-pane"><?php $render($tabs['lei']); ?></div>
      <div id="tab-req" class="tab-pane"><?php $render($tabs['requerimento']); ?></div>
      <div id="tab-out" class="tab-pane"><?php $render($tabs['outros']); ?></div>
    </div>
  </div>

  <script>
    // Abas simples
    (function(){
      const btns=[...document.querySelectorAll('.tab-btn')];
      const panes=[...document.querySelectorAll('.tab-pane')];
      btns.forEach(b=>{
        b.addEventListener('click',()=>{
          btns.forEach(x=>x.classList.remove('active'));
          panes.forEach(p=>p.classList.remove('active'));
          b.classList.add('active');
          const id=b.getAttribute('data-tab');
          const pane=document.getElementById(id);
          if(pane) pane.classList.add('active');
        });
      });
    })();
  </script>
  <?php footer_public(); exit;
}

/* -----------------------------------------------------------------------
   PROPOSTAS
   ----------------------------------------------------------------------- */
if ($view==='propostas') {
  $q = strp('q',''); $ano = nump('ano',0); $tipo = strp('tipo',''); $autor = nump('autor_id',0);

  $conds = ["1=1"]; $p=[];
  if ($q!==''){ $conds[]="(m.titulo LIKE :q OR m.descricao LIKE :q OR CONCAT(m.numero,'/',m.ano) LIKE :q)"; $p[':q']="%$q%"; }
  if ($ano>0){ $conds[]="m.ano=:a"; $p[':a']=$ano; }
  if ($tipo!==''){ $conds[]="m.tipo=:t"; $p[':t']=$tipo; }
  if ($autor>0){ $conds[]="m.autor_id=:au"; $p[':au']=$autor; }
  $conds[] = "EXISTS (SELECT 1 FROM sessao_materias sm WHERE sm.materia_id=m.id AND sm.status='finalizada' AND sm.publicar_site=1)";

  $sql="SELECT m.id,m.numero,m.ano,m.tipo,m.titulo,u.nome AS autor_nome,u.partido AS autor_partido
        FROM materias m
        LEFT JOIN usuarios u ON u.id=m.autor_id
        WHERE ".implode(' AND ',$conds)."
        ORDER BY m.ano DESC, m.id DESC LIMIT 400";
  $st=$pdo->prepare($sql); $st->execute($p); $rows=$st->fetchAll();

  $tipos = $pdo->query("SELECT DISTINCT tipo FROM materias WHERE tipo<>'' ORDER BY tipo")->fetchAll(PDO::FETCH_COLUMN) ?: [];
  $auts  = $pdo->query("SELECT id,nome FROM usuarios WHERE tipo_usuario='vereador' AND ativo=1 ORDER BY nome")->fetchAll();

  header_public('Propostas Legislativas'); ?>
  <div class="card">
    <div class="hd">Propostas Legislativas</div>
    <div class="bd">
      <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px">
        <input type="hidden" name="v" value="propostas">
        <input name="q" placeholder="nº, título, descrição" value="<?=h($q)?>">
        <select name="tipo"><option value="">Tipo</option><?php foreach($tipos as $t): ?><option <?=$t===$tipo?'selected':''?>><?=h($t)?></option><?php endforeach; ?></select>
        <input name="ano" type="number" placeholder="Ano" value="<?=$ano?:''?>">
        <select name="autor_id"><option value="0">Autor (vereador)</option><?php foreach($auts as $a): ?><option value="<?=$a['id']?>" <?=$autor===$a['id']?'selected':''?>><?=h($a['nome'])?></option><?php endforeach; ?></select>
        <button class="btn flat"><i class="fa fa-filter"></i> Filtrar</button>
      </form>

      <div class="table-wrap">
        <table>
          <thead><tr><th style="width:130px">Número</th><th>Proposição</th><th style="width:220px">Autor</th></tr></thead>
          <tbody>
            <?php foreach($rows as $r): ?>
              <tr>
                <td><?=h($r['numero'])?>/<?=h($r['ano'])?><br><span class="muted"><?=h($r['tipo'])?></span></td>
                <td><strong><?=h($r['titulo'])?></strong></td>
                <td><?=h($r['autor_nome']?:'—')?><?= $r['autor_partido'] ? ' — '.h($r['autor_partido']) : '' ?></td>
              </tr>
            <?php endforeach; if(!$rows): ?>
              <tr><td colspan="3" class="muted">Nenhuma proposição encontrada.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
  <?php footer_public(); exit;
}

/* -----------------------------------------------------------------------
   PRESENÇA — relatório por sessão
   ----------------------------------------------------------------------- */
if ($view==='presenca') {
  $det=detect_quorum($pdo);
  header_public('Presença em Plenário');
  if(!$det){
    ?><div class="card"><div class="hd">Presença</div><div class="bd"><span class="muted">Módulo não habilitado (sem tabela de quórum).</span></div></div><?php
    footer_public(); exit;
  }
  $sid=nump('sid',0);
  $slist=$pdo->query("SELECT id,numero,data_sessao,status FROM sessoes ORDER BY data_sessao DESC, id DESC LIMIT 80")->fetchAll();
  if(!$sid && $slist) $sid=(int)$slist[0]['id'];

  $rows=[];
  if($sid){
    $L=$pdo->prepare("SELECT legislatura_id FROM sessoes WHERE id=:s"); $L->execute([':s'=>$sid]); $leg=(int)($L->fetchColumn()?:0);
    if ($leg>0 && table_exists($pdo,'legislatura_vereadores')) {
      $V=$pdo->prepare("SELECT u.id,u.nome,u.partido,u.foto FROM legislatura_vereadores lv JOIN usuarios u ON u.id=lv.vereador_id WHERE lv.legislatura_id=:l ORDER BY u.nome"); $V->execute([':l'=>$leg]); $vereadores=$V->fetchAll();
    } else {
      $vereadores=$pdo->query("SELECT id,nome,partido,foto FROM usuarios WHERE tipo_usuario='vereador' AND ativo=1 ORDER BY nome")->fetchAll();
    }
    $map=[]; foreach($vereadores as $v){ $map[(int)$v['id']]=map_user_public($v)+['presente'=>null]; }
    $Q=$pdo->prepare("SELECT vereador_id, {$det['col']} AS vcol FROM {$det['table']} WHERE sessao_id=:s");
    $Q->execute([':s'=>$sid]); $quorum=$Q->fetchAll();
    foreach($quorum as $qr){
      $vid=(int)$qr['vereador_id']; $val=$qr['vcol']; $presente=null;
      if(is_numeric($val)) $presente=((int)$val)?1:0;
      elseif(is_string($val)) $presente=(strtolower((string)$val)==='presente'||(string)$val==='1')?1:0;
      if(isset($map[$vid])) $map[$vid]['presente']=$presente;
    }
    $rows=array_values($map);
  } ?>
  <div class="card">
    <div class="hd">Presença em Plenário</div>
    <div class="bd">
      <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px">
        <input type="hidden" name="v" value="presenca">
        <select name="sid">
          <?php foreach($slist as $s): ?>
            <option value="<?=$s['id']?>" <?=$sid===$s['id']?'selected':''?>>Sessão <?=$s['numero']?> — <?=ymd($s['data_sessao'])?> (<?=h($s['status'])?>)</option>
          <?php endforeach; ?>
        </select>
        <button class="btn flat"><i class="fa fa-sync"></i> Carregar</button>
      </form>

      <div class="table-wrap"><table>
        <thead><tr><th>Vereador</th><th style="width:140px">Presença</th></tr></thead>
        <tbody>
          <?php foreach($rows as $r): ?>
            <tr>
              <td><div style="display:flex;gap:10px;align-items:center"><img class="avatar" src="<?=h($r['foto'])?>"><div><div style="font-weight:900"><?=h($r['nome'])?></div><div class="muted"><?=h($r['partido']?:'')?></div></div></div></td>
              <td><?= $r['presente']===1 ? 'Presente' : ($r['presente']===0 ? 'Ausente' : '—') ?></td>
            </tr>
          <?php endforeach; if(!$rows): ?><tr><td colspan="2" class="muted">Nenhum dado para a sessão selecionada.</td></tr><?php endif; ?>
        </tbody></table></div>
    </div>
  </div>
  <?php footer_public(); exit;
}

/* -----------------------------------------------------------------------
   MESA DIRETORA
   ----------------------------------------------------------------------- */
if ($view==='mesa') {
  $L = current_legislature($pdo);
  header_public('Mesa Diretora');
  if(!$L){ ?><div class="muted">Nenhuma legislatura cadastrada.</div><?php footer_public(); exit; }

  $mesa=[];
  if (table_exists($pdo,'legislatura_mesa')) {
    $q=$pdo->prepare("SELECT lm.cargo,u.id,u.nome,u.partido,u.foto
                      FROM legislatura_mesa lm
                      JOIN usuarios u ON u.id=lm.vereador_id
                      WHERE lm.legislatura_id=:l
                      ORDER BY FIELD(lm.cargo,'Presidente','Vice-Presidente','1º Secretário','2º Secretário'), u.nome");
    $q->execute([':l'=>$L['id']]); $mesa=$q->fetchAll();
  } ?>
  <div class="card">
    <div class="hd">Mesa Diretora — Legislatura <?=h($L['periodo'] ?: $L['numero'])?></div>
    <div class="bd">
      <?php if($mesa): foreach($mesa as $m): $U=map_user_public($m); ?>
        <div style="display:flex;gap:12px;align-items:center;margin-bottom:10px">
          <img class="avatar" src="<?=h($U['foto'])?>" onerror="this.src='<?=BASE?>/assets/avatar.png'">
          <div>
            <div style="font-weight:900"><?=h($U['nome'])?></div>
            <div class="muted"><?=h($m['cargo'])?> — <?=h($U['partido']?:'')?></div>
          </div>
        </div>
      <?php endforeach; else: ?>
        <div class="muted">Mesa não cadastrada.</div>
      <?php endif; ?>
    </div>
  </div>
  <?php footer_public(); exit;
}

/* -----------------------------------------------------------------------
   COMISSÕES
   ----------------------------------------------------------------------- */
if ($view==='comissoes') {
  $rows=$pdo->query("SELECT id,nome,tipo FROM comissoes ORDER BY nome")->fetchAll();
  header_public('Comissões'); ?>
  <div class="card">
    <div class="hd">Comissões</div>
    <div class="bd">
      <div class="tiles" style="grid-template-columns:repeat(3,1fr)">
        <?php
          $pal = ['blue','green','purple','orange','cyan','gray'];
          $i=0;
          foreach($rows as $r):
            $cls=$pal[$i%count($pal)]; $i++;
        ?>
          <a class="tile <?=$cls?>" href="?v=comissao&id=<?=$r['id']?>">
            <div class="icon"><i class="fa-solid fa-users-rectangle"></i></div>
            <div class="t"><?=h($r['nome'])?></div>
            <div class="s"><?=h($r['tipo'])?></div>
          </a>
        <?php endforeach; if(!$rows): ?>
          <div class="muted">Nenhuma comissão encontrado.</div>
        <?php endif; ?>
      </div>
    </div>
  </div>
  <?php footer_public(); exit;
}
if ($view==='comissao' && $id>0) {
  $st=$pdo->prepare("SELECT id,nome,tipo,finalidade FROM comissoes WHERE id=:id");
  $st->execute([':id'=>$id]); $c=$st->fetch();
  header_public('Comissão');
  if(!$c){ ?><div class="muted">Comissão não encontrada.</div><?php footer_public(); exit; }

  $membros=[];
  if (table_exists($pdo,'comissoes_membros')){
    $q=$pdo->prepare("SELECT u.id,u.nome,u.partido,u.foto,cm.cargo
                      FROM comissoes_membros cm
                      JOIN usuarios u ON u.id=cm.vereador_id
                      WHERE cm.comissao_id=:id
                      ORDER BY cm.cargo DESC, u.nome");
    $q->execute([':id'=>$id]); $membros=$q->fetchAll();
  } ?>
  <div class="card">
    <div class="hd"><?=h($c['nome'])?></div>
    <div class="bd">
      <div class="muted">Tipo: <?=h($c['tipo'])?></div>
      <?php if($c['finalidade']): ?><div style="margin-top:8px"><?=nl2br(h($c['finalidade']))?></div><?php endif; ?>
    </div>
  </div>
  <div class="card" style="margin-top:12px">
    <div class="hd">Composição</div>
    <div class="bd table-wrap">
      <table>
        <thead><tr><th>Vereador</th><th style="width:220px">Cargo</th></tr></thead>
        <tbody>
          <?php foreach($membros as $m): $U=map_user_public($m); ?>
            <tr>
              <td>
                <div style="display:flex;gap:10px;align-items:center">
                  <img class="avatar" src="<?=h($U['foto'])?>">
                  <div><div style="font-weight:900"><?=h($U['nome'])?></div><div class="muted"><?=h($U['partido']?:'')?></div></div>
                </div>
              </td>
              <td><?=h($m['cargo'])?></td>
            </tr>
          <?php endforeach; if(!$membros): ?>
            <tr><td colspan="2" class="muted">Sem membros cadastrados.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
  <?php footer_public(); exit;
}

/* -----------------------------------------------------------------------
   LEGISLAÇÃO
   ----------------------------------------------------------------------- */
if ($view==='legislacao') {
  $q=strp('q',''); $tipo_id=nump('tipo_id',0); $tema_id=nump('tema_id',0); $ano=nump('ano',0);

  $sql="SELECT l.id,l.data_norma,l.numero,l.ementa,l.pdf_path,
               t.nome AS tipo_nome, te.nome AS tema_nome
        FROM legislacao l
        JOIN legislacao_tipos t ON t.id=l.tipo_id
        LEFT JOIN legislacao_temas te ON te.id=l.tema_id
        WHERE 1=1";
  $p=[];
  if ($q!==''){ $sql.=" AND (l.numero LIKE :q OR l.ementa LIKE :q OR l.palavras_chave LIKE :q)"; $p[':q']="%$q%"; }
  if ($tipo_id>0){ $sql.=" AND l.tipo_id=:tid"; $p[':tid']=$tipo_id; }
  if ($tema_id>0){ $sql.=" AND l.tema_id=:tm";  $p[':tm']=$tema_id; }
  if ($ano>0){     $sql.=" AND YEAR(l.data_norma)=:yy"; $p[':yy']=$ano; }
  $sql.=" ORDER BY l.data_norma DESC, l.id DESC LIMIT 400";
  $st=$pdo->prepare($sql); $st->execute($p); $rows=$st->fetchAll();

  $tipos=$pdo->query("SELECT id,nome FROM legislacao_tipos ORDER BY nome")->fetchAll();
  $temas=$pdo->query("SELECT id,nome FROM legislacao_temas ORDER BY nome")->fetchAll();

  header_public('Legislação'); ?>
  <div class="card">
    <div class="hd">Legislação</div>
    <div class="bd">
      <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px">
        <input type="hidden" name="v" value="legislacao">
        <input name="q" placeholder="nº, ementa, palavra-chave" value="<?=h($q)?>">
        <select name="tipo_id"><option value="0">Tipo</option><?php foreach($tipos as $t): ?><option value="<?=$t['id']?>" <?=$t['id']===$tipo_id?'selected':''?>><?=h($t['nome'])?></option><?php endforeach; ?></select>
        <select name="tema_id"><option value="0">Tema</option><?php foreach($temas as $t): ?><option value="<?=$t['id']?>" <?=$t['id']===$tema_id?'selected':''?>><?=h($t['nome'])?></option><?php endforeach; ?></select>
        <input name="ano" type="number" placeholder="Ano" value="<?=$ano?:''?>">
        <button class="btn flat"><i class="fa fa-filter"></i> Filtrar</button>
      </form>

      <div class="table-wrap">
        <table>
          <thead><tr><th style="width:110px">Data</th><th style="width:160px">Número</th><th style="width:200px">Tipo</th><th style="width:200px">Tema</th><th>Ementa</th><th style="width:120px">Arquivo</th></tr></thead>
          <tbody>
            <?php foreach($rows as $r): $pdf = $r['pdf_path'] ? (BASE.'/'.ltrim($r['pdf_path'],'/')) : null; ?>
              <tr>
                <td><?=ymd($r['data_norma'])?></td>
                <td><?=h($r['numero'])?></td>
                <td><?=h($r['tipo_nome'])?></td>
                <td><?=h($r['tema_nome'] ?? '—')?></td>
                <td><?=h(mb_strimwidth((string)($r['ementa']??''),0,120,'…','UTF-8'))?></td>
                <td><?= $pdf ? '<a class="btn flat" target="_blank" href="'.h($pdf).'"><i class="fa fa-file-pdf"></i> PDF</a>' : '<span class="muted">—</span>' ?></td>
              </tr>
            <?php endforeach; if(!$rows): ?>
              <tr><td colspan="6" class="muted">Sem resultados.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
  <?php footer_public(); exit;
}

/* -----------------------------------------------------------------------
   SESSÕES (lista) / SESSÃO (detalhe)
   ----------------------------------------------------------------------- */
if ($view==='sessoes') {
  $status=strp('status',''); $d1=strp('data_from',''); $d2=strp('data_to',''); $leg=nump('legislatura_id',0);
  $conds=["1=1"]; $p=[];
  if($status!==''){ $conds[]="status=:st"; $p[':st']=$status; }
  if($d1!==''){ $conds[]="data_sessao>=:d1"; $p[':d1']=$d1; }
  if($d2!==''){ $conds[]="data_sessao<=:d2"; $p[':d2']=$d2; }
  if($leg>0){ $conds[]="legislatura_id=:lg"; $p[':lg']=$leg; }
  $sql="SELECT id,numero,tipo,data_sessao,legislatura_id,status
        FROM sessoes WHERE ".implode(' AND ',$conds)."
        ORDER BY data_sessao DESC, id DESC LIMIT 300";
  $st=$pdo->prepare($sql); $st->execute($p); $rows=$st->fetchAll();

  header_public('Sessões Plenárias'); ?>
  <div class="card">
    <div class="hd">Sessões Plenárias</div>
    <div class="bd">
      <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px">
        <input type="hidden" name="v" value="sessoes">
        <select name="status">
          <option value="">Todos os status</option>
          <option value="preparacao" <?=$status==='preparacao'?'selected':''?>>Preparação</option>
          <option value="ativa" <?=$status==='ativa'?'selected':''?>>Ativa</option>
          <option value="encerrada" <?=$status==='encerrada'?'selected':''?>>Encerrada</option>
        </select>
        <input name="data_from" type="date" value="<?=h($d1)?>">
        <input name="data_to" type="date" value="<?=h($d2)?>">
        <input name="legislatura_id" type="number" placeholder="Legislatura ID" value="<?=$leg?:''?>">
        <button class="btn flat"><i class="fa fa-filter"></i> Filtrar</button>
      </form>

      <div class="table-wrap">
        <table>
          <thead><tr><th style="width:120px">Número</th><th>Tipo</th><th style="width:140px">Data</th><th style="width:140px">Status</th><th style="width:120px">Ações</th></tr></thead>
          <tbody>
            <?php foreach($rows as $s): ?>
              <tr>
                <td><strong><?=h($s['numero'])?></strong></td>
                <td><?=h($s['tipo'])?></td>
                <td><?=ymd($s['data_sessao'])?></td>
                <td><span class="badge"><?=h($s['status'])?></span></td>
                <td><a class="btn flat" href="?v=sessao&id=<?=$s['id']?>"><i class="fa fa-eye"></i> Ver</a></td>
              </tr>
            <?php endforeach; if(!$rows): ?>
              <tr><td colspan="5" class="muted">Nenhuma sessão.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
  <?php footer_public(); exit;
}
if ($view==='sessao' && $id>0) {
  $st=$pdo->prepare("SELECT * FROM sessoes WHERE id=:id LIMIT 1");
  $st->execute([':id'=>$id]); $s=$st->fetch();
  header_public('Sessão'); if(!$s){ ?><div class="muted">Sessão não encontrada.</div><?php footer_public(); exit; }

  $stm=$pdo->prepare("SELECT sm.id AS sm_id, sm.ordem, sm.status, sm.resultado, sm.publicar_site,
                             m.id AS materia_id, m.numero, m.ano, m.tipo, m.titulo,
                             u.nome AS autor_nome, u.partido AS autor_partido
                      FROM sessao_materias sm
                      JOIN materias m ON m.id=sm.materia_id
                      LEFT JOIN usuarios u ON u.id=m.autor_id
                      WHERE sm.sessao_id=:s
                      ORDER BY sm.ordem ASC, sm.id ASC");
  $stm->execute([':s'=>$id]); $materias=$stm->fetchAll();

  $itens = ($s['status']==='ativa')
    ? $materias
    : array_values(array_filter($materias, fn($r)=> $r['status']==='finalizada' && (int)$r['publicar_site']===1));

  // ATA via tabela/arquivo
  $ataUrl = ata_link($id); ?>

  <div class="card">
    <div class="hd">Sessão <?=h($s['numero'])?> — <?=h($s['tipo'])?></div>
    <div class="bd">
      <div>Data: <strong><?=ymd($s['data_sessao'])?></strong></div>
      <div class="muted">Status: <?=h($s['status'])?></div>
    </div>
  </div>

  <div class="card" style="margin-top:12px">
    <div class="hd">Matérias da Sessão</div>
    <div class="bd table-wrap">
      <table>
        <thead><tr><th style="width:60px">#</th><th>Matéria</th><th style="width:220px">Autor</th><th style="width:160px">Situação</th></tr></thead>
        <tbody>
          <?php foreach($itens as $r): ?>
            <tr>
              <td><?=h($r['ordem'])?></td>
              <td><strong><?=h($r['titulo'])?></strong><br><span class="muted"><?=h($r['tipo'])?> — Nº <?=h($r['numero'])?>/<?=h($r['ano'])?></span></td>
              <td><?=h($r['autor_nome']?:'—')?><?= $r['autor_partido'] ? ' — '.h($r['autor_partido']) : '' ?></td>
              <td><span class="badge"><?=h($r['status'])?><?= $r['resultado'] ? ' · '.h($r['resultado']) : '' ?></span></td>
            </tr>
          <?php endforeach; if(!$itens): ?>
            <tr><td colspan="4" class="muted">Nenhuma matéria disponível publicamente.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <div class="card" style="margin-top:12px">
    <div class="hd">Ata</div>
    <div class="bd">
      <?php if($ataUrl): ?>
        <a class="btn" href="<?=$ataUrl?>"><i class="fa fa-file-lines"></i> Ver Ata</a>
      <?php else: ?>
        <span class="muted">Arquivo/registro de ata não encontrado.</span>
      <?php endif; ?>
    </div>
  </div>
  <?php footer_public(); exit;
}

/* -----------------------------------------------------------------------
   ATA — visualização pública (via tabela `atas`)
   ----------------------------------------------------------------------- */
if ($view==='ata') {
  $sid = nump('sid', 0);        // sessao_id
  $aid = nump('id', 0);         // opcional: id da ata

  // Busca ata publicada por sessão OU por id
  $where = $aid ? "a.id=:id" : "a.sessao_id=:s";
  $p = $aid ? [':id'=>$aid] : [':s'=>$sid];

  $st = $pdo->prepare("
    SELECT a.id, a.sessao_id, a.titulo, a.texto_html, a.pdf_path, a.publicar_site,
           s.numero AS sessao_numero, s.tipo AS sessao_tipo, s.data_sessao
      FROM atas a
      JOIN sessoes s ON s.id=a.sessao_id
     WHERE {$where} AND a.publicar_site=1
     LIMIT 1
  ");
  $st->execute($p);
  $row = $st->fetch();

  header_public('Ata');
  if (!$row) {
    ?><div class="card"><div class="hd">Ata</div><div class="bd"><span class="muted">Ata não encontrada ou não publicada.</span></div></div><?php
    footer_public(); exit;
  }

  $pdf_url = $row['pdf_path'] ? (BASE.'/'.ltrim((string)$row['pdf_path'],'/')) : null;
  ?>
  <div class="card">
    <div class="hd">Ata — Sessão <?=h($row['sessao_numero'])?> · <?=h($row['sessao_tipo'])?> (<?=ymd($row['data_sessao'])?>)</div>
    <div class="bd">
      <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px">
        <?php if($pdf_url): ?>
          <a class="btn" target="_blank" href="<?=$pdf_url?>"><i class="fa fa-file-pdf"></i> Baixar PDF</a>
          <a class="btn flat" target="_blank" href="<?=$pdf_url?>"><i class="fa fa-up-right-from-square"></i> Abrir em nova aba</a>
        <?php endif; ?>
      </div>

      <?php if($pdf_url): ?>
        <div style="border:1px solid var(--border);border-radius:12px;overflow:hidden">
          <iframe
            src="<?=h($pdf_url)?>#view=FitH"
            style="width:100%;height:82vh;border:0"
          ></iframe>
        </div>
      <?php elseif(!empty($row['texto_html'])): ?>
        <div style="border:1px solid var(--border);border-radius:12px;overflow:hidden">
          <iframe
            style="width:100%;height:82vh;border:0"
            srcdoc="<?=htmlspecialchars((string)$row['texto_html'], ENT_QUOTES, 'UTF-8')?>"
          ></iframe>
        </div>
      <?php else: ?>
        <div class="muted">Nenhum conteúdo disponível para esta ata.</div>
      <?php endif; ?>
    </div>
  </div>
  <?php
  footer_public(); exit;
}

/* -----------------------------------------------------------------------
   ATAS — lista
   ----------------------------------------------------------------------- */
if ($view==='atas') {
  $rows=$pdo->query("SELECT id,numero,data_sessao,status
                     FROM sessoes
                     WHERE status IN ('encerrada','ativa','preparacao')
                     ORDER BY id DESC LIMIT 300")->fetchAll();

  header_public('Atas'); ?>
  <div class="card">
    <div class="hd">Atas</div>
    <div class="bd table-wrap">
      <table>
        <thead><tr><th style="width:130px">Sessão</th><th>Descrição</th><th style="width:160px">Ação</th></tr></thead>
        <tbody>
          <?php foreach($rows as $r):
            $link = ata_link((int)$r['id']);
          ?>
            <tr>
              <td>#<?=h($r['id'])?></td>
              <td>
                <div style="font-weight:900">Sessão <?=h($r['numero'])?> — <?=ymd($r['data_sessao'])?></div>
                <div class="muted">Status: <?=h($r['status'])?></div>
              </td>
              <td>
                <?= $link
                      ? '<a class="btn flat" href="'.h($link).'"><i class="fa fa-file-lines"></i> Ver Ata</a>'
                      : '<span class="muted">ata_public.php/ata.php não encontrado</span>' ?>
              </td>
            </tr>
          <?php endforeach; if(!$rows): ?>
            <tr><td colspan="3" class="muted">Nenhuma sessão encontrada.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
  <?php footer_public(); exit;
}

/* -----------------------------------------------------------------------
   404
   ----------------------------------------------------------------------- */
header_public('Página não encontrada'); ?>
<div class="card"><div class="hd">Página não encontrada</div><div class="bd">Use o menu superior para navegar.</div></div>
<?php footer_public(); exit;

} catch (Throwable $e) {
  header_public('Erro'); ?><div class="card"><div class="hd">Erro</div><div class="bd">Ocorreu um erro ao processar a página.</div></div><?php footer_public(); exit;
}
