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

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Security\MfaService;

final class MfaController extends Controller
{
    public function challenge(): void
    {
        $pending=Auth::pendingMfaUserId();
        if (!$pending) $this->redirect('/login');
        if (Auth::pendingMfaMode()==='enroll') {
            $setup=MfaService::beginEnrollment($pending);
            $_SESSION['mfa_enrollment_secret']=$setup['secret'];
            $_SESSION['mfa_enrollment_uri']=$setup['uri'];
            $this->view('auth/mfa-enroll',['pageTitle'=>'Activer la double authentification','hideNavigation'=>true,'setup'=>$setup]);
            return;
        }
        $this->view('auth/mfa-challenge',['pageTitle'=>'Double authentification','hideNavigation'=>true]);
    }

    public function verify(): void
    {
        Csrf::verify($_POST['_csrf'] ?? null);
        $userId=Auth::pendingMfaUserId();
        if (!$userId) $this->redirect('/login');
        $code=(string)($_POST['code'] ?? '');
        if (!MfaService::verify($userId,$code)) {
            $_SESSION['error']='Code de double authentification invalide.';
            $this->redirect('/mfa');
        }
        Auth::completePendingMfa();
        $this->redirect(Auth::consumePendingReturnTo());
    }

    public function enroll(): void
    {
        Csrf::verify($_POST['_csrf'] ?? null);
        $userId=Auth::pendingMfaUserId();
        if (!$userId || Auth::pendingMfaMode()!=='enroll') $this->redirect('/login');
        try {
            $codes=MfaService::confirmEnrollment($userId,(string)($_POST['code'] ?? ''));
            $_SESSION['mfa_new_backup_codes']=$codes;
            Auth::completePendingMfa();
            $this->redirect('/mfa/codes');
        } catch (\Throwable $e) {
            $_SESSION['error']=$e->getMessage();
            $this->redirect('/mfa');
        }
    }

    public function codes(): void
    {
        Auth::requireLogin();
        $codes=$_SESSION['mfa_new_backup_codes'] ?? [];
        unset($_SESSION['mfa_new_backup_codes']);
        if (!is_array($codes) || !$codes) $this->redirect('/');
        $this->view('auth/mfa-codes',['pageTitle'=>'Codes de secours MFA','hideNavigation'=>true,'codes'=>$codes]);
    }
}
