<?php
session_start();
require_once 'db/config.php';

// Check if user is admin
if (!isset($_SESSION['user']) || $_SESSION['user'] !== 'admin') {
    http_response_code(403);
    echo "Forbidden";
    exit;
}

$pdo = db();
$stmt = $pdo->query("SELECT first_name, last_name, email FROM attendees ORDER BY created_at DESC");
$attendees = $stmt->fetchAll(PDO::FETCH_ASSOC);

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=attendees.csv');

$output = fopen('php://output', 'w');

// Add BOM to fix UTF-8 in Excel
fputs($output, "\xEF\xBB\xBF");

// Add header row
fputcsv($output, ['First Name', 'Last Name', 'Email']);

// Add data rows
foreach ($attendees as $attendee) {
    fputcsv($output, [
        $attendee['first_name'],
        $attendee['last_name'],
        $attendee['email']
    ]);
}

fclose($output);
exit;
