<?php
if (!function_exists('export_csv_headers')) {
    function export_csv_headers(string $filename): void
    {
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Pragma: no-cache');
        header('Expires: 0');
    }
}

if (!function_exists('csv_out')) {
    function csv_out(array $headers, array $rows, string $filename = 'export.csv'): void
    {
        export_csv_headers($filename);

        $out = fopen('php://output', 'w');
        if ($out === false) {
            throw new RuntimeException('Unable to open output stream.');
        }

        // UTF-8 BOM for Excel
        fwrite($out, "\xEF\xBB\xBF");

        fputcsv($out, $headers);

        foreach ($rows as $row) {
            $line = [];
            foreach ($headers as $key) {
                $line[] = $row[$key] ?? '';
            }
            fputcsv($out, $line);
        }

        fclose($out);
        exit;
    }
}