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

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

$sql = 'SELECT f.id, f.arquivo, f.created_at,
  e.nome_evento, e.destino, e.data_evento, e.token_publico,
  c.nome AS cliente_nome
FROM frames f
JOIN eventos e ON e.id=f.evento_id
JOIN clientes c ON c.id=f.cliente_id';

$params = [];
if ($q !== '') {
  $sql .= ' WHERE c.nome LIKE ? OR e.nome_evento LIKE ? OR e.destino LIKE ?';
  $like = '%' . $q . '%';
  $params = [$like, $like, $like];
}
$sql .= ' ORDER BY f.id DESC LIMIT 200';

$st = $pdo->prepare($sql);
$st->execute($params);
$rows = $st->fetchAll();

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

$base = app_base_path();
$icoEye = $base . '/assets/img/icon-view-blue.svg';
$icoWeb = $base . '/assets/img/icon-web.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">Frames</h1>
    <div class="fb-sub">Últimos 200 registros gerados pelos clientes.</div>
  </div>
</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 por cliente, evento ou destino...">
      <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 style="width:80px;">ID</th>
            <th style="width:96px;">Thumb</th>
            <th>Cliente</th>
            <th>Evento</th>
            <th style="width:110px;">Data</th>
            <th style="width:170px;">Gerado</th>
            <th class="text-end" style="width:210px;">Ações</th>
          </tr>
        </thead>
        <tbody>
        <?php if (!$rows): ?>
          <tr class="fb-row"><td colspan="7" class="text-muted">Nenhum frame ainda.</td></tr>
        <?php endif; ?>
        <?php foreach ($rows as $r):
          $rel = (string)$r['arquivo'];
          $abs = __DIR__ . '/..' . $rel;
          $exists = ($rel !== '' && file_exists($abs));
          $img = $exists ? build_url_path($rel) : build_url_path('/assets/img/thumb-missing.svg');
          $clientLink = build_url_path('/index.php') . '?token=' . rawurlencode((string)$r['token_publico']);
        ?>
          <tr class="fb-row">
            <td class="fw-semibold">#<?= (int)$r['id']; ?></td>
            <td>
              <?php if ($exists): ?>
                <a href="<?= htmlspecialchars($img); ?>" target="_blank" title="Abrir PNG">
                  <img src="<?= htmlspecialchars($img); ?>" alt="thumb" style="width:72px;height:92px;object-fit:cover;border-radius:16px;border:1px solid rgba(0,0,0,.08);background:#f8fafc;">
                </a>
              <?php else: ?>
                <img src="<?= htmlspecialchars($img); ?>" alt="thumb" title="Arquivo não encontrado" style="width:72px;height:92px;object-fit:cover;border-radius:16px;border:1px solid rgba(0,0,0,.08);background:#f8fafc;opacity:.85;">
              <?php endif; ?>
            </td>
            <td class="fw-bold"><?= htmlspecialchars((string)$r['cliente_nome']); ?></td>
            <td>
              <div class="fw-semibold"><?= htmlspecialchars((string)$r['nome_evento']); ?></div>
              <div class="text-muted small"><?= htmlspecialchars((string)$r['destino']); ?></div>
            </td>
            <td class="text-muted"><?= htmlspecialchars(br_date((string)$r['data_evento'])); ?></td>
            <td class="text-muted small"><?= htmlspecialchars(br_datetime((string)$r['created_at'])); ?></td>
            <td>
              <div class="fb-actions">
                <a class="fb-iconbtn blue <?= $exists ? '' : 'disabled'; ?>" title="Abrir PNG" target="_blank" href="<?= htmlspecialchars($exists ? $img : '#'); ?>" <?= $exists ? '' : 'onclick="return false;"'; ?>>
                  <img src="<?= htmlspecialchars($icoEye); ?>" alt="Ver">
                </a>
                <a class="fb-iconbtn" title="Abrir link do cliente" target="_blank" href="<?= htmlspecialchars($clientLink); ?>">
                  <img src="<?= htmlspecialchars($icoWeb); ?>" alt="Web">
                </a>
                <button class="fb-iconbtn red" type="button" title="Excluir" onclick="fbDeleteFrame(<?= (int)$r['id']; ?>)">
                  <img src="<?= htmlspecialchars($icoTrash); ?>" alt="Excluir">
                </button>
              </div>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </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'}; }
}

async function fbDeleteFrame(id){
  if (!confirm('Excluir este frame?')) return;
  const r = await fbFetchJson('../api/admin_delete_frame.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'; ?>
