<?php
// api/analytics.php — JSON analytics export for one event (admin-authenticated)
require_once __DIR__ . '/../config.php';
adminGuard();

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

// Ownership check
$ev = $db->prepare('SELECT * FROM events WHERE id=? AND admin_id=?');
$ev->execute([$eventId, $_SESSION['admin_id']]);
$event = $ev->fetch();
if (!$event) jsonOut(['error' => 'Event not found'], 404);

$one = function (string $sql) use ($db, $eventId) {
    $s = $db->prepare($sql); $s->execute([$eventId]); return $s;
};

$total   = (int)$one('SELECT COUNT(*) FROM guests WHERE event_id=?')->fetchColumn();
$checked = (int)$one('SELECT COUNT(*) FROM guests WHERE event_id=? AND checked_in=1')->fetchColumn();

$byMethod = $one('SELECT COALESCE(check_in_method,"none") m, COUNT(*) c
                  FROM guests WHERE event_id=? AND checked_in=1 GROUP BY m')->fetchAll(PDO::FETCH_KEY_PAIR);

$byCategory = $one('SELECT COALESCE(NULLIF(category,""),"Uncategorized") cat,
                    COUNT(*) total, SUM(checked_in) checked
                    FROM guests WHERE event_id=? GROUP BY cat ORDER BY total DESC')->fetchAll();

$byChecker = $db->prepare('SELECT c.name, COUNT(*) c
                           FROM guests g JOIN checkers c ON c.id=g.checked_by
                           WHERE g.event_id=? AND g.checked_in=1 GROUP BY c.id ORDER BY c DESC');
$byChecker->execute([$eventId]);
$byChecker = $byChecker->fetchAll();

$byHour = $one("SELECT DATE_FORMAT(check_in_time,'%Y-%m-%d %H:00') hr, COUNT(*) c
                FROM guests WHERE event_id=? AND checked_in=1
                GROUP BY hr ORDER BY hr")->fetchAll();

jsonOut([
    'event' => [
        'id'       => (int)$event['id'],
        'title'    => $event['title'],
        'slug'     => $event['slug'],
        'timezone' => eventTz($event),
        'date'     => $event['event_date'],
    ],
    'summary' => [
        'total_guests'    => $total,
        'checked_in'      => $checked,
        'pending'         => $total - $checked,
        'attendance_rate' => $total ? round($checked / $total * 100, 1) : 0,
    ],
    'by_method'   => $byMethod,
    'by_category' => $byCategory,
    'by_checker'  => $byChecker,
    'by_hour'     => $byHour,
    'generated_at'=> date('c'),
]);
