<?php
declare(strict_types=1);
namespace App\Controllers;

use App\Core\Controller;
use App\Core\SessionAuth;

final class AuthController extends Controller {
    public function login(): void {
        if (app()->get(SessionAuth::class)->check()) redirect(base_url('?page=dashboard'));
        $this->view('auth/login', ['title' => 'تسجيل الدخول']);
    }

    public function authenticate(): void {
        verify_csrf();
        $auth = app()->get(SessionAuth::class);
        $ok = $auth->attempt(trim((string)($_POST['username'] ?? '')), (string)($_POST['password'] ?? ''));
        if (!$ok) {
            flash('error', 'بيانات الدخول غير صحيحة');
            redirect(base_url('?page=login'));
        }
        redirect(base_url('?page=dashboard'));
    }

    public function logout(): void {
        app()->get(SessionAuth::class)->logout();
        redirect(base_url('?page=login'));
    }
}
