<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

reports_module_boot();

if (!can_export_reports_module()) {
    abort_request(403, 'Access denied', 'You do not have permission to export reports.');
}

$reportKey = (string) ($_GET['report'] ?? '');
if (!in_array($reportKey, exportable_report_keys(), true)) {
    abort_request(404, 'Report not found', 'The requested report export is not available.');
}

$filters = reports_filters_from_request($_GET);
$datasets = report_export_datasets($filters);
$rows = $datasets[$reportKey] ?? [];

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

$output = fopen('php://output', 'wb');
if ($output === false) {
    exit;
}

if ($rows === []) {
    fputcsv($output, ['No data available']);
    fclose($output);
    exit;
}

fputcsv($output, array_keys($rows[0]));
foreach ($rows as $row) {
    fputcsv($output, $row);
}

fclose($output);
exit;
