<?php
declare(strict_types=1);

$sessionPath = __DIR__ . '/../storage/sessions';
if (is_dir($sessionPath) && is_writable($sessionPath)) {
    session_save_path($sessionPath);
}
session_start();

require_once __DIR__ . '/../includes/database.php';

if (empty($_SESSION['rsvp_admin'])) {
    http_response_code(403);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Please sign in to export RSVP responses.';
    exit;
}

$config = rsvp_config();
$eventId = $config['event']['id'];
$filename = 'ebabe-rsvp-responses-' . date('Y-m-d-His') . '.csv';

try {
    $pdo = rsvp_pdo();
    $stmt = $pdo->prepare(
        'SELECT
            full_name,
            email,
            phone,
            category,
            attendance,
            party_size,
            note,
            email_sent,
            notification_sent,
            created_at
         FROM rsvp_responses
         WHERE event_id = :event_id
         ORDER BY created_at DESC, id DESC'
    );
    $stmt->execute(['event_id' => $eventId]);

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Pragma: no-cache');

    $output = fopen('php://output', 'w');
    if ($output === false) {
        throw new RuntimeException('Could not open export stream.');
    }

    fwrite($output, "\xEF\xBB\xBF");
    fputcsv($output, [
        'Full Name',
        'Email',
        'Phone',
        'Category',
        'Response',
        'Party Size',
        'Note',
        'Guest Email Sent',
        'Admin Notification Sent',
        'Submitted At',
    ]);

    while ($row = $stmt->fetch()) {
        fputcsv($output, [
            $row['full_name'],
            $row['email'],
            $row['phone'],
            $row['category'],
            $row['attendance'] === 'yes' ? 'Joyfully accepts' : 'Regretfully declines',
            $row['party_size'],
            $row['note'],
            (int) $row['email_sent'] ? 'Yes' : 'No',
            (int) $row['notification_sent'] ? 'Yes' : 'No',
            $row['created_at'],
        ]);
    }

    fclose($output);
} catch (Throwable $exception) {
    error_log('RSVP export failed: ' . $exception->getMessage());
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Could not export RSVP responses. Check the database connection.';
}
