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

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

/* Lista */
$lista = $pdo->query("
  SELECT id, numero, periodo, data_inicio, data_fim, ativo
  FROM legislaturas
  ORDER BY data_inicio DESC, id DESC
")->fetchAll();

/* Vereadores para selects */
$vereadores = $pdo->query("
  SELECT id, nome, COALESCE(partido,'') AS partido
  FROM usuarios
  WHERE tipo_usuario='vereador' AND ativo=1
  ORDER BY nome
")->fetchAll();

$msg = $_GET['msg'] ?? null;
?>
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<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">
<title>Legislaturas</title>
<style>
  :root{
    --brand:#2563eb;--brand-600:#1d4ed8;
    --bg:#f6f8fb;--card:#fff;--border:#e5e7eb;--muted:#64748b;--text:#0f172a;
    --green:#22c55e;--green-600:#16a34a;--green-100:#dcfce7;
    --red:#ef4444;--red-600:#dc2626;--red-100:#fee2e2;
    --amber:#f59e0b;--amber-600:#d97706;
    --radius:14px;--radius-sm:10px;--shadow:0 12px 28px rgba(2,6,23,.06),0 2px 6px rgba(2,6,23,.04);
  }
  html,body{background:var(--bg);color:var(--text)}
  .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);backdrop-filter:blur(8px)}
  .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}
  .title{font-weight:800}

  /* ---------- BOTÕES (sistema unificado) ---------- */
  .btn{
    --btn-bg:#fff; --btn-fg:#0f172a; --btn-bd:var(--border);
    display:inline-flex; align-items:center; gap:8px;
    background:var(--btn-bg); color:var(--btn-fg); border:2px solid var(--btn-bd);
    border-radius:10px; padding:.55rem .9rem; font-weight:800; text-decoration:none; cursor:pointer;
    box-shadow:var(--shadow); transition:transform .15s ease, filter .15s ease, background .15s ease, border-color .15s ease;
  }
  .btn:hover{ transform:translateY(-1px); filter:brightness(.98); }
  .btn.small{ padding:.45rem .7rem; font-size:.9rem }
  .btn.block{ width:100%; justify-content:center; }

  .btn-primary{ --btn-bg:var(--brand); --btn-fg:#fff; --btn-bd:var(--brand); }
  .btn-primary:hover{ background:var(--brand-600); border-color:var(--brand-600); }

  .btn-secondary{ --btn-bg:#fff; --btn-fg:#0f172a; --btn-bd:var(--border); }
  .btn-secondary:hover{ background:#f1f5f9; }

  .btn-danger{ --btn-bg:var(--red); --btn-fg:#fff; --btn-bd:var(--red); }
  .btn-danger:hover{ background:var(--red-600); border-color:var(--red-600); }

  .btn-warning{ --btn-bg:var(--amber); --btn-fg:#fff; --btn-bd:var(--amber); }
  .btn-warning:hover{ background:var(--amber-600); border-color:var(--amber-600); }

  .btn-outline-primary{ --btn-bg:#fff; --btn-fg:var(--brand-600); --btn-bd:var(--brand-600); }
  .btn-outline-primary:hover{ background:#eef2ff; }

  /* ---------- Cards / Tabelas ---------- */
  .card{background:var(--card);border:1px solid var(--border);border-radius:14px;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}
  .table{width:100%;border-collapse:separate;border-spacing:0}
  .table thead th{background:#f8fafc;color:#334155;font-size:.9rem;text-align:left;padding:.75rem .7rem;border-bottom:1px solid var(--border)}
  .table td{padding:.7rem .7rem;border-bottom:1px solid var(--border);vertical-align:middle}
  .row-actions{display:flex;gap:8px;flex-wrap:wrap}
  .badge{display:inline-block;padding:.22rem .6rem;border-radius:999px;font-weight:700;font-size:.78rem}
  .b-green{background:var(--green-100);color:var(--green-600)} .b-gray{background:#e5e7eb;color:#374151}
  .toast{position:fixed;right:16px;bottom:16px;background:#111827;color:#fff;padding:.7rem .9rem;border-radius:10px;box-shadow:var(--shadow)}

  /* ---------- Modal ---------- */
  .modal{position:fixed;inset:0;display:none;z-index:40}
  .modal.open{display:block}
  .modal .overlay{position:absolute;inset:0;background:rgba(15,23,42,.45);backdrop-filter:blur(2px)}
  .modal .card{position:relative;z-index:41;max-width:980px;margin:4vh auto;background:#fff;border:1px solid var(--border);border-radius:16px;box-shadow:var(--shadow)}
  .modal .hd{padding:14px 16px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between}
  .modal .bd{padding:14px 16px;max-height:72vh;overflow:auto}
  .close{background:transparent;border:0;font-size:22px;cursor:pointer;color:#0f172a;line-height:1}
  .tabs{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px}
  .tab-btn{border:1px solid var(--border);background:#fff;border-radius:10px;padding:.45rem .7rem;font-weight:700;cursor:pointer}
  .tab-btn.active{background:var(--brand);color:#fff;border-color:var(--brand)}
  .tab{display:none}.tab.active{display:block}
  label{font-weight:700;font-size:.9rem;color:#1f2937;display:block;margin-bottom:6px}
  input,select,textarea{width:100%;border:2px solid var(--border);border-radius:10px;padding:.55rem .7rem;font-size:1rem;outline:none;background:#fff}
  textarea{min-height:120px}
  input:focus,select:focus,textarea:focus{border-color:var(--brand);box-shadow:0 0 0 3px rgba(37,99,235,.15)}
  .grid2{display:grid;grid-template-columns:1fr 1fr;gap:12px}
  .grid3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px}
  .grid4{display:grid;grid-template-columns:1fr 1fr 1fr auto;gap:12px} /* novo para a Mesa */
  @media(max-width:980px){ .grid4{grid-template-columns:1fr 1fr} }
  @media(max-width:720px){ .grid2,.grid3,.grid4{grid-template-columns:1fr} }

  .mini-table{width:100%;border-collapse:collapse;margin-top:8px}
  .mini-table th,.mini-table td{border-bottom:1px solid var(--border);padding:.45rem .4rem;text-align:left}

  /* ---------- Responsivo (lista como cartões) ---------- */
  @media (max-width:780px){
    .header-inner{gap:8px}
    .actions{width:100%; display:flex; gap:8px; justify-content:flex-end}
    .table thead{display:none}
    .table, .table tbody, .table tr, .table td{display:block; width:100%}
    .table tr{border-bottom:1px solid var(--border); padding:.6rem .7rem}
    .table td{border:0; padding:.45rem 0; display:flex; align-items:center; justify-content:space-between; gap:10px}
    .table td::before{
      content: attr(data-label);
      font-weight:800; color:#475569;
    }
    .row-actions{gap:6px}
    .row-actions .btn{width:100%; justify-content:center}
  }
</style>
</head>
<body>

<header class="header">
  <div class="header-inner">
    <div class="brand" style="display:flex;align-items:center;gap:10px">
      <a class="btn btn-secondary" href="<?= BASE ?>/admin.php"><i class="fa fa-arrow-left"></i> Voltar</a>
      <div class="title">Legislaturas</div>
    </div>
    <div class="actions">
      <a class="btn btn-primary" id="btnNova" href="#"><i class="fa fa-plus"></i> Adicionar</a>
    </div>
  </div>
</header>

<div class="wrap">
  <?php if($msg): ?><div class="toast" id="toast"><?=h($msg)?></div><?php endif; ?>

  <div class="card">
    <div class="hd"><strong><i class="fa fa-table"></i> Lista</strong></div>
    <div class="bd" style="padding:0">
      <table class="table" id="tblLeg">
        <thead>
          <tr>
            <th style="width:100px">Número</th>
            <th>Período</th>
            <th style="width:160px">Início</th>
            <th style="width:160px">Término</th>
            <th style="width:320px">Ações</th>
          </tr>
        </thead>
        <tbody>
          <?php if(!$lista): ?>
          <tr><td colspan="5" class="muted" style="padding:16px">Nenhum registro.</td></tr>
          <?php else: foreach($lista as $r): ?>
          <tr data-id="<?= (int)$r['id'] ?>">
            <td data-label="Número"><?= (int)$r['numero'] ?></td>
            <td data-label="Período"><?= h($r['periodo']) ?></td>
            <td data-label="Início"><?= h(date('d/m/Y', strtotime($r['data_inicio']))) ?></td>
            <td data-label="Término"><?= h(date('d/m/Y', strtotime($r['data_fim']))) ?></td>
            <td data-label="Ações">
              <div class="row-actions">
                <button class="btn btn-outline-primary small btn-edit" type="button"><i class="fa fa-pen"></i> Editar</button>
                <a class="btn btn-danger small"
                   onclick="return confirm('Excluir esta legislatura?');"
                   href="<?= BASE ?>/actions.php?op=leg_excluir&id=<?= (int)$r['id'] ?>">
                  <i class="fa fa-trash"></i> Excluir
                </a>
              </div>
            </td>
          </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- MODAL -->
<div class="modal" id="modalLeg" aria-hidden="true" role="dialog" aria-modal="true">
  <div class="overlay" data-close></div>
  <div class="card" role="document" aria-labelledby="legTitle">
    <div class="hd">
      <h3 id="legTitle"><i class="fa fa-landmark"></i> Legislatura</h3>
      <button class="close" type="button" data-close aria-label="Fechar">&times;</button>
    </div>
    <div class="bd">
      <div class="tabs">
        <button class="tab-btn active" data-tab="dados">Dados básicos</button>
        <button class="tab-btn" data-tab="veread">Vereadores</button>
        <button class="tab-btn" data-tab="mesa">Mesa diretora</button>
      </div>

      <!-- Dados básicos -->
      <div class="tab active" id="tab-dados">
        <form id="formLeg" method="post" action="<?= BASE ?>/actions.php?op=leg_salvar">
          <input type="hidden" name="id" id="leg_id">
          <div class="grid2">
            <div>
              <label>Número da legislatura</label>
              <input name="numero" id="leg_numero" required>
            </div>
            <div>
              <label>Período de Vigência</label>
              <input name="periodo" id="leg_periodo" placeholder="Ex.: 2025/2028">
            </div>
          </div>
          <div class="grid2" style="margin-top:12px">
            <div>
              <label>Data início</label>
              <input type="date" name="data_inicio" id="leg_inicio" required>
            </div>
            <div>
              <label>Data fim</label>
              <input type="date" name="data_fim" id="leg_fim" required>
            </div>
          </div>
          <div style="margin-top:14px;display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap">
            <button class="btn btn-secondary" type="button" data-close><i class="fa fa-xmark"></i> Cancelar</button>
            <button class="btn btn-primary" type="submit"><i class="fa fa-save"></i> Salvar</button>
          </div>
        </form>
      </div>

      <!-- Vereadores -->
      <div class="tab" id="tab-veread">
        <form class="grid3" id="formAddVereador">
          <input type="hidden" name="leg_id" id="lv_leg_id">
          <div>
            <label>Vereador</label>
            <select name="vereador_id" id="lv_vereador">
              <?php foreach($vereadores as $v): ?>
                <option value="<?= (int)$v['id'] ?>"><?= h($v['nome']) ?><?= $v['partido'] ? ' — '.h($v['partido']) : '' ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label>&nbsp;</label>
            <button class="btn btn-primary" type="submit"><i class="fa fa-plus"></i> Adicionar</button>
          </div>
        </form>
        <table class="mini-table" id="tblLv" style="margin-top:10px">
          <thead><tr><th>Vereador</th><th style="width:120px">Ações</th></tr></thead>
          <tbody><tr><td class="muted" colspan="2">—</td></tr></tbody>
        </table>
      </div>

      <!-- Mesa Diretora -->
      <div class="tab" id="tab-mesa">
        <form class="grid4" id="formAddMesa">
          <input type="hidden" name="leg_id" id="lm_leg_id">
          <div>
            <label>Vereador</label>
            <select name="vereador_id" id="lm_vereador">
              <?php foreach($vereadores as $v): ?>
                <option value="<?= (int)$v['id'] ?>"><?= h($v['nome']) ?><?= $v['partido'] ? ' — '.h($v['partido']) : '' ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label>Cargo</label>
            <select name="cargo" id="lm_cargo">
              <option>Presidente</option>
              <option>Vice-Presidente</option>
              <option>1º Secretário</option>
              <option>2º Secretário</option>
              <option>3º Secretário</option>
            </select>
          </div>
          <div>
            <label>Sessão Legislativa (opcional)</label>
            <select name="sessao_legislativa" id="lm_sessao_leg">
              <option value="">— Selecionar (opcional)</option>
              <option value="1ª Sessão Legislativa">1ª Sessão Legislativa</option>
              <option value="2ª Sessão Legislativa">2ª Sessão Legislativa</option>
              <option value="3ª Sessão Legislativa">3ª Sessão Legislativa</option>
              <option value="4ª Sessão Legislativa">4ª Sessão Legislativa</option>
            </select>
          </div>
          <div>
            <label>&nbsp;</label>
            <button class="btn btn-primary" type="submit"><i class="fa fa-plus"></i> Adicionar</button>
          </div>
        </form>
        <table class="mini-table" id="tblLm" style="margin-top:10px">
          <thead>
            <tr>
              <th>Vereador</th>
              <th>Cargo</th>
              <th>Sessão Leg.</th>
              <th style="width:120px">Ações</th>
            </tr>
          </thead>
          <tbody><tr><td class="muted" colspan="4">—</td></tr></tbody>
        </table>
      </div>

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

<script>
document.addEventListener('DOMContentLoaded', () => {
  const toast = document.getElementById('toast');
  if (toast){ setTimeout(()=> toast.remove(), 2200); }

  function wireModal(modalEl, opener){
    const closeEls = modalEl.querySelectorAll('[data-close], .overlay');
    function open(){ modalEl.classList.add('open'); modalEl.setAttribute('aria-hidden','false'); document.body.style.overflow='hidden'; }
    function close(){ modalEl.classList.remove('open'); modalEl.setAttribute('aria-hidden','true'); document.body.style.overflow=''; }
    if (opener) opener.addEventListener('click', (ev)=>{ ev.preventDefault(); open(); });
    closeEls.forEach(el => el.addEventListener('click', close));
    document.addEventListener('keydown', (e)=>{ if (e.key==='Escape' && modalEl.classList.contains('open')) close(); });
    return { open, close };
  }

  const modalLeg = document.getElementById('modalLeg');
  const btnNova  = document.getElementById('btnNova');
  const modalCtrl = wireModal(modalLeg, btnNova);

  function setActiveTab(key){
    document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));
    document.querySelectorAll('.tab').forEach(t=>t.classList.remove('active'));
    const btn = [...document.querySelectorAll('.tab-btn')].find(b => b.dataset.tab === key) || document.querySelector('.tab-btn');
    const tab = document.getElementById('tab-'+(key||'dados'));
    btn && btn.classList.add('active');
    tab && tab.classList.add('active');
  }
  document.querySelectorAll('.tab-btn').forEach(btn=>{
    btn.addEventListener('click', ()=> setActiveTab(btn.dataset.tab));
  });

  // limpar e abrir NOVA
  btnNova?.addEventListener('click', (e)=>{
    e.preventDefault();
    document.getElementById('legTitle').textContent = 'Nova Legislatura';
    ['leg_id','leg_numero','leg_periodo','leg_inicio','leg_fim'].forEach(id=>{ const el=document.getElementById(id); if(el) el.value=''; });
    document.getElementById('lv_leg_id').value = '';
    document.getElementById('lm_leg_id').value = '';
    setLists({vereadores:[], mesa:[], row:{id:''}});
    setActiveTab('dados');
    modalCtrl.open();
  });

  async function openEditById(id, tabToFocus){
    id = parseInt(id,10);
    if(!id || isNaN(id)){ return; }
    const url = new URL('<?= BASE ?>/actions.php', location.origin);
    url.searchParams.set('op','leg_info'); url.searchParams.set('id', String(id));
    try{
      const r = await fetch(url, {cache:'no-store'}); const data = await r.json();
      if(!data || !data.ok){ alert('Falha ao carregar.'); return; }
      document.getElementById('legTitle').textContent = `Legislatura ${data.row.periodo||''}`;
      document.getElementById('leg_id').value = data.row.id||'';
      document.getElementById('leg_numero').value = data.row.numero||'';
      document.getElementById('leg_periodo').value = data.row.periodo||'';
      document.getElementById('leg_inicio').value = (data.row.data_inicio||'').slice(0,10);
      document.getElementById('leg_fim').value    = (data.row.data_fim||'').slice(0,10);
      document.getElementById('lv_leg_id').value = data.row.id;
      document.getElementById('lm_leg_id').value = data.row.id;
      setLists(data);
      setActiveTab(tabToFocus || 'dados');
      modalCtrl.open();
    }catch(e){ console.error(e); alert('Falha ao carregar.'); }
  }

  document.getElementById('tblLeg')?.addEventListener('click', (ev)=>{
    const btn = ev.target.closest('.btn-edit'); if(!btn) return;
    const tr = btn.closest('tr'); if(!tr) return;
    openEditById(tr.dataset.id);
  });

  function esc(s){ return String(s??'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
  window.setLists = function(payload){
    const tbV = document.querySelector('#tblLv tbody');
    tbV.innerHTML = (payload.vereadores && payload.vereadores.length)
      ? payload.vereadores.map(v => `
        <tr>
          <td>${esc(v.nome)}${v.partido? ' — '+esc(v.partido):''}</td>
          <td><a class="btn btn-danger small" href="<?= BASE ?>/actions.php?op=leg_del_vereador&id=${v.id}&leg_id=${payload.row?.id||''}&tab=veread&reopen=${payload.row?.id||''}"><i class="fa fa-trash"></i> Remover</a></td>
        </tr>`).join('')
      : `<tr><td class="muted" colspan="2">Nenhum vereador vinculado.</td></tr>`;

    const tbM = document.querySelector('#tblLm tbody');
    tbM.innerHTML = (payload.mesa && payload.mesa.length)
      ? payload.mesa.map(m => `
        <tr>
          <td>${esc(m.nome)}${m.partido? ' — '+esc(m.partido):''}</td>
          <td>${esc(m.cargo||'')}</td>
          <td>${esc(m.sessao_legislativa || '') || '—'}</td>
          <td><a class="btn btn-danger small" href="<?= BASE ?>/actions.php?op=leg_del_mesa&id=${m.id}&leg_id=${payload.row?.id||''}&tab=mesa&reopen=${payload.row?.id||''}"><i class="fa fa-trash"></i> Remover</a></td>
        </tr>`).join('')
      : `<tr><td class="muted" colspan="4">Nenhum membro na mesa.</td></tr>`;
  }

  function submitTo(op, formEl, tab){
    const fd = new FormData(formEl);
    const params = new URLSearchParams(fd);
    const legId = params.get('leg_id') || '';
    params.set('tab', tab||'dados');
    params.set('reopen', legId);
    location.href = '<?= BASE ?>/actions.php?op='+op+'&'+params.toString();
  }
  document.getElementById('formAddVereador')?.addEventListener('submit', (e)=>{ e.preventDefault(); submitTo('leg_add_vereador', e.currentTarget, 'veread'); });
  document.getElementById('formAddMesa')?.addEventListener('submit', (e)=>{ e.preventDefault(); submitTo('leg_add_mesa', e.currentTarget, 'mesa'); });

  // Reabrir automaticamente se vier com ?reopen=ID (&tab=...)
  const qs = new URLSearchParams(location.search);
  const reopenId = parseInt(qs.get('reopen') || '0', 10);
  const tab = qs.get('tab');
  if (reopenId > 0) { openEditById(reopenId, tab||'dados'); }
});
</script>
</body>
</html>
