<?php
require_once __DIR__.'/../config/config.php';
require_once __DIR__.'/../config/database.php';
require_once __DIR__.'/../includes/functions.php';
require_once __DIR__.'/../includes/admin_functions.php';
afAdminRequireAuth();

$format = (string)($_GET['format'] ?? 'csv');
if (!in_array($format, ['csv','json'], true)) $format = 'csv';
$filters = [
    'subject_user_id' => (int)($_GET['usuario_id'] ?? 0),
    'action_key' => sanitize($_GET['action'] ?? ''),
    'from' => !empty($_GET['from']) ? preg_replace('/[^0-9\-]/','',(string)$_GET['from']).' 00:00:00' : '',
    'to' => !empty($_GET['to']) ? preg_replace('/[^0-9\-]/','',(string)$_GET['to']).' 23:59:59' : '',
];
$rows = afStage24ExportAuditRows($pdo, $filters, 5000);
$fileName = 'aura-auditoria-'.date('Ymd-His').'.'.$format;

if ($format === 'json') {
    $content = json_encode(['generated_at'=>date(DATE_ATOM),'filters'=>$filters,'rows'=>$rows], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    afStage24RegisterAuditExport($pdo, afAdminId(), 'audit_logs', 'json', $filters, count($rows), $fileName, $content);
    header('Content-Type: application/json; charset=UTF-8');
    header('Content-Disposition: attachment; filename="'.$fileName.'"');
    echo $content;
    exit;
}

$fh = fopen('php://temp', 'r+');
fputcsv($fh, ['id','uuid','data','acao','ator_tipo','ator_usuario','ator_admin','usuario_alvo','entidade_tipo','entidade_id','severidade','origem'], ';');
foreach ($rows as $r) {
    fputcsv($fh, [
        $r['id'] ?? '', $r['event_uuid'] ?? '', $r['created_at'] ?? '', $r['action_key'] ?? '', $r['actor_type'] ?? '',
        $r['actor_user_id'] ?? '', $r['actor_admin_id'] ?? '', $r['subject_user_id'] ?? '', $r['entity_type'] ?? '', $r['entity_id'] ?? '',
        $r['severity'] ?? '', $r['source'] ?? '',
    ], ';');
}
rewind($fh);
$content = stream_get_contents($fh);
fclose($fh);
afStage24RegisterAuditExport($pdo, afAdminId(), 'audit_logs', 'csv', $filters, count($rows), $fileName, $content);
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="'.$fileName.'"');
echo "\xEF\xBB\xBF".$content;
exit;
