<?php
class Auth
{
    public static function user(): ?array
    {
        if (empty($_SESSION['user_id'])) {
            return null;
        }
        return User::find((int)$_SESSION['user_id']);
    }

    public static function id(): ?int
    {
        return empty($_SESSION['user_id']) ? null : (int)$_SESSION['user_id'];
    }

    public static function login(string $email, string $password): bool
    {
        $user = User::findByEmail($email);
        if (!$user || !password_verify($password, $user['password_hash'])) {
            return false;
        }
        if (($user['role'] ?? '') === 'student' && (($user['student_status'] ?? 'active') !== 'active')) {
            return false;
        }
        session_regenerate_id(true);
        unset($_SESSION['professional_id'], $_SESSION['professional_name'], $_SESSION['beginner_instructor_id']);
        $_SESSION['user_id'] = (int)$user['id'];
        $_SESSION['role'] = $user['role'];
        return true;
    }

    public static function logout(): void
    {
        $_SESSION = [];
        if (ini_get('session.use_cookies')) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
        }
        session_destroy();
    }

    public static function requireLogin(): void
    {
        if (!self::id()) {
            redirect('login');
        }
    }

    public static function requireAdmin(): void
    {
        self::requireLogin();
        if (($_SESSION['role'] ?? '') !== 'admin') {
            http_response_code(403);
            exit('Acesso negado.');
        }
    }

    public static function requireStudent(): void
    {
        self::requireLogin();
        if (($_SESSION['role'] ?? '') !== 'student') {
            redirect('admin/dashboard');
        }
    }
}
