<?php

declare(strict_types=1);

namespace App\Shared\Support;

final class Path
{
    public static function public(string $relative = ''): string
    {
        $base = realpath(APP_BASE_PATH . '/public');
        if ($base === false) {
            $base = APP_BASE_PATH . '/public';
        }

        $relative = ltrim(str_replace('\\', '/', $relative), '/');
        return $relative !== '' ? ($base . DIRECTORY_SEPARATOR . $relative) : $base;
    }

    public static function baseUri(): string
    {
        static $base = null;
        if ($base !== null) {
            return $base;
        }

        $script = $_SERVER['SCRIPT_NAME'] ?? '';
        $dir = str_replace('\\', '/', dirname($script));
        $dir = rtrim($dir, '/');
        $base = ($dir === '.' || $dir === '') ? '' : $dir;

        return $base;
    }

    public static function url(string $path = ''): string
    {
        $path = str_replace('\\', '/', trim($path));
        $base = self::baseUri();

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

        if (preg_match('#^https?://#i', $path) === 1) {
            return $path;
        }

        if ($base !== '' && ($path === $base || str_starts_with($path, $base . '/'))) {
            return $path;
        }

        if (str_starts_with($path, '/')) {
            return ($base === '' ? '' : $base) . $path;
        }

        return ($base === '' ? '' : $base) . '/' . ltrim($path, '/');
    }

    public static function asset(string $path): string
    {
        return self::url($path);
    }
}
