<?php
// Helpers centralizados para generar rutas y URLs subcarpeta-aware

if (!function_exists('get_base_path')) {
    function get_base_path() {
        // Preferir REQUEST_URI (incluye subcarpeta real), sin query string
        $uri = $_SERVER['REQUEST_URI'] ?? '';
        if ($uri !== '' && ($qpos = strpos($uri, '?')) !== false) {
            $uri = substr($uri, 0, $qpos);
        }
        $script = $uri !== '' ? $uri : ($_SERVER['SCRIPT_NAME'] ?? '');

        $host = $_SERVER['HTTP_HOST'] ?? '';
        $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['SERVER_PORT'] ?? '') == 443);
        $scheme = $https ? 'https' : 'http';

        // Derivar directorio base a partir del script/URI
        $baseDir = '';
        if ($script !== '') {
            $pos = strpos($script, '/modules/');
            if ($pos !== false) {
                $baseDir = substr($script, 0, $pos);
            } else {
                // Usar directorio del script como base
                $baseDir = dirname($script);
            }
            // Normalizar: quitar trailing slash y convertir '/' a vacío
            $baseDir = rtrim($baseDir, '/');
            $baseDir = ($baseDir === '' || $baseDir === '/') ? '' : $baseDir;
        }

        // Validar host: usar absoluto solo si parece un host real
        $isValidHost = false;
        if ($host) {
            $isValidHost = (
                filter_var($host, FILTER_VALIDATE_IP) !== false ||
                $host === 'localhost' ||
                strpos($host, '.') !== false ||
                strpos($host, ':') !== false
            );
        }

        if ($isValidHost) {
            return $scheme . '://' . $host . ($baseDir !== '' ? $baseDir : '');
        }
        return $baseDir;
    }
}

if (!function_exists('asset')) {
    // Genera URL para un recurso en /public
    function asset($path) {
        $base = get_base_path();
        $path = '/' . ltrim($path, '/');
        // Evitar "//public/..." si base está vacío
        if ($base === '') { return $path; }
        return $base . $path;
    }
}

if (!function_exists('route_url')) {
    // Genera URL hacia index.php con query, aceptando string o array
    function route_url($query) {
        $base = get_base_path();
        if (is_array($query)) {
            $query_str = http_build_query($query);
        } else {
            $query_str = (string)$query;
        }
        if ($query_str !== '' && $query_str[0] !== '?') {
            $query_str = '?' . ltrim($query_str, '?');
        }
        return ($base === '' ? '' : $base) . '/index.php' . $query_str;
    }
}

if (!function_exists('module_url')) {
    // Genera URL hacia rutas dentro de /modules
    function module_url($path) {
        $base = get_base_path();
        $path = ltrim($path, '/');
        if (strpos($path, 'modules/') !== 0) {
            $path = 'modules/' . $path;
        }
        return ($base === '' ? '' : $base . '/') . $path;
    }
}

if (!function_exists('isLoggedIn')) {
    function isLoggedIn() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}