<?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;
    }

    return false;
}

function normalize_legacy_route_path(string $path): array
{
    $path = trim($path);

    if (strpos($path, 'index.php?route=') === 0) {
        $legacyQuery = substr($path, strlen('index.php?'));
        parse_str($legacyQuery, $legacyParams);

        $routePath = isset($legacyParams['route']) ? (string) $legacyParams['route'] : '/';
        unset($legacyParams['route']);

        return [$routePath, http_build_query($legacyParams)];
    }

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

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

    return [$routePath, $queryString];
}

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

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

    list($routePath, $queryString) = normalize_legacy_route_path($path);
    $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');
}
