<?php
namespace App\Controllers;

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

final class AuthController extends Controller {
    public function show(): void {
        if (Auth::check()) $this->redirect('/');
        $this->view('auth/login', [
            'pageTitle' => 'Connexion',
            'hideNavigation' => true,
            'returnTo' => Auth::safeReturnTo((string)($_GET['return_to'] ?? '/public/')),
            'reauthentication' => isset($_GET['reauth']),
        ]);
    }

    public function login(): void {
        Csrf::verify($_POST['_csrf'] ?? null);
        $email = trim($_POST['email'] ?? '');
        $password = (string)($_POST['password'] ?? '');
        if (!Auth::attempt($email, $password)) {
            $_SESSION['error'] = 'Identifiants incorrects ou compte inactif.';
            $returnTo = Auth::safeReturnTo((string)($_POST['return_to'] ?? '/public/'));
            header('Location: /public/login?return_to=' . rawurlencode($returnTo));
            exit;
        }
        $returnTo = Auth::safeReturnTo((string)($_POST['return_to'] ?? '/public/'));
        if (Auth::pendingMfaUserId()) {
            Auth::setPendingReturnTo($returnTo);
            header('Location: /public/mfa');
            exit;
        }
        header('Location: ' . $returnTo);
        exit;
    }

    public function logout(): void {
        Csrf::verify($_POST['_csrf'] ?? null);
        Auth::logout();
        $this->redirect('/login');
    }
}
