<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Permission;
use App\Services\SecurityInformationEventManagementService;

final class SecurityInformationEventManagementController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('administration.permissions.view');
        $hours = max(1, min(720, (int)($_GET['hours'] ?? 24)));
        $this->view('security/siem', [
            'pageTitle' => 'SIEM & SOC Pro',
            'report' => (new SecurityInformationEventManagementService())->report($hours),
        ]);
    }

    public function exportCsv(): void
    {
        Auth::requireLogin();
        Permission::require('administration.permissions.view');
        $report = (new SecurityInformationEventManagementService())->report((int)($_GET['hours'] ?? 24));
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="axiom_siem_'.date('Ymd_His').'.csv"');
        $out = fopen('php://output', 'wb');
        if ($out === false) { http_response_code(500); return; }
        fwrite($out, "\xEF\xBB\xBF");
        fputcsv($out, ['Horodatage','Sévérité','Catégorie','Événement','Acteur pseudonymisé','Chemin','Request ID'], ';');
        foreach ($report['recent_events'] as $event) {
            fputcsv($out, [$event['timestamp'],$event['severity'],$event['category'],$event['event'],$event['actor'],$event['path'],$event['request_id']], ';');
        }
        fclose($out);
    }
}
