<?php

declare(strict_types=1);

/**
 * Helpers for physical index.php files in admin/ and contracts/ subfolders.
 */

function karvi_project_root(): string
{
    return defined('KARVI_ROOT') ? KARVI_ROOT : dirname(__DIR__);
}

function karvi_normalize_request_path(): string
{
    foreach (['REDIRECT_URL', 'REQUEST_URI', 'PATH_INFO'] as $key) {
        if (empty($_SERVER[$key])) {
            continue;
        }

        $path = parse_url((string)$_SERVER[$key], PHP_URL_PATH);
        if (!is_string($path) || $path === '') {
            continue;
        }

        $path = str_replace('\\', '/', $path);
        $path = rtrim($path, '/') ?: '/';
        if ($path === '/index.php' || $path === '/default.php') {
            return '/';
        }

        return $path;
    }

    return '/';
}

function karvi_run(string $route): never
{
    $_SERVER['KARVI_ROUTE'] = str_starts_with($route, '/') ? $route : '/' . $route;
    if (!defined('KARVI_ROOT')) {
        define('KARVI_ROOT', karvi_project_root());
    }
    require karvi_project_root() . '/includes/karvi_front.php';
    exit;
}

function karvi_run_from_prefix(string $prefix, ?string $pattern = null): never
{
    $path = karvi_normalize_request_path();
    $prefix = rtrim($prefix, '/');
    $regex = $pattern ?? ('#(' . preg_quote($prefix, '#') . '(?:/.*)?)#');

    if (preg_match($regex, $path, $matches)) {
        $route = rtrim((string)$matches[1], '/') ?: $prefix;
        karvi_run($route);
    }

    karvi_run($prefix);
}
