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

final class SecuritySessionControlController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('administration.permissions.view');
        $this->view('security/sessions', [
            'pageTitle'=>'Contrôle des sessions actives',
            'report'=>(new SecuritySessionControlService())->dashboard(),
            'canManage'=>Permission::can('administration.permissions.manage'),
            'currentUserId'=>(int)(Auth::id() ?? 0),
        ]);
    }

    public function revokeUser(): void
    {
        Auth::requireRecentAuthentication();
        Permission::require('administration.permissions.manage');
        Csrf::verify($_POST['_csrf'] ?? null);
        try {
            $self = (new SecuritySessionControlService())->revokeUser(
                (int)($_POST['user_id'] ?? 0),
                (int)(Auth::id() ?? 0)
            );
            if ($self) {
                Auth::logout();
                header('Location: /public/login?reauth=1');
                exit;
            }
            $_SESSION['flash_success']='Toutes les sessions de cet utilisateur ont été révoquées.';
        } catch (\Throwable $e) {
            $_SESSION['flash_error']=$e->getMessage();
        }
        $this->redirect('/administration/securite/sessions');
    }

    public function revokeOthers(): void
    {
        Auth::requireRecentAuthentication();
        Permission::require('administration.permissions.manage');
        Csrf::verify($_POST['_csrf'] ?? null);
        try {
            $count=(new SecuritySessionControlService())->revokeAllExceptCurrent(
                (int)(Auth::id() ?? 0),
                (string)($_SESSION['session_token'] ?? '')
            );
            $_SESSION['flash_success']=$count . ' session(s) distante(s) révoquée(s). Votre session actuelle est conservée.';
        } catch (\Throwable $e) {
            $_SESSION['flash_error']=$e->getMessage();
        }
        $this->redirect('/administration/securite/sessions');
    }
}
