<?php

$filename = $exportFilename ?? ('users-' . date('Ymd-His') . '.csv');
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

$escapeValue = static function ($value, bool $allowSignedNumeric = false) {
    if ($value === null) {
        return '';
    }
    $string = (string) $value;
    if ($string !== '' && in_array($string[0], ['=', '@'], true)) {
        return "'" . $string;
    }
    if ($string !== '' && in_array($string[0], ['+', '-'], true)) {
        if ($allowSignedNumeric && preg_match('/^[+-]?[0-9\\s().-]+$/', $string)) {
            return $string;
        }
        return "'" . $string;
    }
    return $string;
};

$formatTimestamp = static function ($value) {
    if ($value === null || $value === '') {
        return '';
    }
    return dt($value, 'Y-m-d H:i:s');
};
 $joinLabels = static function ($value) {
    if (is_array($value)) {
        return implode(' | ', array_map('strval', $value));
    }
    if (is_string($value)) {
        $value = trim($value);
        if ($value === '') {
            return '';
        }
        return str_replace('||', ' | ', $value);
    }
    return '';
 };

$handle = fopen('php://output', 'w');
if ($handle === false) {
    return;
}

fputcsv($handle, ['id', 'uuid', 'first_name', 'last_name', 'email', 'phone', 'mobile', 'short_dial', 'locale', 'theme', 'active', 'tenants', 'departments', 'roles', 'created_by', 'modified_by', 'created', 'modified'], ',', '"', '\\');

foreach (($exportRows ?? []) as $row) {
    fputcsv($handle, [
        $escapeValue($row['id'] ?? ''),
        $escapeValue($row['uuid'] ?? ''),
        $escapeValue($row['first_name'] ?? ''),
        $escapeValue($row['last_name'] ?? ''),
        $escapeValue($row['email'] ?? ''),
        $escapeValue($row['phone'] ?? '', true),
        $escapeValue($row['mobile'] ?? '', true),
        $escapeValue($row['short_dial'] ?? '', true),
        $escapeValue($row['locale'] ?? ''),
        $escapeValue($row['theme'] ?? ''),
        (int) ($row['active'] ?? 0),
        $escapeValue($joinLabels($row['tenant_labels'] ?? [])),
        $escapeValue($joinLabels($row['department_labels'] ?? [])),
        $escapeValue($joinLabels($row['role_labels'] ?? [])),
        $escapeValue($row['created_by'] ?? ''),
        $escapeValue($row['modified_by'] ?? ''),
        $formatTimestamp($row['created'] ?? ''),
        $formatTimestamp($row['modified'] ?? ''),
    ], ',', '"', '\\');
}

fclose($handle);
