<?php
// admin/admin_atas.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; }

/* ------------ Sessões para vincular (todas, mais recentes primeiro) ------------- */
$sessoes = $pdo->query("
  SELECT id, tipo, numero, status, DATE_FORMAT(data_sessao,'%d/%m/%Y') AS data_fmt
  FROM sessoes
  ORDER BY data_sessao DESC, id DESC
")->fetchAll();

/* Coluna sessao_id permite NULL? Se não permitir, vínculo é obrigatório */
$colSessao = $pdo->query("SHOW COLUMNS FROM atas LIKE 'sessao_id'")->fetch(PDO::FETCH_ASSOC) ?: [];
$sessaoAceitaNull = (strtoupper($colSessao['Null'] ?? 'NO') === 'YES');

/* ------------ Lista de atas ------------- */
$q = $pdo->query("
  SELECT a.*, s.tipo, s.numero, DATE_FORMAT(s.data_sessao,'%d/%m/%Y') AS s_data
  FROM atas a
  LEFT JOIN sessoes s ON s.id = a.sessao_id
  ORDER BY a.created_at DESC, a.id DESC
");
$atas = $q->fetchAll();

$msg = $_GET['msg'] ?? null;

/* ------------ Dados do form (edição) ------------- */
$id  = (int)($_GET['id'] ?? 0);
$row = ['id'=>'','sessao_id'=>'','titulo'=>'','resumo'=>'','texto_html'=>'','pdf_path'=>'','publicar_site'=>1,'data_ata'=>''];
if ($id) {
  $st = $pdo->prepare("SELECT * FROM atas WHERE id=:id");
  $st->execute([':id'=>$id]);
  if ($st->rowCount()) { $row = $st->fetch(); }
}

/* helper de escape */
if (!function_exists('h')) {
  function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}
?>
<!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="/arapiraca/assets/style.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<title>Atas (lançamento manual)</title>
<style>
  :root{
    --bg-grad-a:#eef2ff; --bg-grad-b:#f5f3ff; --card-bg:#ffffff;
    --border:#e5e7eb; --text:#0f172a; --muted:#64748b;
    --brand:#2563eb; --brand-2:#1d4ed8; --brand-3:#dbeafe;
    --amber:#f59e0b; --amber-2:#d97706; --amber-3:#fff7ed;
    --red:#ef4444; --red-2:#dc2626;
    --shadow: 0 10px 30px rgba(2,6,23,.06);
  }
  body{
    font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial;
    background:
      radial-gradient(1200px 600px at 10% -10%, var(--bg-grad-a), transparent),
      radial-gradient(1200px 600px at 110% 0%, var(--bg-grad-b), transparent),
      #f8fafc;
    color: var(--text);
    min-height: 100vh;
  }
  .header{
    position:sticky; top:0; z-index:10;
    background:rgba(255,255,255,.86);
    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; gap:14px; flex-wrap:wrap;
  }
  .header-inner .grow{ flex:1 1 auto; }
  .title{ font-weight:800; font-size:1.15rem; }
  .wrap{ max-width:1200px; margin:18px auto; padding:0 16px; }

  .btn{
    display:inline-flex; align-items:center; gap:8px;
    background:var(--brand); color:#fff; border-radius:12px;
    padding:.6rem .95rem; font-weight:800; border:0; cursor:pointer;
    box-shadow:var(--shadow); transition:.15s; text-decoration:none;
  }
  .btn:hover{ background:var(--brand-2); transform: translateY(-1px); }
  .btn.outline{ background:#fff; color:var(--brand); border:1px solid var(--brand); }
  .btn.outline:hover{ background:var(--brand-3); }
  .btn.warning{ background:var(--amber); }
  .btn.warning:hover{ background:var(--amber-2); }
  .btn.danger{ background:var(--red); }
  .btn.danger:hover{ background:var(--red-2); }

  .card{ background:#fff; 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; gap:10px; }
  .card .bd{ padding:16px; }

  label{ font-weight:800; font-size:.9rem; color:#1f2937; display:block; margin-bottom:6px; }
  input, select, textarea{ border:2px solid var(--border); border-radius:10px; padding:.6rem .75rem; font-size:1rem; outline:none; width:100%; }
  input:focus, select:focus, textarea:focus{ border-color: var(--brand); box-shadow: 0 0 0 3px rgba(37,99,235,.12); }
  textarea{ min-height:120px; }

  .grid2{ display:grid; grid-template-columns:1fr 1fr; gap:12px; }
  .grid3{ display:grid; grid-template-columns:1fr 1fr 1fr; gap:12px; }
  @media(max-width:760px){ .grid2,.grid3{ grid-template-columns:1fr; } }

  .table{ width:100%; border-collapse:collapse; }
  .table th, .table td{ padding:.72rem .7rem; border-bottom:1px solid var(--border); text-align:left; vertical-align: top; }
  .table thead th{ background:#f8fafc; color:#334155; font-size:.9rem; }
  .muted{ color:var(--muted); }
  .toast{ position:fixed; right:16px; bottom:16px; background:#111827; color:#fff; padding:.7rem .9rem; border-radius:10px; box-shadow:var(--shadow); display:none; }
  .toast.show{ display:block; }

  .chips{ display:flex; gap:8px; flex-wrap:wrap; }
  .chip{ display:inline-flex; align-items:center; gap:8px; border-radius:9999px; padding:.52rem .9rem; font-weight:800; border:1px solid transparent; text-decoration:none; cursor:pointer; transition:.15s; }
  .chip i{ font-size:.95rem; }
  .chip.sm{ padding:.46rem .8rem; font-size:.95rem; }
  .chip.blue-outline{ background:#fff; color:var(--brand-2); border-color:var(--brand-2); }
  .chip.blue-outline:hover{ background:var(--brand-3); }
  .chip.blue-solid{ background:var(--brand); color:#fff; border-color:var(--brand); }
  .chip.blue-solid:hover{ background:var(--brand-2); }
  .chip.amber{ background:var(--amber); color:#fff; border-color:var(--amber); }
  .chip.amber:hover{ background:var(--amber-2); }
  .chip.red{ background:var(--red); color:#fff; border-color:var(--red); }
  .chip.red:hover{ background:var(--red-2); }

  @media (max-width: 800px){
    .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; }
    .table td[data-label]::before{
      content: attr(data-label) ": ";
      font-weight:800; color:#475569; display:inline-block; min-width: 140px;
    }
  }

  /* ========= Modal ========= */
  .modal-backdrop{
    position:fixed; inset:0; background:rgba(15,23,42,.45);
    display:none; align-items:center; justify-content:center;
    z-index:50; padding:18px;
  }
  .modal-backdrop.show{ display:flex; }
  .modal{
    width:min(980px, 100%);
    background:#fff; border-radius:16px; border:1px solid var(--border);
    box-shadow: 0 20px 60px rgba(2,6,23,.25); overflow:hidden;
  }
  .modal .modal-hd{
    display:flex; align-items:center; justify-content:space-between;
    padding:14px 16px; border-bottom:1px solid var(--border);
    background:#f8fafc;
  }
  .modal .modal-bd{ padding:16px; max-height:70vh; overflow:auto; }
  .modal .modal-ft{
    display:flex; gap:10px; justify-content:flex-end;
    padding:12px 16px; border-top:1px solid var(--border); background:#fff;
  }
  .icon-btn{
    background:transparent; border:0; cursor:pointer; padding:8px; border-radius:8px;
  }
  .icon-btn:hover{ background:#eef2ff; }
</style>
</head>
<body>

<header class="header">
  <div class="header-inner">
    <a class="btn outline" href="/arapiraca/admin.php"><i class="fa fa-arrow-left"></i> Voltar</a>
    <div class="title">Atas (lançamento manual)</div>
    <div class="grow"></div>
    <button class="btn" id="btnNova"><i class="fa fa-plus"></i> Nova Ata</button>
    <a class="btn outline" href="/arapiraca/admin_atas.php"><i class="fa fa-rotate"></i> Atualizar</a>
  </div>
</header>

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

  <!-- ===== Lista ===== -->
  <div class="card">
    <div class="hd">
      <strong><i class="fa fa-list"></i> Atas cadastradas</strong>
    </div>
    <div class="bd" style="padding:0">
      <table class="table">
        <thead>
          <tr>
            <th style="width:70px">#</th>
            <th>Título</th>
            <th style="width:200px">Sessão</th>
            <th style="width:110px">Publicado</th>
            <th style="width:320px">Ações</th>
          </tr>
        </thead>
        <tbody>
          <?php if(!$atas): ?>
            <tr><td colspan="5" class="muted" style="padding:14px">Nenhuma ata.</td></tr>
          <?php else: foreach($atas as $a): ?>
            <tr>
              <td data-label="#"><?= (int)$a['id'] ?></td>
              <td data-label="Título">
                <div><strong><?= h($a['titulo']) ?></strong></div>
                <?php if(!empty($a['resumo'])): ?><div class="muted"><?= h(mb_strimwidth($a['resumo'],0,140,'…')) ?></div><?php endif; ?>
              </td>
              <td data-label="Sessão">
                <?php if($a['sessao_id']): ?>
                  #<?= (int)$a['sessao_id'] ?><br>
                  <?= h(($a['tipo']??'').' '.($a['numero']??'')) ?><br>
                  <span class="muted"><?= h($a['s_data']??'') ?></span>
                <?php else: ?>
                  <span class="muted">—</span>
                <?php endif; ?>
              </td>
              <td data-label="Publicado"><?= (int)$a['publicar_site'] ? 'Sim' : 'Não' ?></td>
              <td data-label="Ações">
                <div class="chips">
                  <!-- Mantemos o link com ?id=... para autoabrir modal preenchido -->
                  <a class="chip blue-outline" href="/arapiraca/admin_atas.php?id=<?= (int)$a['id'] ?>"><i class="fa fa-pen"></i> Editar</a>
                  <a class="chip amber" href="/arapiraca/actions.php?op=ata_toggle_publicar&id=<?= (int)$a['id'] ?>">
                    <i class="fa fa-eye<?= (int)$a['publicar_site']?'-slash':'' ?>"></i> <?= (int)$a['publicar_site'] ? 'Não publicar' : 'Publicar' ?>
                  </a>
                  <?php if($a['pdf_path']): ?>
                    <a class="chip blue-outline" target="_blank" href="<?= '/arapiraca/' . ltrim($a['pdf_path'],'/') ?>"><i class="fa fa-file-pdf"></i> PDF</a>
                  <?php endif; ?>
                  <a class="chip red" onclick="return confirm('Excluir esta ata?');"
                     href="/arapiraca/actions.php?op=ata_excluir&id=<?= (int)$a['id'] ?>"><i class="fa fa-trash"></i> Excluir</a>
                </div>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- ===== Modal de Cadastro/Edição ===== -->
<div class="modal-backdrop" id="modalAtas" aria-hidden="true" role="dialog" aria-modal="true">
  <div class="modal" role="document" aria-labelledby="modalTitle">
    <div class="modal-hd">
      <strong id="modalTitle"><i class="fa fa-file-lines"></i> <?= $row['id'] ? 'Editar Ata #'.(int)$row['id'] : 'Nova Ata' ?></strong>
      <button class="icon-btn" id="btnClose" aria-label="Fechar"><i class="fa fa-xmark"></i></button>
    </div>

    <form id="formAta" method="post" action="/arapiraca/actions.php?op=ata_salvar" enctype="multipart/form-data">
      <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
      <div class="modal-bd">
        <div class="grid2">
          <div>
            <label for="titulo">Título</label>
            <input id="titulo" name="titulo" required value="<?= h($row['titulo']) ?>">
          </div>
          <div>
            <label for="sessao_id">Vincular à Sessão <?= $sessaoAceitaNull ? '(opcional)' : '(obrigatório)' ?></label>
            <select id="sessao_id" name="sessao_id" <?= $sessaoAceitaNull ? '' : 'required' ?>>
              <?php if ($sessaoAceitaNull): ?>
                <option value="">— sem vínculo —</option>
              <?php else: ?>
                <option value="" disabled <?= $row['sessao_id'] ? '' : 'selected' ?>>— selecione uma sessão —</option>
              <?php endif; ?>
              <?php foreach($sessoes as $s): ?>
                <option value="<?= (int)$s['id'] ?>" <?= ((int)$row['sessao_id']===(int)$s['id'])?'selected':'' ?>>
                  #<?= (int)$s['id'] ?> — <?= h($s['tipo']) ?> nº <?= h($s['numero']) ?> — <?= h($s['data_fmt']) ?><?= $s['status'] ? ' ('.h($s['status']).')' : '' ?>
                </option>
              <?php endforeach; ?>
            </select>
            <?php if(!$sessaoAceitaNull): ?>
              <div class="muted" style="font-size:.9rem;margin-top:6px">
                * O vínculo é obrigatório porque <code>atas.sessao_id</code> não permite <em>NULL</em>.
              </div>
            <?php endif; ?>
          </div>
        </div>

        <div class="grid3" style="margin-top:12px">
          <?php if (array_key_exists('data_ata', $row)): ?>
          <div>
            <label for="data_ata">Data da ata (opcional)</label>
            <input id="data_ata" type="date" name="data_ata" value="<?= h($row['data_ata']) ?>">
          </div>
          <?php endif; ?>
          <div>
            <label for="publicar_site">Publicar no site?</label>
            <select id="publicar_site" name="publicar_site">
              <option value="1" <?= ((int)$row['publicar_site']===1)?'selected':'' ?>>Sim</option>
              <option value="0" <?= ((int)$row['publicar_site']===0)?'selected':'' ?>>Não</option>
            </select>
          </div>
          <div></div>
        </div>

        <label style="margin-top:12px" for="resumo">Resumo (curto)</label>
        <textarea id="resumo" name="resumo" placeholder="Resumo da ata para listagem..."><?= h($row['resumo']) ?></textarea>

        <label style="margin-top:12px" for="texto_html">Conteúdo (HTML opcional — para “ver online”)</label>
        <textarea id="texto_html" name="texto_html" placeholder="Cole aqui o HTML ou o texto formatado..."><?= h($row['texto_html']) ?></textarea>

        <div class="grid2" style="margin-top:12px; align-items:end">
          <div>
            <label for="pdf">Anexo PDF (opcional)</label>
            <input id="pdf" type="file" name="pdf" accept="application/pdf">
            <?php if(!empty($row['pdf_path'])): ?>
              <div class="muted" style="margin-top:6px">
                Atual: <a href="<?= '/arapiraca/' . ltrim($row['pdf_path'],'/') ?>" target="_blank">abrir PDF</a>
              </div>
            <?php endif; ?>
          </div>
          <div></div>
        </div>
      </div>

      <div class="modal-ft">
        <button class="btn outline" type="button" id="btnReset"><i class="fa fa-eraser"></i> Limpar</button>
        <button class="btn" type="submit"><i class="fa fa-save"></i> Salvar</button>
      </div>
    </form>
  </div>
</div>

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

  const modal=document.getElementById('modalAtas');
  const btnNova=document.getElementById('btnNova');
  const btnClose=document.getElementById('btnClose');
  const form=document.getElementById('formAta');
  const btnReset=document.getElementById('btnReset');

  function openModal(){
    modal.classList.add('show');
    modal.setAttribute('aria-hidden','false');
    // Foca o primeiro campo
    const first=form.querySelector('input,select,textarea');
    if(first){ first.focus(); }
    // Bloqueia rolagem do body
    document.body.style.overflow='hidden';
  }
  function closeModal(){
    modal.classList.remove('show');
    modal.setAttribute('aria-hidden','true');
    document.body.style.overflow='';
  }
  function clearFormForNew(){
    // Limpa os campos para NOVA ATA (sem recarregar)
    form.querySelector('[name="id"]').value='';
    form.querySelector('[name="titulo"]').value='';
    const selSess=form.querySelector('[name="sessao_id"]');
    if(selSess){ selSess.value=''; }
    const dt=form.querySelector('[name="data_ata"]');
    if(dt){ dt.value=''; }
    form.querySelector('[name="publicar_site"]').value='1';
    form.querySelector('[name="resumo"]').value='';
    form.querySelector('[name="texto_html"]').value='';
    const pdf=form.querySelector('[name="pdf"]');
    if(pdf){ pdf.value=''; }
    // Atualiza título do modal
    const title=document.getElementById('modalTitle');
    if(title){ title.textContent='Nova Ata'; }
  }

  // Abre modal em "Nova Ata"
  if(btnNova){
    btnNova.addEventListener('click', (e)=>{
      e.preventDefault();
      clearFormForNew();
      openModal();
    });
  }

  // Fecha modal
  if(btnClose){ btnClose.addEventListener('click', closeModal); }
  modal.addEventListener('click', (e)=>{
    if(e.target === modal){ closeModal(); }
  });
  document.addEventListener('keydown', (e)=>{
    if(e.key === 'Escape' && modal.classList.contains('show')) closeModal();
  });

  // Botão limpar
  if(btnReset){
    btnReset.addEventListener('click', ()=>{
      form.reset();
    });
  }

  // Se a página veio com ?id=..., abre o modal automaticamente já preenchido pelo PHP
  <?php if ($id): ?>
    openModal();
  <?php endif; ?>
})();
</script>
</body>
</html>
