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

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

$sql = "SELECT c.id, c.client_key, c.nome, c.created_at, c.updated_at,
  f.arquivo AS ultimo_frame, f.created_at AS ultimo_frame_em,
  e.nome_evento, e.token_publico
FROM clientes c
LEFT JOIN frames f ON f.id = (
  SELECT f2.id FROM frames f2 WHERE f2.cliente_id=c.id ORDER BY f2.created_at DESC LIMIT 1
)
LEFT JOIN eventos e ON e.id = f.evento_id";

$params = [];
if ($q !== '') {
  $sql .= " WHERE c.nome LIKE ? OR c.client_key LIKE ?";
  $like = '%' . $q . '%';
  $params = [$like, $like];
}

$sql .= " ORDER BY c.id DESC LIMIT 300";

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

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

$base = app_base_path();
$icoEye = $base . '/assets/img/icon-view-blue.svg';
$icoWeb = $base . '/assets/img/icon-web.svg';
$icoList = $base . '/assets/img/icon-list.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">Clientes</h1>
    <div class="fb-sub">Registros automáticos conforme geração de frames.</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 nome ou client_key...">
      <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 style="width:260px;">Chave</th>
            <th style="width:170px;">Última atividade</th>
            <th class="text-end" style="width:210px;">Ações</th>
          </tr>
        </thead>
        <tbody>
        <?php if (!$rows): ?>
          <tr class="fb-row"><td colspan="6" class="text-muted">Nenhum cliente ainda.</td></tr>
        <?php endif; ?>
        <?php foreach ($rows as $r):
          $rel = (string)($r['ultimo_frame'] ?? '');
          $abs = $rel ? (__DIR__ . '/..' . $rel) : '';
          $exists = ($rel && $abs && file_exists($abs));
          $thumb = $exists ? build_url_path($rel) : build_url_path('/assets/img/thumb-missing.svg');
          $token = (string)($r['token_publico'] ?? '');
          $clientLink = $token ? (build_url_path('/index.php') . '?token=' . rawurlencode($token)) : '';
        ?>
          <tr class="fb-row">
            <td class="fw-semibold">#<?= (int)$r['id']; ?></td>
            <td>
              <?php if ($exists): ?>
                <a href="<?= htmlspecialchars($thumb); ?>" target="_blank" title="Abrir PNG">
                  <img src="<?= htmlspecialchars($thumb); ?>" 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($thumb); ?>" alt="thumb" title="Sem frame" 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>
              <div class="fw-bold"><?= htmlspecialchars((string)$r['nome']); ?></div>
              <?php if (!empty($r['nome_evento'])): ?>
                <div class="text-muted small">Último evento: <?= htmlspecialchars((string)$r['nome_evento']); ?></div>
              <?php endif; ?>
            </td>
            <td class="text-muted"><code><?= htmlspecialchars((string)$r['client_key']); ?></code></td>
            <td class="text-muted small">
              <?= htmlspecialchars(br_datetime((string)($r['ultimo_frame_em'] ?? $r['updated_at'] ?? $r['created_at']))); ?>
            </td>
            <td>
              <div class="fb-actions">
                <a class="fb-iconbtn blue <?= $exists ? '' : 'disabled'; ?>" title="Abrir PNG" target="_blank" href="<?= htmlspecialchars($exists ? $thumb : '#'); ?>" <?= $exists ? '' : 'onclick="return false;"'; ?>>
                  <img src="<?= htmlspecialchars($icoEye); ?>" alt="Ver">
                </a>
                <?php if ($clientLink): ?>
                  <a class="fb-iconbtn" title="Abrir link do cliente" target="_blank" href="<?= htmlspecialchars($clientLink); ?>">
                    <img src="<?= htmlspecialchars($icoWeb); ?>" alt="Web">
                  </a>
                <?php else: ?>
                  <span class="fb-iconbtn disabled" title="Sem token">
                    <img src="<?= htmlspecialchars($icoWeb); ?>" alt="Web">
                  </span>
                <?php endif; ?>
                <a class="fb-iconbtn" title="Ver frames" href="frames.php?q=<?= rawurlencode((string)$r['nome']); ?>">
                  <img src="<?= htmlspecialchars($icoList); ?>" alt="Lista">
                </a>
              </div>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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