<?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');
        }

        $errors = Session::errors();
        if (Session::getFlash('error') && empty($errors['login'])) {
            $errors['login'] = (string) Session::getFlash('error');
        }

        $this->view('auth/login', ['errors' => $errors], 'auth');
    }

    public function authenticate(): void
    {
        if (!Csrf::verify($_POST['_token'] ?? null)) {
            Session::putErrors(['login' => 'Sua sessão expirou. Atualize a página e tente entrar novamente.']);
            $this->redirectTo('admin/login');
        }
        $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');
    }
}
