<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Models\AdminUser;
use Core\Controller;
use Core\Csrf;
use Core\Session;

final class AdminAuthController extends Controller
{
    public function login(): void
    {
        if (AdminUser::current()) $this->redirectTo('admin/admissoes');
        $this->view('auth/login', ['errors' => Session::errors()], 'auth');
    }

    public function authenticate(): void
    {
        if (!Csrf::verify($_POST['_token'] ?? null)) {
            http_response_code(419);
            exit('Token CSRF inválido.');
        }
        $email = trim((string)($_POST['email'] ?? ''));
        $password = (string)($_POST['password'] ?? '');
        if ($email === '' || $password === '') {
            Session::putErrors(['login' => 'Informe e-mail e senha.']);
            Session::putOldInput($_POST);
            $this->redirectTo('admin/login');
        }
        if (!AdminUser::authenticate($email, $password)) {
            Session::putErrors(['login' => 'Credenciais inválidas.']);
            Session::putOldInput(['email' => $email]);
            $this->redirectTo('admin/login');
        }
        Session::flash('success', 'Acesso liberado.');
        $this->redirectTo('admin/admissoes');
    }

    public function logout(): void
    {
        AdminUser::logout();
        Session::flash('success', 'Sessão encerrada.');
        $this->redirectTo('admin/login');
    }
}
