<?php
ini_set('display_errors', '0');

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/query.php';
admin_require_login();

[$where, $params, $filters] = rsvp_filters();

$stmt = db()->prepare('SELECT * FROM rsvps' . $where . ' ORDER BY created_at ASC');
$stmt->execute($params);

$name = 'pko50-guests-' . date('Y-m-d-Hi') . '.csv';

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $name . '"');
header('Pragma: no-cache');

$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF"); // BOM so Excel reads the accents

fputcsv($out, ['Name', 'Phone', 'Country', 'Answer', 'Language', 'Received on', 'Received at', 'Updated'], ',', '"', '\\');

while ($row = $stmt->fetch()) {
    fputcsv($out, [
        $row['full_name'],
        $row['phone_e164'],
        $row['country_iso'],
        $row['attending'] ? 'Yes' : 'No',
        strtoupper($row['lang']),
        date('Y-m-d', strtotime($row['created_at'])),
        date('H:i', strtotime($row['created_at'])),
        $row['updated_at'] ? date('Y-m-d H:i', strtotime($row['updated_at'])) : '',
    ], ',', '"', '\\');
}

fclose($out);
