<?php
// api/export.php  —  Export full guest list as CSV
require_once __DIR__ . '/../config.php';
startSecureSession();
if (empty($_SESSION['admin_id'])) { http_response_code(401); exit('Unauthorized'); }

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

$ev = $db->prepare('SELECT * FROM events WHERE id=? AND admin_id=?');
$ev->execute([$eventId, $_SESSION['admin_id']]);
$event = $ev->fetch();
if (!$event) { http_response_code(404); exit('Event not found'); }

$stmt = $db->prepare(
    'SELECT g.name, g.email, g.phone, g.table_number, g.seat_number, g.category,
            g.checked_in, g.check_in_time, g.check_in_method, c.name AS checker_name,
            g.token
     FROM guests g
     LEFT JOIN checkers c ON c.id = g.checked_by
     WHERE g.event_id = ?
     ORDER BY g.name ASC'
);
$stmt->execute([$eventId]);
$guests = $stmt->fetchAll();

$filename = 'guest-report-' . $event['slug'] . '-' . date('Ymd-His') . '.csv';
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Pragma: no-cache');

$out = fopen('php://output', 'w');
fputcsv($out, [
    'Name','Email','Phone','Table','Seat','Category',
    'Checked In','Check-in Time','Method','Checked By','Token'
]);
foreach ($guests as $g) {
    fputcsv($out, [
        $g['name'], $g['email'], $g['phone'],
        $g['table_number'], $g['seat_number'], $g['category'],
        $g['checked_in'] ? 'Yes' : 'No',
        $g['check_in_time'] ?? '',
        $g['check_in_method'] ?? '',
        $g['checker_name'] ?? '',
        $g['token'],
    ]);
}
fclose($out);
exit;
