<?php

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

        $statement = Database::connection()->prepare(
            'SELECT id, name, email, role, permissions, status FROM users WHERE id = ? AND status = "active" LIMIT 1'
        );
        $statement->execute([$_SESSION['user_id']]);
        $user = $statement->fetch();

        return $user ?: null;
    }

    public static function check(): bool
    {
        return self::user() !== null;
    }

    public static function can(string $permission): bool
    {
        $user = self::user();

        if (!$user) {
            return false;
        }

        if ($user['role'] === 'admin') {
            return true;
        }

        $permissions = json_decode((string) ($user['permissions'] ?? '[]'), true);

        return is_array($permissions) && in_array($permission, $permissions, true);
    }

    public static function attempt(string $email, string $password): bool
    {
        $statement = Database::connection()->prepare(
            'SELECT * FROM users WHERE email = ? AND status = "active" LIMIT 1'
        );
        $statement->execute([$email]);
        $user = $statement->fetch();

        if (!$user || !password_verify($password, $user['password'])) {
            return false;
        }

        session_regenerate_id(true);
        $_SESSION['user_id'] = (int) $user['id'];

        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::check()) {
            redirect('/login');
        }
    }

    public static function requirePermission(string $permission): void
    {
        self::requireLogin();

        if (!self::can($permission)) {
            http_response_code(403);
            $pageTitle = 'Acces refuse - Locative';
            require dirname(__DIR__) . '/resources/views/errors/403.php';
            exit;
        }
    }
}
