<?php
declare(strict_types=1);

function app_load_env(string $file): array {
    if (!file_exists($file)) return [];
    $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
    $env = [];
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#')) continue;
        // allow comments after values
        $line = preg_replace('/\s+;.*$/', '', $line);
        if (!str_contains($line, '=')) continue;
        [$k, $v] = explode('=', $line, 2);
        $k = trim($k);
        $v = trim($v);
            $v = trim($v, "\"'");
        $env[$k] = $v;
    }
    return $env;
}

$envPath = __DIR__ . '/../.env';
$examplePath = __DIR__ . '/../.env.example';

if (file_exists($envPath)) {
  $GLOBALS['APP_ENV'] = app_load_env($envPath);
} else {
  $GLOBALS['APP_ENV'] = app_load_env($examplePath);
}


function app_config(string $key, ?string $default=null): ?string {
    return $GLOBALS['APP_ENV'][$key] ?? $default;
}

function app_base_url(): string {
    $u = app_config('APP_BASE_URL', '');
    return rtrim($u, '/');
}

function app_base_path(): string {
    $p = app_config('APP_BASE_PATH', '');
    if ($p === null) $p = '';
    $p = trim($p);
    if ($p === '' || $p === '/') return '';
    return rtrim($p, '/');
}
