<?php
declare(strict_types=1);
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Permission;
use App\Services\SecurityOperationsCenterService;

final class SecurityOperationsCenterController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('soc.dashboard.view');
        $service=new SecurityOperationsCenterService();
        $incidentId=max(0,(int)($_GET['incident'] ?? 0));
        $this->view('security/soc', [
            'pageTitle'=>'SOC Enterprise',
            'report'=>$service->dashboard($_GET),
            'incident'=>$incidentId>0 ? $service->incident($incidentId) : null,
        ]);
    }

    public function updateIncident(): void
    {
        Auth::requireLogin();
        Permission::require('soc.incidents.manage');
        Csrf::verify($_POST['_csrf'] ?? null);
        $id=max(0,(int)($_POST['incident_id'] ?? 0));
        $status=(string)($_POST['status'] ?? 'investigating');
        $note=trim((string)($_POST['note'] ?? ''));
        (new SecurityOperationsCenterService())->updateIncident($id,$status,$note,(int)(Auth::user()['id'] ?? 0));
        $_SESSION['success']='Incident SOC mis à jour.';
        $this->redirect('/administration/securite/soc?incident='.$id);
    }

    public function assignIncident(): void
    {
        Auth::requireRecentAuthentication();
        Permission::require('soc.incidents.assign');
        Csrf::verify($_POST['_csrf'] ?? null);
        $id=max(0,(int)($_POST['incident_id'] ?? 0));
        $assignee=max(0,(int)($_POST['assigned_to'] ?? 0));
        (new SecurityOperationsCenterService())->assignIncident($id,$assignee,(int)(Auth::id() ?? 0));
        $_SESSION['success']='Affectation de l’incident enregistrée.';
        $this->redirect('/administration/securite/soc?incident='.$id);
    }

    public function addResponseAction(): void
    {
        Auth::requireRecentAuthentication();
        Permission::require('soc.incidents.respond');
        Csrf::verify($_POST['_csrf'] ?? null);
        $id=max(0,(int)($_POST['incident_id'] ?? 0));
        (new SecurityOperationsCenterService())->addResponseAction(
            $id,
            (string)($_POST['action_type'] ?? 'note'),
            (string)($_POST['content'] ?? ''),
            (int)(Auth::id() ?? 0)
        );
        $_SESSION['success']='Action de réponse enregistrée.';
        $this->redirect('/administration/securite/soc?incident='.$id);
    }

    public function reopenIncident(): void
    {
        Auth::requireRecentAuthentication();
        Permission::require('soc.incidents.close');
        Csrf::verify($_POST['_csrf'] ?? null);
        $id=max(0,(int)($_POST['incident_id'] ?? 0));
        (new SecurityOperationsCenterService())->reopenIncident($id,(string)($_POST['reason'] ?? ''),(int)(Auth::id() ?? 0));
        $_SESSION['success']='Incident rouvert.';
        $this->redirect('/administration/securite/soc?incident='.$id);
    }

    public function reportHtml(): void
    {
        Auth::requireLogin();
        Permission::require('soc.incidents.export');
        $id=max(0,(int)($_GET['incident'] ?? 0));
        $incident=(new SecurityOperationsCenterService())->incident($id);
        if ($incident===null) { http_response_code(404); exit('Incident introuvable.'); }
        $this->view('security/incident_report', ['pageTitle'=>'Rapport d’incident SOC','incident'=>$incident]);
    }

    public function exportCsv(): void
    {
        Auth::requireLogin();
        Permission::require('soc.dashboard.view');
        $report=(new SecurityOperationsCenterService())->dashboard($_GET);
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="axiom_soc_'.date('Ymd_His').'.csv"');
        $out=fopen('php://output','wb');
        if ($out===false) { http_response_code(500); return; }
        fwrite($out, "\xEF\xBB\xBF");
        fputcsv($out,['ID','UUID','Statut','Gravité','Score','Titre','Module','Utilisateur','Événements','Premier événement','Dernier événement'],';');
        foreach ($report['incidents'] as $row) {
            fputcsv($out,[$row['id'],$row['incident_uuid'],$row['status'],$row['severity'],$row['risk_score'],$row['title'],$row['module'],$row['user_id'],$row['event_count'],$row['first_event_at'],$row['last_event_at']],';');
        }
        fclose($out);
    }
}
