<?php
// api/report_data.php
require_once __DIR__ . '/../config.php';
startSecureSession();
if (empty($_SESSION['admin_id'])) { jsonOut(['error'=>'Unauthorized'], 401); }

$eventId = (int)($_GET['event_id'] ?? 0);
$db = db();

// Verify event belongs to admin
$ev = $db->prepare('SELECT id FROM events WHERE id=? AND admin_id=?');
$ev->execute([$eventId, $_SESSION['admin_id']]);
if (!$ev->fetch()) { jsonOut(['error'=>'Not found'], 404); }

$stmt = $db->prepare(
    'SELECT g.*, c.name AS checker_name
     FROM guests g LEFT JOIN checkers c ON c.id=g.checked_by
     WHERE g.event_id=? ORDER BY g.check_in_time DESC'
);
$stmt->execute([$eventId]);
$guests = $stmt->fetchAll();

$total   = count($guests);
$checked = count(array_filter($guests, fn($g) => $g['checked_in']));
$pending = $total - $checked;
$pct     = $total > 0 ? round($checked / $total * 100) : 0;

ob_start();
foreach ($guests as $i => $g):
?>
<tr>
  <td class="text-muted text-sm"><?= $i+1 ?></td>
  <td style="font-weight:500"><?= htmlspecialchars($g['name']) ?></td>
  <td>
    <?php if ($g['category']): ?>
      <span class="badge badge-gold"><?= htmlspecialchars($g['category']) ?></span>
    <?php else: ?>—<?php endif; ?>
  </td>
  <td class="text-muted text-sm"><?= htmlspecialchars($g['table_number'] ?? '—') ?></td>
  <td>
    <?php if ($g['checked_in']): ?>
      <span class="badge badge-success">✓ In</span>
    <?php else: ?>
      <span class="badge badge-muted">Pending</span>
    <?php endif; ?>
  </td>
  <td class="text-muted text-sm">
    <?= $g['check_in_time'] ? date('H:i · M j', strtotime($g['check_in_time'])) : '—' ?>
  </td>
  <td>
    <?php if ($g['check_in_method']): ?>
      <span class="badge <?= $g['check_in_method']==='qr'?'badge-info':'badge-gold' ?>">
        <?= strtoupper($g['check_in_method']) ?>
      </span>
    <?php else: ?>—<?php endif; ?>
  </td>
  <td class="text-muted text-sm"><?= htmlspecialchars($g['checker_name'] ?? '—') ?></td>
</tr>
<?php endforeach;
$html = ob_get_clean();

jsonOut([
    'html'  => $html,
    'stats' => compact('total','checked','pending','pct'),
]);
