<?php
// includes/env.php
// Minimal .env loader (no external deps). Safe to include multiple times.

if (!function_exists('ua_load_env')) {
    function ua_load_env(string $envPath): void
    {
        if (!is_file($envPath) || !is_readable($envPath)) return;

        $lines = file($envPath, FILE_IGNORE_NEW_LINES);
        if (!$lines) return;

        foreach ($lines as $line) {
            $line = trim($line);
            if ($line === '' || str_starts_with($line, '#')) continue;

            // KEY=VALUE (VALUE may be quoted)
            $pos = strpos($line, '=');
            if ($pos === false) continue;
            $key = trim(substr($line, 0, $pos));
            $val = trim(substr($line, $pos + 1));
            if ($key === '') continue;

            if ((str_starts_with($val, '"') && str_ends_with($val, '"')) || (str_starts_with($val, "'") && str_ends_with($val, "'"))) {
                $val = substr($val, 1, -1);
            }

            if (getenv($key) === false) {
                putenv($key . '=' . $val);
                $_ENV[$key] = $val;
            }
        }
    }
}
