<?php
/**
 * URL helpers — pretty paths locally; index.php?route= on hosts without mod_rewrite.
 */

/**
 * Web URL prefix for the app install (stable when opened via /mobile/, /landing/, etc.).
 */
function nazareth_detect_base_path(): string
{
    if (!defined('ROOT_PATH')) {
        return '';
    }

    $root = str_replace('\\', '/', ROOT_PATH);
    $docRoot = $_SERVER['DOCUMENT_ROOT'] ?? '';
    if ($docRoot !== '') {
        $docRoot = rtrim(str_replace('\\', '/', realpath($docRoot) ?: $docRoot), '/');
        $rootReal = rtrim(str_replace('\\', '/', realpath($root) ?: $root), '/');
        if ($docRoot !== '' && strpos($rootReal, $docRoot) === 0) {
            $base = substr($rootReal, strlen($docRoot));
            return ($base === '' || $base === '/') ? '' : $base;
        }
    }

    $script = str_replace('\\', '/', $_SERVER['SCRIPT_NAME'] ?? '/index.php');
    $dir = dirname($script);
    if (preg_match('#/(mobile|landing)(/index\.php)?$#', $dir) || preg_match('#/(mobile|landing)$#', $dir)) {
        $dir = dirname($dir);
    }
    return ($dir === '/' || $dir === '.') ? '' : $dir;
}

if (!defined('NAZARETH_USE_INDEX_ROUTES')) {
    $host = preg_replace('/:\d+$/', '', strtolower($_SERVER['HTTP_HOST'] ?? ''));
    $isLocal = in_array($host, ['localhost', '127.0.0.1'], true)
        || substr($host, -6) === '.local'
        || substr($host, -5) === '.test';
    define('NAZARETH_USE_INDEX_ROUTES', !$isLocal && !empty($host));
}

/**
 * Static file under /public/ (CSS, JS, images). Never routed through index.php.
 */
function nazareth_asset(string $path): string
{
    $path = ltrim(str_replace('\\', '/', $path), '/');
    if (strpos($path, 'public/') === 0) {
        $path = substr($path, 7);
    }
    return BASE_PATH . '/public/' . $path;
}

/** CSS/JS under /mobile/ (data collection PWA). */
function nazareth_mobile_asset(string $path): string
{
    $path = ltrim(str_replace('\\', '/', $path), '/');
    return BASE_PATH . '/mobile/' . $path;
}

/**
 * App page URL (login, dashboard, members/edit/5, etc.).
 * For CSS/JS/images use nazareth_asset(), not this function.
 */
function nazareth_url(string $path = '', array $query = []): string
{
    $path = trim($path, '/');
    $base = BASE_PATH;

    if (NAZARETH_USE_INDEX_ROUTES) {
        $url = $base . '/index.php';
        $params = $query;
        if ($path !== '') {
            $params = array_merge(['route' => $path], $params);
        }
        if ($params !== []) {
            $url .= '?' . http_build_query($params);
        }
        return $url;
    }

    $url = $base . ($path === '' ? '/' : '/' . $path);
    if ($query !== []) {
        $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($query);
    }
    return $url;
}

/**
 * Resolve route when mod_rewrite / ErrorDocument forwards a path without ?route=.
 */
function nazareth_resolve_route(): string
{
    if (isset($_GET['route']) && $_GET['route'] !== '') {
        return trim((string) $_GET['route'], '/');
    }

    $uri = $_SERVER['REDIRECT_URL'] ?? $_SERVER['REQUEST_URI'] ?? '';
    $path = parse_url($uri, PHP_URL_PATH);
    if (!is_string($path) || $path === '') {
        return '';
    }

    $base = BASE_PATH;
    if ($base !== '' && strpos($path, $base) === 0) {
        $path = substr($path, strlen($base));
    }
    $path = trim($path, '/');

    if ($path === '' || $path === 'index.php') {
        return '';
    }
    if (strpos($path, 'public/') === 0 || strpos($path, 'vendor/') === 0) {
        return '';
    }

    return $path;
}

/** Send Location header and exit. */
function nazareth_redirect(string $path = '', array $query = []): void
{
    header('Location: ' . nazareth_url($path, $query));
    exit;
}
