<?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\SocPlaybookService;

final class SocPlaybookController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin(); Permission::require('soc.playbooks.view');
        $service = new SocPlaybookService();
        $runId = max(0, (int) ($_GET['run'] ?? 0));
        $dashboard = $service->dashboard();

        // Do not expose the dashboard under the generic $data variable: the shared
        // layout may reuse that name before the view is rendered.
        $this->view('security/soc_playbooks', [
            'pageTitle' => 'SOC Playbooks',
            'playbooks' => is_array($dashboard['playbooks'] ?? null) ? $dashboard['playbooks'] : [],
            'incidents' => is_array($dashboard['incidents'] ?? null) ? $dashboard['incidents'] : [],
            'runs' => is_array($dashboard['runs'] ?? null) ? $dashboard['runs'] : [],
            'run' => $runId > 0 ? $service->run($runId) : null,
        ]);
    }
    public function start(): void
    {
        Auth::requireRecentAuthentication(); Permission::require('soc.playbooks.execute'); Csrf::verify($_POST['_csrf']??null);
        $id=(new SocPlaybookService())->start(max(0,(int)($_POST['playbook_id']??0)),max(0,(int)($_POST['incident_id']??0)),(int)(Auth::id()??0));
        $_SESSION['success']='Playbook démarré en attente de validation humaine.'; $this->redirect('/administration/securite/soc/playbooks?run='.$id);
    }
    public function step(): void
    {
        Auth::requireRecentAuthentication(); Permission::require('soc.playbooks.execute'); Csrf::verify($_POST['_csrf']??null);
        $id=max(0,(int)($_POST['run_id']??0)); (new SocPlaybookService())->executeCurrent($id,(string)($_POST['decision']??''),(string)($_POST['note']??''),(int)(Auth::id()??0));
        $_SESSION['success']='Étape du playbook traitée.'; $this->redirect('/administration/securite/soc/playbooks?run='.$id);
    }
    public function status(): void
    {
        Auth::requireRecentAuthentication(); Permission::require('soc.playbooks.execute'); Csrf::verify($_POST['_csrf']??null);
        $id=max(0,(int)($_POST['run_id']??0)); (new SocPlaybookService())->changeStatus($id,(string)($_POST['status']??''),(int)(Auth::id()??0));
        $_SESSION['success']='État du playbook mis à jour.'; $this->redirect('/administration/securite/soc/playbooks?run='.$id);
    }
}
