<?php
declare(strict_types=1);

function base_url(string $path = ''): string {

    // Detect protocol
    $protocol = (
        (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
        ($_SERVER['SERVER_PORT'] ?? 80) == 443
    ) ? "https://" : "http://";

    // Host
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';

    // ==== FIX PALING PENTING ====
    // Tetapkan ROOT project dari DOCUMENT_ROOT
    $root = str_replace('\\', '/', realpath($_SERVER['DOCUMENT_ROOT']));
    $project = str_replace('\\', '/', realpath(__DIR__ . '/../../'));

    // Buat relative path project
    $relative = str_replace($root, '', $project);

    // Rapikan slash
    $relative = '/' . trim($relative, '/');

    // Pastikan path ada slash di depan
    if ($path !== '' && $path[0] !== '/') {
        $path = '/' . $path;
    }

    return $protocol . $host . $relative . $path;
}

return [
    'BASE_URL' => base_url()
];
