<?php
class Auth
{
    public static function check(): bool
    {
        return !empty($_SESSION['user_id']);
    }

    public static function user(): ?array
    {
        return $_SESSION['user'] ?? null;
    }

    public static function login(array $user): void
    {
        session_regenerate_id(true);
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user'] = $user;
    }

    public static function logout(): void
    {
        session_unset();
        session_destroy();
        if (isset($_COOKIE[session_name()])) {
            setcookie(session_name(), '', time() - 3600, '/');
        }
    }

    public static function guard(): void
    {
        if (!self::check()) {
            $config = require __DIR__ . '/../../config/config.php';
            $baseUrl = rtrim($config['app']['url'] ?? '', '/');
            header('Location: ' . $baseUrl . '/login');
            exit;
        }
    }
}
