<?php
/// file: app/Controllers/Admin/AuthController.php

declare(strict_types=1);

namespace App\Controllers\Admin;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;

final class AuthController extends Controller
{
    public function form(Request $request): Response
    {
        $auth = new Auth();
        if ($auth->check()) {
            return $this->redirect(url('/admin'));
        }
        $html = $this->adminGuestView('admin/login', [
            'error' => Session::pullFlash()['error'] ?? null,
        ]);
        return Response::html($html);
    }

    public function login(Request $request): Response
    {
        if (! Csrf::verify($request->input('_csrf'))) {
            Session::flash('error', 'Invalid token.');
            return $this->redirect(url('/admin/login'));
        }
        $email = trim((string) $request->input('email', ''));
        $password = (string) $request->input('password', '');
        $auth = new Auth();
        if (! $auth->attempt($email, $password)) {
            Session::flash('error', 'Invalid credentials.');
            return $this->redirect(url('/admin/login'));
        }
        return $this->redirect(url('/admin'));
    }

    public function logout(Request $request): Response
    {
        (new Auth())->logout();
        return $this->redirect(url('/admin/login'));
    }
}
