<?php

declare(strict_types=1);

use App\Core\App;

function env(string $key, mixed $default = null): mixed
{
    $value = $_ENV[$key] ?? $_SERVER[$key] ?? getenv($key);
    return ($value === false || $value === null) ? $default : $value;
}

function app(): App
{
    return App::instance();
}

function e(mixed $value): string
{
    return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function url(string $path = ''): string
{
    return app()->url($path);
}

function asset(string $path): string
{
    return url('assets/' . ltrim($path, '/'));
}

function csrf_field(): string
{
    return '<input type="hidden" name="_token" value="' . e(app()->csrf()->token()) . '">';
}

function old(string $key, mixed $default = ''): mixed
{
    return app()->session()->old($key, $default);
}

function can(string $module, string $action = 'view'): bool
{
    return app()->auth()->check() && app()->auth()->can($module, $action);
}

function requireLogin(): void
{
    (new \App\Middleware\AuthMiddleware())->handle(app()->request());
}

function requirePermission(string $module, string $action = 'view'): void
{
    (new \App\Middleware\PermissionMiddleware())->handle(app()->request(), $module . '.' . $action);
}

function requireAdmin(): void
{
    (new \App\Middleware\AdminMiddleware())->handle(app()->request());
}
