<?php

declare(strict_types=1);

function app_base_path(): string
{
    if (defined('APP_BASE_PATH') && APP_BASE_PATH !== '') {
        return rtrim((string) APP_BASE_PATH, '/');
    }

    if (defined('BASE_URL') && BASE_URL !== '') {
        return rtrim((string) BASE_URL, '/');
    }

    $scriptName = isset($_SERVER['SCRIPT_NAME']) ? str_replace('\\', '/', (string) $_SERVER['SCRIPT_NAME']) : '';
    return rtrim(str_replace('/index.php', '', $scriptName), '/');
}

function using_route_fallback(): bool
{
    if (defined('FORCE_ROUTE_FALLBACK') && FORCE_ROUTE_FALLBACK) {
        return true;
    }

    if (isset($_GET['route'])) {
        return true;
    }

    $requestUri = isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '';
    return strpos($requestUri, '/index.php') !== false;
}

function base_url(string $path = ''): string
{
    $base = app_base_path();
    $path = (string) $path;

    if ($path === '' || $path === '/') {
        return using_route_fallback() ? $base . '/index.php' : $base . '/';
    }

    $routePath = $path;
    $queryString = '';

    if (strpos($path, '?') !== false) {
        $parts = explode('?', $path, 2);
        $routePath = $parts[0];
        $queryString = $parts[1];
    }

    $normalized = '/' . ltrim($routePath, '/');

    if (using_route_fallback()) {
        $url = $base . '/index.php?route=' . rawurlencode($normalized);
        if ($queryString !== '') {
            $url .= '&' . $queryString;
        }
        return $url;
    }

    $url = $base . $normalized;
    if ($queryString !== '') {
        $url .= '?' . $queryString;
    }

    return $url;
}

function asset_url(string $path = ''): string
{
    $path = '/' . ltrim((string) $path, '/');

    if (strpos($path, '/assets/') === 0) {
        return app_base_path() . $path;
    }

    return app_base_path() . $path;
}

function storage_url(string $path = ''): string
{
    $path = ltrim((string) $path, '/');
    if (strpos($path, 'uploads/') === 0) {
        return app_base_path() . '/' . $path;
    }

    return app_base_path() . '/uploads/ocorrencias/' . $path;
}

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