<?php

declare(strict_types=1);

class Env
{
    private static array $vars = [];

    public static function load(string $path = __DIR__ . '/../.env'): void
    {
        if (!is_file($path)) {
            return;
        }

        $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            $line = trim($line);
            if ($line === '' || str_starts_with($line, '#')) {
                continue;
            }
            if (str_starts_with(mb_strtolower($line), 'export ')) {
                $line = trim(mb_substr($line, 7));
                if ($line === '' || str_starts_with($line, '#')) {
                    continue;
                }
            }

            [$key, $value] = array_map('trim', array_pad(explode('=', $line, 2), 2, ''));
            if ($key === '') {
                continue;
            }

            self::$vars[$key] = trim($value, " \t\n\r\0\x0B\"'");
            $envValue = self::$vars[$key];
            putenv("{$key}={$envValue}");
            $_ENV[$key] = $envValue;
            $_SERVER[$key] = $envValue;
        }

        if (strtolower(getenv('APP_ENV') ?? '') === 'dev') {
            echo 'Loaded .env from ' . $path . "\n";
        }
    }

    public static function get(string $key, ?string $default = null): ?string
    {
        $envValue = getenv($key);
        if ($envValue !== false) {
            return $envValue;
        }

        return self::$vars[$key] ?? $default;
    }
}
