<?php
require_once __DIR__ . '/../config/bootstrap.php';
admin_require_login();
$pdo = db();

$q = trim((string)($_GET['q'] ?? ''));

if ($q !== '') {
  $st = $pdo->prepare('SELECT id, status, nome_evento, data_evento, destino, token_publico, updated_at, created_at FROM eventos WHERE nome_evento LIKE ? OR destino LIKE ? ORDER BY id DESC');
  $like = '%' . $q . '%';
  $st->execute([$like, $like]);
  $events = $st->fetchAll();
} else {
  $events = $pdo->query('SELECT id, status, nome_evento, data_evento, destino, token_publico, updated_at, created_at FROM eventos ORDER BY id DESC')->fetchAll();
}

$title = 'Admin - Eventos';
require __DIR__ . '/_partials/header.php';

$base = app_base_path();
$icoEye = $base . '/assets/img/icon-view.svg';
$icoBuilder = $base . '/assets/img/icon-builder.svg';
$icoTrash = $base . '/assets/img/icon-trash.svg';
?>

<div class="d-flex align-items-end justify-content-between mb-3">
  <div>
    <div class="fb-backwrap"><a class="fb-back" href="index.php">Voltar</a></div>
    <h1 class="fb-h1">Eventos</h1>
    <div class="fb-sub">Crie o evento (nome/data/destino) e depois monte o template no Builder.</div>
  </div>
  <button class="btn btn-primary fb-btn" data-bs-toggle="modal" data-bs-target="#modalCreate">+ Evento</button>
</div>

<div class="fb-card mb-3">
  <div class="fb-card-b">
    <form class="fb-searchbar" method="get">
      <input class="form-control fb-input" name="q" value="<?= htmlspecialchars($q); ?>" placeholder="Buscar evento...">
      <button class="btn btn-dark fb-btn" type="submit">Pesquisar</button>
    </form>
  </div>
</div>

<div class="fb-card">
  <div class="fb-card-b">
    <div class="table-responsive">
      <table class="fb-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Status</th>
            <th>Evento</th>
            <th>Data</th>
            <th>Destino</th>
            <th class="text-end">Ações</th>
          </tr>
        </thead>
        <tbody>
        <?php if (!$events): ?>
          <tr class="fb-row"><td colspan="6" class="text-muted">Nenhum evento criado ainda.</td></tr>
        <?php endif; ?>
        <?php foreach ($events as $e):
          $st = (string)$e['status'];
          $pillClass = ($st === 'published') ? 'ok' : (($st === 'archived') ? 'off' : 'draft');
          $pillText = ($st === 'published') ? 'Publicado' : (($st === 'archived') ? 'Arquivado' : 'Rascunho');
        ?>
          <tr class="fb-row">
            <td class="fw-semibold">#<?= (int)$e['id']; ?></td>
            <td><span class="fb-pill <?= $pillClass; ?>"><?= $pillText; ?></span></td>
            <td class="fw-bold"><?= htmlspecialchars((string)$e['nome_evento']); ?></td>
            <td class="text-muted"><?= htmlspecialchars(br_date((string)$e['data_evento'])); ?></td>
            <td class="text-muted"><?= htmlspecialchars((string)$e['destino']); ?></td>
            <td>
              <div class="fb-actions">
                <?php if ($st === 'published'): ?>
                  <a class="fb-iconbtn gray" title="Abrir link do cliente" target="_blank" href="<?= $base; ?>/index.php?token=<?= htmlspecialchars((string)$e['token_publico']); ?>">
                    <img src="<?= htmlspecialchars($icoEye); ?>" alt="Ver">
                  </a>
                <?php else: ?>
                  <span class="fb-iconbtn gray" title="Link disponível apenas quando publicado" style="opacity:.5;cursor:not-allowed;">
                    <img src="<?= htmlspecialchars($icoEye); ?>" alt="Ver">
                  </span>
                <?php endif; ?>

                <a class="fb-iconbtn orange" title="Abrir Builder" href="event_builder.php?id=<?= (int)$e['id']; ?>">
                  <img src="<?= htmlspecialchars($icoBuilder); ?>" alt="Builder">
                </a>

                <button class="fb-iconbtn red" type="button" title="Excluir" onclick="fbDeleteEvent(<?= (int)$e['id']; ?>)">
                  <img src="<?= htmlspecialchars($icoTrash); ?>" alt="Excluir">
                </button>
              </div>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Modal Create (layout próximo do PDF) -->
<div class="modal fade" id="modalCreate" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content" style="border-radius:22px;">
      <div class="modal-body p-4">
        <div class="d-flex align-items-center justify-content-between">
          <h4 class="mb-0" style="font-weight:900;">Criar novo evento / viagem</h4>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
        </div>
        <div class="text-muted mt-1">Informe os dados base para liberar o Builder.</div>

        <div class="mt-3">
          <label class="form-label fw-semibold">Nome do evento</label>
          <input id="c_nome" class="form-control fb-input" placeholder="Ex: Viagem Formatura 2026">
        </div>
        <div class="mt-3">
          <label class="form-label fw-semibold">Data</label>
          <input id="c_data" type="date" class="form-control fb-input">
        </div>
        <div class="mt-3">
          <label class="form-label fw-semibold">Destino</label>
          <input id="c_destino" class="form-control fb-input" placeholder="Ex: Jericoacoara - CE">
        </div>
        <div class="mt-3">
          <label class="form-label fw-semibold">Endereço</label>
          <input id="c_endereco" class="form-control fb-input" placeholder="Rua, número, cidade...">
        </div>

        <div id="c_err" class="alert alert-danger mt-3 d-none"></div>

        <div class="d-flex gap-2 mt-4">
          <button class="btn btn-outline-secondary fb-btn flex-fill" data-bs-dismiss="modal" type="button">Cancelar</button>
          <button id="btnCreate" class="btn btn-primary fb-btn flex-fill" type="button">Criar e abrir Builder</button>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
async function fbFetchJson(url, opts={}){
  const res = await fetch(url, opts);
  const txt = await res.text();
  try { return JSON.parse(txt); } catch(e){ return {ok:false, error:'Resposta inválida'}; }
}

document.getElementById('btnCreate').addEventListener('click', async ()=>{
  const nome_evento = (document.getElementById('c_nome').value||'').trim();
  const data_evento = (document.getElementById('c_data').value||'').trim();
  const destino = (document.getElementById('c_destino').value||'').trim();
  const endereco = (document.getElementById('c_endereco').value||'').trim();

  const err = document.getElementById('c_err');
  err.classList.add('d-none');
  err.textContent = '';

  const r = await fbFetchJson('../api/admin_create_event.php', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body: JSON.stringify({nome_evento, data_evento, destino, endereco})
  });

  if (!r.ok){
    err.textContent = r.error || 'Erro ao criar.';
    err.classList.remove('d-none');
    return;
  }
  window.location.href = 'event_builder.php?id=' + r.id;
});

async function fbDeleteEvent(id){
  if (!confirm('Excluir este evento?')) return;
  const r = await fbFetchJson('../api/admin_delete_event.php', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body: JSON.stringify({id})
  });
  if (!r.ok){ alert(r.error || 'Erro ao excluir'); return; }
  location.reload();
}
</script>

<?php require __DIR__ . '/_partials/footer.php'; ?>
