<?php
namespace App\Controllers;

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

class AuthController extends Controller
{
    public function __construct()
    {
        Auth::boot();
    }

    public function loginForm(): void
    {
        if (Auth::check()) { $this->redirect('/'); return; }
        $this->render('auth/login', [
            'pageTitle' => 'Agent sign in',
            'error' => Session::flash('error'),
            'next' => Request::query('next', '/'),
        ], 'layout/auth');
    }

    public function login(): void
    {
        $this->requireCsrf();
        $email = trim((string)Request::post('email'));
        $password = (string)Request::post('password');
        $next = (string)Request::post('next', '/');

        if (Auth::attempt($email, $password)) {
            $this->redirect($next && str_starts_with($next, '/') ? $next : '/');
            return;
        }

        Session::flash('error', 'Incorrect email or password.');
        $this->redirect('/login');
    }

    public function logout(): void
    {
        Auth::logout();
        $this->redirect('/login');
    }
}
