<?php
namespace App\Config;

class Config {
    protected static array $settings = [];
    protected static bool $loaded = false;

    public static function load(): void {
        if (self::$loaded) {
            return;
        }

        $envPath = dirname(__DIR__, 2) . '/.env';
        if (file_exists($envPath)) {
            $lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            foreach ($lines as $line) {
                $line = trim($line);
                if (empty($line) || str_starts_with($line, '#')) {
                    continue;
                }
                if (str_contains($line, '=')) {
                    [$key, $val] = explode('=', $line, 2);
                    $key = trim($key);
                    $val = trim($val);
                    // Strip quotes if present
                    if ((str_starts_with($val, '"') && str_ends_with($val, '"')) ||
                        (str_starts_with($val, "'") && str_ends_with($val, "'"))) {
                        $val = substr($val, 1, -1);
                    }
                    self::$settings[$key] = $val;
                    $_ENV[$key] = $val;
                    putenv("{$key}={$val}");
                }
            }
        }
        self::$loaded = true;
    }

    public static function get(string $key, mixed $default = null): mixed {
        self::load();
        return self::$settings[$key] ?? getenv($key) ?: $default;
    }

    public static function set(string $key, mixed $value): void {
        self::$settings[$key] = $value;
    }
}
