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

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

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

// ===== helpers de segurança/ux =====
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){
  $d = trim((string)$d);
  if (!$d) return '';
  $ts = strtotime($d);
  return $ts ? date('d/m/Y',$ts) : h($d);
}
function map_user_public(array $u): array {
  return [
    'id'      => (int)$u['id'],
    'nome'    => $u['nome'],
    'partido' => $u['partido'] ?? null,
    'foto'    => $u['foto'] ? (BASE.'/'.ltrim($u['foto'],'/')) : (BASE.'/assets/avatar.png'),
  ];
}

// ===== layout =====
function header_public(string $title='Atividades Legislativas'){
  ?>
  <!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.4.0/css/all.min.css" rel="stylesheet">
  <style>
    :root{
      --brand:#2563eb;--brand-2:#1d4ed8;--border:#e5e7eb;--muted:#64748b;--bg:#f6f8fb;
      --green:#22c55e;--red:#ef4444;--amber:#f59e0b;
      --shadow:0 12px 28px rgba(2,6,23,.06),0 2px 6px rgba(2,6,23,.04);
      --radius:14px;
    }
    html,body{background:var(--bg);color:#0f172a}
    .wrap{max-width:1200px;margin:18px auto;padding:0 16px}
    .header{position:sticky;top:0;z-index:10;background:#fff;border-bottom:1px solid var(--border)}
    .header-inner{max-width:1200px;margin:0 auto;padding:12px 16px;display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}
    .brand{display:flex;gap:10px;align-items:center;font-weight:900}
    .nav{display:flex;gap:8px;flex-wrap:wrap}
    .btn{display:inline-flex;align-items:center;gap:8px;background:#fff;border:1px solid var(--border);border-radius:10px;padding:.5rem .8rem;font-weight:700;text-decoration:none;color:#0f172a}
    .btn:hover{background:#f8fafc}
    .btn.primary{background:var(--brand);color:#fff;border-color:transparent}
    .btn.primary:hover{background:var(--brand-2)}
    .card{background:#fff;border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow)}
    .card .hd{padding:14px 16px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between}
    .card .bd{padding:16px}
    .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:12px}
    .kpi{padding:16px;border-radius:14px;color:#0f172a;background:#fff;border:1px solid var(--border)}
    .muted{color:var(--muted)}
    table{width:100%;border-collapse:separate;border-spacing:0}
    thead th{background:#f8fafc;border-bottom:1px solid var(--border);text-align:left;padding:10px}
    tbody td{border-bottom:1px solid var(--border);padding:10px;vertical-align:top}
    .avatar{width:52px;height:52px;border-radius:999px;object-fit:cover;background:#e5e7eb;border:1px solid var(--border)}
    .badge{display:inline-block;padding:.18rem .55rem;border-radius:999px;font-weight:800;font-size:.74rem;background:#eef2ff;color:#4338ca}
    .search{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-bottom:12px}
    input,select,textarea{border:2px solid var(--border);border-radius:10px;padding:.55rem .7rem;font-size:1rem;background:#fff}
    input:focus,select:focus{outline:0;box-shadow:0 0 0 3px rgba(37,99,235,.12);border-color:var(--brand)}
    .pill{display:inline-block;padding:.22rem .55rem;border-radius:999px;background:#edf2f7}
    .toolbar{display:flex;gap:8px;flex-wrap:wrap}
    .table-wrap{overflow-x:auto}
    .cta{display:inline-flex;gap:6px;align-items:center}
  </style>
  </head><body>
  <header class="header">
    <div class="header-inner">
      <div class="brand"><i class="fa-solid fa-landmark-flag"></i> Atividades Legislativas</div>
      <nav class="nav">
        <a class="btn" href="?"><i class="fa fa-house"></i> Início</a>
        <a class="btn" href="?v=vereadores"><i class="fa fa-user-group"></i> Vereadores</a>
        <a class="btn" href="?v=legislaturas"><i class="fa fa-calendar"></i> Legislaturas</a>
        <a class="btn" href="?v=comissoes"><i class="fa fa-people-group"></i> Comissões</a>
        <a class="btn" href="?v=legislacao"><i class="fa fa-scale-balanced"></i> Legislação</a>
        <a class="btn" href="?v=sessoes"><i class="fa fa-gavel"></i> Sessões</a>
        <a class="btn" href="?v=atas"><i class="fa fa-file-lines"></i> Atas</a>
      </nav>
    </div>
  </header>
  <div class="wrap">
  <?php
}
function footer_public(){
  ?>
  </div>
  <footer style="margin-top:28px;padding:18px;color:#475569;text-align:center;font-size:.92rem">
    <div>© <?=date('Y')?> Câmara Municipal — Módulo Público</div>
  </footer>
  </body></html>
  <?php
}

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

// ===== páginas =====
try {

  // HOME
  if ($view === 'home' || $view === '') {
    // KPIs rápidos
    $totalV = (int)$pdo->query("SELECT COUNT(*) FROM usuarios WHERE tipo_usuario='vereador' AND ativo=1")->fetchColumn();
    $totalC = (int)$pdo->query("SELECT COUNT(*) FROM comissoes")->fetchColumn();
    $totalL = (int)$pdo->query("SELECT COUNT(*) FROM legislaturas")->fetchColumn();
    $totalN = (int)$pdo->query("SELECT COUNT(*) FROM legislacao")->fetchColumn();
    $rs = $pdo->query("SELECT SUM(status='preparacao') p,SUM(status='ativa') a,SUM(status='encerrada') e FROM sessoes")->fetch();
    header_public();
    ?>
    <div class="grid" style="margin-bottom:12px">
      <div class="kpi"><div class="muted">Vereadores</div><div style="font-size:1.6rem;font-weight:900"><?=$totalV?></div></div>
      <div class="kpi"><div class="muted">Comissões</div><div style="font-size:1.6rem;font-weight:900"><?=$totalC?></div></div>
      <div class="kpi"><div class="muted">Legislaturas</div><div style="font-size:1.6rem;font-weight:900"><?=$totalL?></div></div>
      <div class="kpi"><div class="muted">Legislação</div><div style="font-size:1.6rem;font-weight:900"><?=$totalN?></div></div>
      <div class="kpi"><div class="muted">Sessões — Preparação</div><div style="font-size:1.6rem;font-weight:900"><?=(int)$rs['p']?></div></div>
      <div class="kpi"><div class="muted">Sessões — Ativas</div><div style="font-size:1.6rem;font-weight:900"><?=(int)$rs['a']?></div></div>
      <div class="kpi"><div class="muted">Sessões — Encerradas</div><div style="font-size:1.6rem;font-weight:900"><?=(int)$rs['e']?></div></div>
    </div>

    <div class="card">
      <div class="hd"><strong><i class="fa fa-bullhorn"></i> Acesso rápido</strong></div>
      <div class="bd">
        <div class="toolbar">
          <a class="btn primary" href="?v=sessoes&status=ativa"><i class="fa fa-gavel"></i> Sessões ativas</a>
          <a class="btn" href="?v=legislacao"><i class="fa fa-scale-balanced"></i> Buscar legislação</a>
          <a class="btn" href="?v=vereadores"><i class="fa fa-user-group"></i> Lista de vereadores</a>
          <a class="btn" href="?v=comissoes"><i class="fa fa-people-group"></i> Comissões</a>
        </div>
      </div>
    </div>
    <?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"><strong><i class="fa fa-user-group"></i> Vereadores</strong>
        <form class="cta" method="get">
          <input type="hidden" name="v" value="vereadores">
          <input name="q" placeholder="Buscar por nome/partido" value="<?=h(strp('q',''))?>">
          <button class="btn" type="submit"><i class="fa fa-magnifying-glass"></i> Buscar</button>
        </form>
      </div>
      <div class="bd">
        <div class="grid">
          <?php foreach($rows as $r): $u=map_user_public($r); ?>
            <div class="card" style="padding:14px">
              <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 class="muted"><?=h($u['partido']?:'')?></div>
                  <div style="margin-top:8px"><a class="btn" href="?v=vereador&id=<?=$u['id']?>"><i class="fa fa-address-card"></i> Ver perfil</a></div>
                </div>
              </div>
            </div>
          <?php endforeach; if(!$rows): ?>
            <div class="muted">Nenhum registro.</div>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <?php
    footer_public(); exit;
  }

  // VEREADOR — perfil + matérias publicadas
  if ($view === 'vereador' && $id>0) {
    $st=$pdo->prepare("SELECT id,nome,partido,foto FROM usuarios WHERE id=:id AND tipo_usuario='vereador' LIMIT 1");
    $st->execute([':id'=>$id]); $u=$st->fetch();
    if(!$u){ header_public('Vereador'); ?><div class="muted">Vereador não encontrado.</div><?php footer_public(); exit; }
    $U = map_user_public($u);

    // matérias publicadas (quando finalizadas e publicar_site=1)
    $ano = nump('ano',0);
    $p = [':v'=>$id];
    $conds = ["m.autor_id=:v"];
    if ($ano>0){ $conds[]="m.ano=:a"; $p[':a']=$ano; }
    $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 ".implode(' AND ',$conds)." AND sm.status='finalizada' AND sm.publicar_site=1
          ORDER BY s.data_sessao DESC, m.id DESC LIMIT 200";
    $stm=$pdo->prepare($sql); $stm->execute($p); $materias=$stm->fetchAll();

    // comissões
    $com = [];
    if ($pdo->query("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name='comissoes_membros'")->fetchColumn()){
      $q=$pdo->prepare("SELECT c.id,c.nome,c.tipo,cm.cargo FROM comissoes_membros cm JOIN comissoes c ON c.id=cm.comissao_id WHERE cm.vereador_id=:v ORDER BY c.nome");
      $q->execute([':v'=>$id]); $com=$q->fetchAll();
    }

    header_public('Vereador — '.$U['nome']);
    ?>
    <div class="card">
      <div class="hd"><strong><i class="fa fa-address-card"></i> Perfil do Vereador</strong></div>
      <div class="bd">
        <div style="display:flex;gap:14px;align-items:center;flex-wrap:wrap">
          <img class="avatar" src="<?=h($U['foto'])?>" onerror="this.src='<?=BASE?>/assets/avatar.png'">
          <div>
            <div style="font-weight:900;font-size:1.3rem"><?=h($U['nome'])?></div>
            <div class="muted">Partido: <?=h($U['partido']?:'—')?></div>
            <?php if($com): ?>
              <div style="margin-top:8px">
                <?php foreach($com as $c): ?>
                  <span class="pill"><?=h($c['nome'])?> — <?=h($c['cargo'])?></span>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>

    <div class="card" style="margin-top:12px">
      <div class="hd">
        <strong><i class="fa fa-list"></i> Matérias Publicadas</strong>
        <form class="cta" method="get">
          <input type="hidden" name="v" value="vereador"><input type="hidden" name="id" value="<?=$id?>">
          <input type="number" name="ano" placeholder="Ano" value="<?=$ano?:''?>">
          <button class="btn" type="submit"><i class="fa fa-filter"></i> Filtrar</button>
        </form>
      </div>
      <div class="bd table-wrap">
        <table>
          <thead><tr><th style="width:120px">Data</th><th style="width:160px">Número</th><th style="width:200px">Tipo</th><th>Título</th><th style="width:120px">Resultado</th></tr></thead>
          <tbody>
          <?php foreach($materias as $m): ?>
            <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>
          <?php endforeach; if(!$materias): ?>
            <tr><td colspan="5" class="muted">Nenhuma matéria publicada.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php
    footer_public(); exit;
  }

  // COMISSÕES — lista
  if ($view === 'comissoes') {
    $st=$pdo->query("SELECT id,nome,tipo FROM comissoes ORDER BY nome");
    $rows=$st->fetchAll();
    header_public('Comissões');
    ?>
    <div class="card">
      <div class="hd"><strong><i class="fa fa-people-group"></i> Comissões</strong></div>
      <div class="bd">
        <div class="grid">
          <?php foreach($rows as $r): ?>
            <div class="card" style="padding:14px">
              <div style="font-weight:900"><?=h($r['nome'])?></div>
              <div class="muted"><?=h($r['tipo'])?></div>
              <div style="margin-top:8px"><a class="btn" href="?v=comissao&id=<?=$r['id']?>"><i class="fa fa-eye"></i> Ver composição</a></div>
            </div>
          <?php endforeach; if(!$rows): ?>
            <div class="muted">Nenhuma comissão.</div>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <?php
    footer_public(); exit;
  }

  // COMISSÃO — detalhe
  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 ($pdo->query("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name='comissoes_membros'")->fetchColumn()){
      $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"><strong><i class="fa fa-people-group"></i> <?=h($c['nome'])?></strong></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"><strong><i class="fa fa-users"></i> Composição</strong></div>
      <div class="bd table-wrap">
        <table>
          <thead><tr><th>Vereador</th><th style="width:200px">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'])?>" onerror="this.src='<?=BASE?>/assets/avatar.png'">
                    <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.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php
    footer_public(); exit;
  }

  // LEGISLATURAS — lista
  if ($view === 'legislaturas') {
    $st=$pdo->query("SELECT id,numero,periodo,data_inicio,data_fim,ativo FROM legislaturas ORDER BY data_inicio DESC, id DESC");
    $rows=$st->fetchAll();
    header_public('Legislaturas');
    ?>
    <div class="card">
      <div class="hd"><strong><i class="fa fa-calendar"></i> Legislaturas</strong></div>
      <div class="bd table-wrap">
        <table>
          <thead><tr><th style="width:120px">Número</th><th>Período</th><th style="width:160px">Início</th><th style="width:160px">Término</th><th style="width:160px">Ações</th></tr></thead>
          <tbody>
          <?php foreach($rows as $r): ?>
            <tr>
              <td><strong><?=h($r['numero'])?></strong></td>
              <td><?=h($r['periodo'])?></td>
              <td><?=ymd($r['data_inicio'])?></td>
              <td><?=ymd($r['data_fim'])?></td>
              <td><a class="btn" href="?v=legislatura&id=<?=$r['id']?>"><i class="fa fa-eye"></i> Ver</a></td>
            </tr>
          <?php endforeach; if(!$rows): ?>
            <tr><td colspan="5" class="muted">Nenhuma legislatura.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php
    footer_public(); exit;
  }

  // LEGISLATURA — detalhe
  if ($view === 'legislatura' && $id>0) {
    $st=$pdo->prepare("SELECT id,numero,periodo,data_inicio,data_fim,ativo FROM legislaturas WHERE id=:id");
    $st->execute([':id'=>$id]); $L=$st->fetch();
    header_public('Legislatura');
    if(!$L){ ?><div class="muted">Legislatura não encontrada.</div><?php footer_public(); exit; }
    // composição
    $vers=[]; if ($pdo->query("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name='legislatura_vereadores'")->fetchColumn()){
      $q=$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=:id ORDER BY u.nome");
      $q->execute([':id'=>$id]); $vers=$q->fetchAll();
    }
    // mesa
    $mesa=[]; if ($pdo->query("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name='legislatura_mesa'")->fetchColumn()){
      $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=:id ORDER BY FIELD(lm.cargo,'Presidente','Vice-Presidente','1º Secretário','2º Secretário'), u.nome");
      $q->execute([':id'=>$id]); $mesa=$q->fetchAll();
    }
    ?>
    <div class="card">
      <div class="hd"><strong><i class="fa fa-calendar"></i> Legislatura <?=h($L['periodo']?:$L['numero'])?></strong></div>
      <div class="bd">
        <div>Período: <strong><?=h($L['periodo'])?></strong></div>
        <div class="muted">De <?=ymd($L['data_inicio'])?> a <?=ymd($L['data_fim'])?></div>
      </div>
    </div>
    <div class="grid" style="margin-top:12px">
      <div class="card">
        <div class="hd"><strong><i class="fa fa-chess-king"></i> Mesa Diretora</strong></div>
        <div class="bd">
          <?php if($mesa): foreach($mesa as $m): $U=map_user_public($m); ?>
            <div style="display:flex;gap:10px;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">Não cadastrada.</div>
          <?php endif; ?>
        </div>
      </div>
      <div class="card">
        <div class="hd"><strong><i class="fa fa-user-group"></i> Vereadores</strong></div>
        <div class="bd">
          <?php if($vers): foreach($vers as $v): $U=map_user_public($v); ?>
            <div style="display:flex;gap:10px;align-items:center;margin-bottom:8px">
              <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($U['partido']?:'')?></div></div>
            </div>
          <?php endforeach; else: ?>
            <div class="muted">Sem composição cadastrada.</div>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <?php
    footer_public(); exit;
  }

  // LEGISLAÇÃO — lista/busca
  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"><strong><i class="fa fa-scale-balanced"></i> Legislação</strong></div>
      <div class="bd">
        <form class="search" method="get">
          <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" type="submit"><i class="fa fa-magnifying-glass"></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><?php if($pdf): ?><a class="btn" target="_blank" href="<?=$pdf?>"><i class="fa fa-file-pdf"></i> PDF</a><?php else: ?><span class="muted">—</span><?php endif; ?></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
  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');
    ?>
    <div class="card">
      <div class="hd"><strong><i class="fa fa-gavel"></i> Sessões</strong></div>
      <div class="bd">
        <form class="search" method="get">
          <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" type="submit"><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:140px">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" 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;
  }

  // SESSÃO — detalhe (matérias + quórum se existir)
  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.votos_favor,sm.votos_contra,sm.votos_abstencao,sm.publicar_site,
                               m.id AS materia_id,m.numero,m.ano,m.tipo,m.titulo,m.descricao,
                               u.id AS autor_id,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();

    // mostra publicamente: finalizadas com publicar_site=1 (mantemos as demais só se sessão ativa)
    $pubItems = array_values(array_filter($materias, function($r){
      return ($r['status']==='finalizada' && (int)$r['publicar_site']===1);
    }));
    $showItems = ($s['status']==='ativa') ? $materias : $pubItems;

    // quórum — melhor esforço
    $candidates=['sessoes_quorum','sessao_quorum','quorum','presencas','presenca_sessao'];
    $table=null; $col=null;
    foreach($candidates as $t){
      $chk = $pdo->prepare("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name=:t");
      $chk->execute([':t'=>$t]); if(!$chk->fetchColumn()) continue;
      $has = $pdo->prepare("SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name=:t AND column_name IN ('sessao_id','vereador_id')");
      $has->execute([':t'=>$t]); if(!$has->fetchColumn()) continue;
      foreach (['presente','presenca','status'] as $cname){
        $ok = $pdo->prepare("SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name=:t AND column_name=:c");
        $ok->execute([':t'=>$t,':c'=>$cname]);
        if ($ok->fetchColumn()){ $table=$t; $col=$cname; break 2; }
      }
    }
    $quorum=[];
    if($table && $col){
      $stq=$pdo->prepare("SELECT vereador_id,$col AS vcol FROM $table WHERE sessao_id=:s");
      $stq->execute([':s'=>$id]); $quorum=$stq->fetchAll();
    }

    ?>
    <div class="card">
      <div class="hd"><strong><i class="fa fa-gavel"></i> Sessão <?=h($s['numero'])?> — <?=h($s['tipo'])?></strong></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"><strong><i class="fa fa-list-check"></i> Matérias da Sessão</strong></div>
      <div class="bd table-wrap">
        <table>
          <thead><tr><th style="width:64px">#</th><th>Título</th><th style="width:200px">Propositor</th><th style="width:160px">Status</th><th style="width:140px">Parcial</th></tr></thead>
          <tbody>
            <?php foreach($showItems as $r): ?>
              <tr>
                <td><?=h($r['ordem'])?></td>
                <td><div style="font-weight:700"><?=h($r['titulo'])?></div><div class="muted"><?=h($r['tipo'])?> — Nº <?=h($r['numero'])?>/<?=h($r['ano'])?></div></td>
                <td><?=h($r['autor_nome']?:'—')?><?= $r['autor_partido'] ? ' — '.h($r['autor_partido']) : '' ?></td>
                <td><span class="badge"><?=h($r['status'])?><?php if($r['resultado']):?> · <?=h($r['resultado'])?><?php endif; ?></span></td>
                <td>F: <?= (int)$r['votos_favor'] ?> · C: <?= (int)$r['votos_contra'] ?> · A: <?= (int)$r['votos_abstencao'] ?></td>
              </tr>
            <?php endforeach; if(!$showItems): ?>
              <tr><td colspan="5" class="muted">Nenhuma matéria disponível publicamente.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <div class="grid" style="margin-top:12px">
      <div class="card">
        <div class="hd"><strong><i class="fa fa-users-viewfinder"></i> Quórum (presenças)</strong></div>
        <div class="bd">
          <?php if($table && $quorum): ?>
            <div class="muted" style="margin-bottom:8px">Fonte: tabela <code><?=h($table)?></code></div>
            <div class="table-wrap">
              <table>
                <thead><tr><th>Vereador</th><th style="width:140px">Presença</th></tr></thead>
                <tbody>
                  <?php
                  // montar mapa com base na legislatura se possível
                  $qL=$pdo->prepare("SELECT legislatura_id FROM sessoes WHERE id=:s"); $qL->execute([':s'=>$id]); $leg=(int)($qL->fetchColumn()?:0);
                  if ($leg>0 && $pdo->query("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name='legislatura_vereadores'")->fetchColumn()){
                    $qV=$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");
                    $qV->execute([':l'=>$leg]); $vereadores=$qV->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]; }
                  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;
                  }
                  $items=array_values($map);
                  foreach($items as $it): ?>
                    <tr>
                      <td><div style="display:flex;gap:10px;align-items:center"><img class="avatar" src="<?=h($it['foto'])?>"><div><div style="font-weight:900"><?=h($it['nome'])?></div><div class="muted"><?=h($it['partido']?:'')?></div></div></div></td>
                      <td><?= $it['presente']===1 ? 'Presente' : ($it['presente']===0 ? 'Ausente' : '—') ?></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php else: ?>
            <div class="muted">Sem dados de presença para esta sessão.</div>
          <?php endif; ?>
        </div>
      </div>

      <div class="card">
        <div class="hd"><strong><i class="fa fa-file-lines"></i> Ata</strong></div>
        <div class="bd">
          <?php
          $ataUrl=null;
          if ($pdo->query("SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name='sessoes' AND column_name='ata_pdf'")->fetchColumn()){
            $ataUrl = $s['ata_pdf'] ? (BASE.'/'.ltrim($s['ata_pdf'],'/')) : null;
          } elseif ($pdo->query("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name='atas'")->fetchColumn()){
            $qA=$pdo->prepare("SELECT pdf_path FROM atas WHERE sessao_id=:s LIMIT 1"); $qA->execute([':s'=>$id]); $ataPath=$qA->fetchColumn();
            $ataUrl = $ataPath ? (BASE.'/'.ltrim($ataPath,'/')) : null;
          }
          if ($ataUrl): ?>
            <a class="btn" target="_blank" href="<?=$ataUrl?>"><i class="fa fa-file-pdf"></i> Abrir PDF da Ata</a>
          <?php else: ?>
            <div class="muted">Ata não disponível.</div>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <?php
    footer_public(); exit;
  }

  // ATAS — lista simples (tabela "atas" ou fallback sessoes.ata_pdf)
  if ($view === 'atas') {
    $rows=[];
    if ($pdo->query("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name='atas'")->fetchColumn()){
      $st=$pdo->query("SELECT id,sessao_id,titulo,resumo,pdf_path,created_at FROM atas ORDER BY id DESC LIMIT 300");
      $rows=$st->fetchAll();
      $mode='atas';
    } else {
      $st=$pdo->query("SELECT id AS sessao_id, numero, data_sessao, ata_pdf FROM sessoes WHERE ata_pdf IS NOT NULL AND ata_pdf<>'' ORDER BY id DESC LIMIT 300");
      $rows=$st->fetchAll();
      $mode='sessoes';
    }
    header_public('Atas');
    ?>
    <div class="card">
      <div class="hd"><strong><i class="fa fa-file-lines"></i> Atas</strong></div>
      <div class="bd table-wrap">
        <table>
          <thead><tr><th style="width:120px">Sessão</th><th>Título/Resumo</th><th style="width:140px">Arquivo</th></tr></thead>
          <tbody>
            <?php foreach($rows as $r): $pdf = ($mode==='atas') ? ($r['pdf_path']?(BASE.'/'.ltrim($r['pdf_path'],'/')):null) : ($r['ata_pdf']?(BASE.'/'.ltrim($r['ata_pdf'],'/')):null); ?>
              <tr>
                <td>#<?=h($r['sessao_id'])?></td>
                <td>
                  <?php if($mode==='atas'): ?>
                    <div style="font-weight:700"><?=h($r['titulo']?:('Ata da Sessão '.$r['sessao_id']))?></div>
                    <div class="muted"><?=h(mb_strimwidth((string)($r['resumo']??''),0,160,'…','UTF-8'))?></div>
                  <?php else: ?>
                    <div style="font-weight:700">Sessão <?=h($r['numero']?:$r['sessao_id'])?> — <?=ymd($r['data_sessao'])?></div>
                  <?php endif; ?>
                </td>
                <td><?php if($pdf): ?><a class="btn" target="_blank" href="<?=$pdf?>"><i class="fa fa-file-pdf"></i> PDF</a><?php else: ?><span class="muted">—</span><?php endif; ?></td>
              </tr>
            <?php endforeach; if(!$rows): ?>
              <tr><td colspan="3" class="muted">Nenhuma ata disponível.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php
    footer_public(); exit;
  }

  // fallback rota desconhecida
  header_public('Página não encontrada');
  ?><div class="muted">Página não encontrada. Use o menu acima.</div><?php
  footer_public(); exit;

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