<?php
// /votacao/admin_comissao.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, nome, tipo, ativo
  FROM comissoes
  ORDER BY nome
")->fetchAll();

/* Vereadores para a composição */
$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">
<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>Comissões</title>
<style>
  :root{
    --brand:#2563eb;--brand-600:#1d4ed8;--brand-100:#dbeafe;
    --green:#22c55e;--green-600:#16a34a;--green-100:#dcfce7;
    --red:#ef4444;--red-600:#dc2626;--red-100:#fee2e2;
    --bg:#f6f8fb;--card:#fff;--border:#e5e7eb;--muted:#64748b;--text:#0f172a;
    --radius:14px;--radius-sm:10px;--shadow:0 12px 28px rgba(2,6,23,.06),0 2px 6px rgba(2,6,23,.04);
    --shadow-sm:0 6px 16px rgba(2,6,23,.06);
  }
  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)}
  .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 unificados ==== */
  .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:var(--radius-sm); padding:.55rem .9rem; font-weight:800; cursor:pointer;
    box-shadow:var(--shadow-sm); text-decoration:none; transition:.15s;
  }
  .btn:hover{filter:brightness(.98);transform:translateY(-1px)}
  .btn.small{padding:.45rem .7rem;font-size:.9rem}

  .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-outline-primary{ --btn-bg:#fff; --btn-fg:var(--brand-600); --btn-bd:var(--brand-600); }
  .btn-outline-primary:hover{ background:#eef2ff; }

  .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); }

  .card{background:var(--card);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}
  .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:var(--radius-sm);box-shadow:var(--shadow)}
  .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:var(--card);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;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}
  @media(max-width:720px){ .grid2,.grid3{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}
</style>
</head>
<body>
<header class="header">
  <div class="header-inner">
    <div class="brand">
      <a class="btn btn-secondary" href="<?= BASE ?>/admin.php"><i class="fa fa-arrow-left"></i> Voltar</a>
      <div class="title">Comissões</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="tblCom">
        <thead>
        <tr>
          <th>Nome</th>
          <th style="width:160px">Tipo</th>
          <th style="width:300px">Ações</th>
        </tr>
        </thead>
        <tbody>
        <?php if(!$lista): ?>
          <tr><td colspan="3" class="muted" style="padding:16px">Nenhum registro.</td></tr>
        <?php else: foreach($lista as $r): ?>
          <tr data-id="<?= (int)$r['id'] ?>">
            <td><?= h($r['nome']) ?></td>
            <td><?= h($r['tipo']) ?></td>
            <td>
              <div class="row-actions">
                <?php if((int)($r['ativo']??1)===1): ?>
                  <!--
                  <span class="badge b-green">Ativa</span>
                  <a class="btn btn-outline-primary small" href="<?= BASE ?>/actions.php?op=com_toggle&id=<?= (int)$r['id'] ?>&to=0"><i class="fa fa-ban"></i> Inativar</a>
                  -->
                <?php else: ?>
                  <!--
                  <span class="badge b-gray">Inativa</span>
                  <a class="btn btn-outline-primary small" href="<?= BASE ?>/actions.php?op=com_toggle&id=<?= (int)$r['id'] ?>&to=1"><i class="fa fa-check"></i> Ativar</a>
                  -->
                <?php endif; ?>

                <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 comissão?');"
                   href="<?= BASE ?>/actions.php?op=com_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="modalCom" aria-hidden="true" role="dialog" aria-modal="true">
  <div class="overlay" data-close></div>
  <div class="card" role="document" aria-labelledby="comTitle">
    <div class="hd">
      <h3 id="comTitle"><i class="fa fa-people-group"></i> Comissão</h3>
      <button class="close" type="button" data-close aria-label="Fechar">&times;</button>
    </div>
    <div class="bd">
      <!-- Abas -->
      <div class="tabs">
        <button class="tab-btn active" data-tab="dados">Dados básicos</button>
        <button class="tab-btn" data-tab="comp">Composição</button>
      </div>

      <!-- Dados básicos -->
      <div class="tab active" id="tab-dados">
        <form id="formCom" method="post" action="<?= BASE ?>/actions.php?op=com_salvar">
          <input type="hidden" name="id" id="com_id">
          <div>
            <label>Nome da comissão</label>
            <input name="nome" id="com_nome" required>
          </div>
          <div class="grid2" style="margin-top:12px">
            <div>
              <label>Tipo</label>
              <select name="tipo" id="com_tipo" required>
                <option value="">----------------------</option>
                <option>Permanente</option>
                <option>Temporária</option>
                <option>Especial</option>
                <option>CPI</option>
              </select>
            </div>
          </div>
          <div style="margin-top:12px">
            <label>Finalidade</label>
            <textarea name="finalidade" id="com_finalidade"></textarea>
          </div>
          <div style="margin-top:14px;display:flex;gap:8px;justify-content:flex-end">
            <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>

      <!-- Composição -->
      <div class="tab" id="tab-comp">
        <form class="grid3" id="formAddMembro">
          <input type="hidden" name="comissao_id" id="cm_com_id">
          <div>
            <label>Vereador</label>
            <select name="vereador_id" id="cm_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="cm_cargo">
              <option>Membro</option>
              <option>Presidente</option>
              <option>Vice-Presidente</option>
              <option>Relator</option>
              <option>Suplente</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="tblCm" style="margin-top:10px">
          <thead><tr><th>Vereador</th><th>Cargo</th><th style="width:120px">Ações</th></tr></thead>
          <tbody><tr><td class="muted" colspan="3">—</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 modalCom = document.getElementById('modalCom');
  const btnNova = document.getElementById('btnNova');
  const modalCtrl = wireModal(modalCom, 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));
  });

  // NOVA
  btnNova?.addEventListener('click', (e)=>{
    e.preventDefault();
    document.getElementById('comTitle').textContent = 'Nova Comissão';
    document.getElementById('com_id').value = '';
    document.getElementById('com_nome').value = '';
    document.getElementById('com_tipo').value = '';
    document.getElementById('com_finalidade').value = '';
    document.getElementById('cm_com_id').value = '';
    setMembers([]);
    setActiveTab('dados');
    modalCtrl.open();
  });

  // Editar
  async function openEditById(id, tabToFocus){
    const url = new URL('<?= BASE ?>/actions.php', location.origin);
    url.searchParams.set('op','com_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('comTitle').textContent = data.row.nome || 'Comissão';
      document.getElementById('com_id').value = data.row.id || '';
      document.getElementById('com_nome').value = data.row.nome || '';
      document.getElementById('com_tipo').value = data.row.tipo || '';
      document.getElementById('com_finalidade').value = data.row.finalidade || '';
      document.getElementById('cm_com_id').value = data.row.id || '';
      setMembers(data.membros||[]);
      setActiveTab(tabToFocus || 'dados');
      modalCtrl.open();
    }catch(e){ console.error(e); alert('Erro de rede.'); }
  }
  document.getElementById('tblCom')?.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);
  });

  // Render composição
  function esc(s){ return String(s??'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
  function setMembers(rows){
    const tb = document.querySelector('#tblCm tbody');
    const comId = document.getElementById('cm_com_id').value || '';
    tb.innerHTML = (rows && rows.length)
      ? rows.map(m => `
          <tr>
            <td>${esc(m.nome)}${m.partido? ' — '+esc(m.partido):''}</td>
            <td>${esc(m.cargo||'Membro')}</td>
            <td>
              <a class="btn btn-danger small" href="<?= BASE ?>/actions.php?op=com_del_membro&id=${m.id}&comissao_id=${comId}&tab=comp&reopen=${comId}">
                <i class="fa fa-trash"></i> Remover
              </a>
            </td>
          </tr>`).join('')
      : `<tr><td class="muted" colspan="3">Nenhum membro.</td></tr>`;
  }

  // Subform composição
  function submitTo(op, formEl, tab){
    const fd = new FormData(formEl);
    const params = new URLSearchParams(fd);
    const id = params.get('comissao_id') || '';
    if (!id){ alert('Salve a comissão antes de adicionar membros.'); return; }
    params.set('tab', tab||'dados');
    params.set('reopen', id);
    location.href = '<?= BASE ?>/actions.php?op='+op+'&'+params.toString();
  }
  document.getElementById('formAddMembro')?.addEventListener('submit', (e)=>{ e.preventDefault(); submitTo('com_add_membro', e.currentTarget, 'comp'); });

  // Reabrir modal após redirecionamentos
  const qs = new URLSearchParams(location.search);
  const reopenId = qs.get('reopen'); const tab = qs.get('tab');
  if (reopenId) { openEditById(reopenId, tab||'dados'); }
});
</script>
</body>
</html>
