<?php
namespace App\Core;

/** Pembangun URL yang menghormati base_url. */
class Url
{
    private static ?string $base = null;

    public static function base(): string
    {
        if (self::$base !== null) return self::$base;
        $b = (string)Config::get('app.base_url', '');
        if ($b === '') {
            // Deteksi otomatis: /path/ke/public bila front controller berada di subfolder
            $script = (string)($_SERVER['SCRIPT_NAME'] ?? '/index.php');
            $b = rtrim(str_replace('\\', '/', dirname($script)), '/');
            if ($b === '.' || $b === '/') $b = '';
        }
        self::$base = rtrim($b, '/');
        return self::$base;
    }

    public static function to(string $path = '/', array $query = []): string
    {
        $path = '/' . ltrim($path, '/');
        $url  = self::base() . $path;
        if ($query) {
            $url .= (str_contains($url, '?') ? '&' : '?') . http_build_query($query);
        }
        return $url;
    }

    public static function asset(string $path): string
    {
        return self::to('assets/' . ltrim($path, '/'));
    }

    public static function current(array $merge = [], array $remove = []): string
    {
        $q = $_GET;
        foreach ($remove as $r) unset($q[$r]);
        foreach ($merge as $k => $v) {
            if ($v === null) unset($q[$k]); else $q[$k] = $v;
        }
        return self::to(Request::uri(), $q);
    }

    public static function full(): string
    {
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        return $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . self::base();
    }
}
