<?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');

/* filtros simples */
$q       = trim($_GET['q'] ?? '');
$tipo_id = (int)($_GET['tipo_id'] ?? 0);
$tema_id = (int)($_GET['tema_id'] ?? 0);
$ano     = (int)($_GET['ano'] ?? 0);

$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();

/* lista */
$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);
$lista = $st->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>Legislação</title>
<style>
:root{
  --brand:#2563eb; --brand-600:#1d4ed8; --brand-100:#dbeafe;
  --red:#ef4444; --red-600:#dc2626; --red-100:#fee2e2;
  --bg:#f6f8fb; --card:#fff; --border:#e5e7eb; --text:#0f172a; --muted:#64748b;
  --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}

/* ===== 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:transform .15s ease, background .15s ease, border-color .15s ease, filter .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-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); }

/* ===== Cartões / tabela ===== */
.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}
.badge{display:inline-block;padding:.18rem .55rem;border-radius:999px;font-weight:800;font-size:.74rem;background:#eef2ff;color:#4338ca}
.toast{position:fixed;right:16px;bottom:16px;background:#111827;color:#fff;padding:.7rem .9rem;border-radius:10px;box-shadow:var(--shadow)}

/* ===== filtros ===== */
.filters{
  display:flex; gap:8px; align-items:center; flex-wrap:nowrap;
  width:100%; overflow-x:auto; padding-bottom:4px;
}
.filters-form{
  display:flex; gap:8px; align-items:center; flex-wrap:nowrap;
  flex:1 1 auto; min-width:0;
}
.filters-form input,.filters-form select{
  border:2px solid var(--border); border-radius:10px; padding:.5rem .6rem;
}
.filters-form input[name="q"]{ flex:1 1 auto; min-width:260px; }
.filters-form select{ flex:0 0 220px; }
.filters-form input[name="ano"]{ flex:0 0 110px; }

/* ===== modal / tabs ===== */
.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:900px;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;outline:none;background:#fff}
textarea{min-height:120px}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:12px}
@media(max-width:720px){ .grid2{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: tabela vira cartões ===== */
@media (max-width: 840px){
  .filters{ overflow:visible }
  .filters-form{ flex-wrap:wrap }
  .filters-form input[name="q"], .filters-form select, .filters-form input[name="ano"]{ flex:1 1 100%; min-width:0 }
  .filters-form button{ width:100% }

  .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:flex-start; justify-content:space-between; gap:10px }
  .table td::before{
    content: attr(data-label);
    font-weight:800; color:#475569; margin-right:10px; min-width:110px;
  }
  .table td:last-child{ padding-top:.6rem }
  .table td .btn{ width:100%; justify-content:center }
}
</style>
</head>
<body>

<header class="header">
  <div class="header-inner">
    <div style="display:flex;align-items:center;gap:12px">
      <a class="btn btn-secondary" href="<?=BASE?>/admin.php"><i class="fa fa-arrow-left"></i> Voltar</a>
      <strong>Legislação</strong>
    </div>
    <div class="filters">
      <form method="get" class="filters-form" action="">
        <input name="q" value="<?=h($q)?>" placeholder="nº, ementa, palavra-chave">
        <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 btn-secondary" type="submit"><i class="fa fa-magnifying-glass"></i> Filtrar</button>
      </form>
      <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-scale-balanced"></i> Normas</strong></div>
    <div class="bd" style="padding:0">
      <table class="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:260px">Ações</th>
          </tr>
        </thead>
        <tbody>
          <?php if(!$lista): ?>
            <tr><td colspan="6" style="padding:14px;color:#64748b">Nenhum registro.</td></tr>
          <?php else: foreach($lista as $r): ?>
            <tr data-id="<?=$r['id']?>">
              <td data-label="Data"><?=h(date('d/m/Y', strtotime($r['data_norma'])))?></td>
              <td data-label="Número"><?=h($r['numero'])?></td>
              <td data-label="Tipo"><?=h($r['tipo_nome'])?></td>
              <td data-label="Tema"><?=h($r['tema_nome'] ?? '—')?></td>
              <td data-label="Ementa"><?=h(mb_strimwidth($r['ementa']??'',0,80,'…','utf-8'))?></td>
              <td data-label="Ações">
                <div style="display:flex;gap:8px;flex-wrap:wrap">
                  <?php if($r['pdf_path']): ?>
                    <a class="btn btn-secondary small" target="_blank" href="<?=BASE.'/'.ltrim($r['pdf_path'],'/')?>"><i class="fa fa-file-pdf"></i> PDF</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 norma?');"
                     href="<?=BASE?>/actions.php?op=law_excluir&id=<?=$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="modalLaw" aria-hidden="true" role="dialog" aria-modal="true">
  <div class="overlay" data-close></div>
  <div class="card" role="document" aria-labelledby="lawTitle">
    <div class="hd">
      <h3 id="lawTitle"><i class="fa fa-scale-balanced"></i> Norma Jurídica</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 da Norma</button>
        <button class="tab-btn" data-tab="rel">Legislação Relacionada</button>
      </div>

      <!-- DADOS -->
      <div class="tab active" id="tab-dados">
        <form id="formLaw" method="post" enctype="multipart/form-data" action="<?=BASE?>/actions.php?op=law_salvar">
          <input type="hidden" name="id" id="law_id">
          <div class="grid2">
            <div>
              <label>Data</label>
              <input type="date" name="data_norma" id="law_data" required>
            </div>
            <div>
              <label>Número</label>
              <input name="numero" id="law_numero" required placeholder="ex.: 3.678/2024">
            </div>
          </div>

          <div class="grid2" style="margin-top:12px">
            <div>
              <label>Tipo de Norma</label>
              <select name="tipo_id" id="law_tipo" required>
                <option value="">----</option>
                <?php foreach($tipos as $t): ?>
                  <option value="<?=$t['id']?>"><?=h($t['nome'])?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div>
              <label>Tema</label>
              <select name="tema_id" id="law_tema">
                <option value="">Padrão</option>
                <?php foreach($temas as $t): ?>
                  <option value="<?=$t['id']?>"><?=h($t['nome'])?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>

          <div style="margin-top:12px">
            <label>Ementa</label>
            <textarea name="ementa" id="law_ementa"></textarea>
          </div>

          <div style="margin-top:12px">
            <label>Palavras-Chave</label>
            <textarea name="palavras" id="law_palavras" placeholder="separe por vírgula"></textarea>
          </div>

          <div style="margin-top:12px">
            <label>Arquivo PDF</label>
            <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
              <input type="file" name="pdf" accept="application/pdf">
              <span id="pdfInfo" class="badge" style="display:none"></span>
            </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>

      <!-- RELACIONADAS -->
      <div class="tab" id="tab-rel">
        <form id="formAddRel" class="grid2">
          <input type="hidden" name="origem_id" id="rel_origem">
          <div>
            <label>Buscar norma (nº, ementa)</label>
            <input id="rel_q" placeholder="Digite para buscar...">
            <div id="rel_sug" class="card" style="margin-top:6px; display:none; padding:8px"></div>
          </div>
          <div>
            <label>Tipo de relação</label>
            <select name="tipo_relacao" id="rel_tipo">
              <option value="cita">Cita</option>
              <option value="altera">Altera</option>
              <option value="revoga">Revoga</option>
              <option value="regulamenta">Regulamenta</option>
            </select>
            <div style="margin-top:8px">
              <button class="btn btn-primary" type="submit"><i class="fa fa-plus"></i> Adicionar</button>
            </div>
          </div>
        </form>

        <table class="mini-table" id="tblRel" style="margin-top:10px">
          <thead><tr><th>Relação</th><th>Norma</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 modal = document.getElementById('modalLaw');
  const btnNova = document.getElementById('btnNova');
  const modalCtrl = wireModal(modal, 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)));

  function esc(s){ return String(s??'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }

  // abrir nova
  btnNova?.addEventListener('click', (e)=>{
    e.preventDefault();
    document.getElementById('lawTitle').textContent = 'Nova Norma Jurídica';
    document.getElementById('law_id').value = '';
    document.getElementById('law_data').value = '';
    document.getElementById('law_numero').value = '';
    document.getElementById('law_tipo').value = '';
    document.getElementById('law_tema').value = '';
    document.getElementById('law_ementa').value = '';
    document.getElementById('law_palavras').value = '';
    document.getElementById('pdfInfo').style.display='none';
    document.getElementById('rel_origem').value = '';
    document.querySelector('#tblRel tbody').innerHTML = `<tr><td class="muted" colspan="3">—</td></tr>`;
    setActiveTab('dados');
    modalCtrl.open();
  });

  // abrir edição
  document.querySelector('table.table')?.addEventListener('click', async (ev)=>{
    const btn = ev.target.closest('.btn-edit'); if(!btn) return;
    const tr = btn.closest('tr'); const id = tr?.dataset?.id; if(!id) return;

    const url = new URL('<?=BASE?>/actions.php', location.origin);
    url.searchParams.set('op','law_info'); url.searchParams.set('id', id);
    try{
      const r = await fetch(url, {cache:'no-store'}); const data = await r.json();
      if(!data || !data.ok){ alert('Falha ao carregar.'); return; }
      const row = data.row;

      document.getElementById('lawTitle').textContent = `Editar Norma — ${row.numero}`;
      document.getElementById('law_id').value   = row.id || '';
      document.getElementById('law_data').value = (row.data_norma||'').slice(0,10);
      document.getElementById('law_numero').value = row.numero||'';
      document.getElementById('law_tipo').value = row.tipo_id || '';
      document.getElementById('law_tema').value = row.tema_id || '';
      document.getElementById('law_ementa').value = row.ementa || '';
      document.getElementById('law_palavras').value = row.palavras_chave || '';
      const pdfInfo = document.getElementById('pdfInfo');
      if (row.pdf_path){
        pdfInfo.style.display='inline-block';
        pdfInfo.innerHTML = `<i class="fa fa-file-pdf"></i> PDF anexado`;
      } else { pdfInfo.style.display='none'; }
      document.getElementById('rel_origem').value = row.id;

      // relações
      const tb = document.querySelector('#tblRel tbody');
      if (data.rels && data.rels.length){
        tb.innerHTML = data.rels.map(r =>
          `<tr>
            <td>${esc(r.tipo_relacao)}</td>
            <td>${esc(r.numero)} — ${esc((r.data_norma||'').slice(0,10).split('-').reverse().join('/'))}</td>
            <td><a class="btn btn-danger small" href="<?=BASE?>/actions.php?op=law_del_rel&id=${r.id}&origem=${row.id}"><i class="fa fa-trash"></i> Remover</a></td>
          </tr>`
        ).join('');
      } else {
        tb.innerHTML = `<tr><td class="muted" colspan="3">—</td></tr>`;
      }

      setActiveTab('dados');
      modalCtrl.open();
    }catch(e){ console.error(e); alert('Erro de rede.'); }
  });

  // busca para relacionar
  const relQ = document.getElementById('rel_q');
  const relSug = document.getElementById('rel_sug');
  let relTimer=null;
  relQ?.addEventListener('input', ()=>{
    clearTimeout(relTimer);
    const q = relQ.value.trim();
    if (q.length<2){ relSug.style.display='none'; relSug.innerHTML=''; return; }
    relTimer=setTimeout(async ()=>{
      const url = new URL('<?=BASE?>/actions.php', location.origin);
      url.searchParams.set('op','law_search'); url.searchParams.set('q', q);
      const r = await fetch(url); const j = await r.json();
      if (!j.ok){ relSug.style.display='none'; return; }
      relSug.style.display='block';
      relSug.innerHTML = j.rows.map(x =>
        `<div style="padding:6px 8px;border-bottom:1px solid #eee;cursor:pointer"
              data-id="${x.id}" data-label="${esc(x.numero)} — ${esc(x.data)}">
          <i class="fa fa-gavel"></i> ${esc(x.numero)} — ${esc(x.data)}<br>
          <span style="color:#64748b">${esc(x.tipo)} • ${esc(x.ementa)}</span>
        </div>`
      ).join('');
    }, 280);
  });
  let relSelectedId = 0;
  relSug?.addEventListener('click',(e)=>{
    const item = e.target.closest('div[data-id]'); if(!item) return;
    relSelectedId = parseInt(item.dataset.id,10)||0;
    relQ.value = item.dataset.label || '';
    relSug.style.display='none';
  });

  // adicionar relação
  document.getElementById('formAddRel')?.addEventListener('submit', (e)=>{
    e.preventDefault();
    const origem = document.getElementById('rel_origem').value || '';
    const tipo   = document.getElementById('rel_tipo').value || 'cita';
    if (!origem){ alert('Salve a norma antes de relacionar.'); return; }
    if (!relSelectedId){ alert('Selecione uma norma na busca.'); return; }
    location.href = `<?=BASE?>/actions.php?op=law_add_rel&origem=${origem}&rel=${relSelectedId}&tipo=${encodeURIComponent(tipo)}&reopen=${origem}&tab=rel`;
  });

  // tabs deep-link: ?reopen=ID&tab=rel
  const qs = new URLSearchParams(location.search);
  const reopen = qs.get('reopen'); const tab = qs.get('tab');
  if (reopen){
    const row = document.querySelector(`tr[data-id="${reopen}"] .btn-edit`);
    if (row) row.click();
    if (tab) setActiveTab(tab);
  }
});
</script>
</body>
</html>
