<?php

namespace App\Helpers;

class Url
{
    private static $baseUrl = null;

    public static function getBaseUrl()
    {
        if (self::$baseUrl === null) {
            if (defined('APP_BASE_URL')) {
                self::$baseUrl = rtrim(APP_BASE_URL, '/');
            } else {
                $docRoot = isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : '';
                $scriptDir = dirname(isset($_SERVER['SCRIPT_FILENAME']) ? $_SERVER['SCRIPT_FILENAME'] : __DIR__ . '/../../public');
                $base = str_replace($docRoot, '', $scriptDir);
                $base = str_replace('\\', '/', $base);
                self::$baseUrl = rtrim($base, '/');
            }
        }
        return self::$baseUrl;
    }

    public static function to($path = '')
    {
        $base = self::getBaseUrl();
        $pathPart = $base . '/' . ltrim($path, '/');

        // If running in a web request and a host is available, return an absolute URL
        if (php_sapi_name() !== 'cli' && (isset($_SERVER['HTTP_HOST']) || isset($_SERVER['SERVER_NAME']))) {
            $host = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'];
            $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
            return $scheme . '://' . $host . $pathPart;
        }

        // Fallback to path-only base
        return $pathPart;
    }

    public static function redirect($path)
    {
        header('Location: ' . self::to($path));
        exit;
    }
}
