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

if (!admin_is_logged_in()) {
    http_response_code(403);
    echo 'Forbidden';
    exit;
}

$pdo = db();
$selected_webinar_id = isset($_GET['webinar_id']) && is_numeric($_GET['webinar_id']) ? max(0, (int) $_GET['webinar_id']) : 0;

$where_sql = 'WHERE a.deleted_at IS NULL';
$params = [];
if ($selected_webinar_id > 0) {
    $where_sql .= ' AND a.webinar_id = :webinar_id';
    $params[':webinar_id'] = $selected_webinar_id;
}

$sql = "SELECT
            a.id,
            a.webinar_id,
            w.title AS webinar_title,
            a.first_name,
            a.last_name,
            a.email,
            a.company,
            a.how_did_you_hear,
            a.timezone,
            a.consented,
            a.created_at
        FROM attendees a
        LEFT JOIN webinars w ON w.id = a.webinar_id
        {$where_sql}
        ORDER BY a.created_at DESC, a.id DESC";
$stmt = $pdo->prepare($sql);
foreach ($params as $name => $value) {
    $stmt->bindValue($name, $value, PDO::PARAM_INT);
}
$stmt->execute();
$attendees = $stmt->fetchAll(PDO::FETCH_ASSOC);

header('Content-Type: text/csv; charset=utf-8');

$filename = 'attendees';
if ($selected_webinar_id > 0) {
    $filename .= '-webinar-' . $selected_webinar_id;
}
$filename .= '-' . date('Y-m-d') . '.csv';
header('Content-Disposition: attachment; filename=' . $filename);

$output = fopen('php://output', 'w');
fputs($output, "\xEF\xBB\xBF");

fputcsv($output, [
    'ID',
    'Webinar ID',
    'Webinar Title',
    'First Name',
    'Last Name',
    'Email',
    'Company',
    'Source',
    'Timezone',
    'Consented',
    'Registered At',
]);

foreach ($attendees as $attendee) {
    fputcsv($output, [
        $attendee['id'],
        $attendee['webinar_id'],
        $attendee['webinar_title'] ?? '',
        $attendee['first_name'],
        $attendee['last_name'],
        $attendee['email'],
        $attendee['company'] ?? '',
        $attendee['how_did_you_hear'] ?? '',
        $attendee['timezone'] ?? '',
        !empty($attendee['consented']) ? 'Yes' : 'No',
        $attendee['created_at'] ?? '',
    ]);
}

fclose($output);
exit;
