<?php
/**
 * Lightweight .env loader for cPanel/shared hosting
 * - Loads .env from project root or auth-backend directory
 * - Populates getenv/$_ENV/$_SERVER for broad compatibility
 */
class TonEnv {
    private static $loaded = false;

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

        $paths = [
            dirname(__DIR__, 2) . '/.env',           // project root
            dirname(__DIR__) . '/.env',              // auth-backend/.env
        ];

        foreach ($paths as $file) {
            if (!is_file($file)) continue;
            $lines = @file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            if ($lines === false) continue;
            foreach ($lines as $line) {
                $line = trim($line);
                if ($line === '' || $line[0] === '#') continue;
                // Support quoted values and KEY=VALUE format
                $parts = explode('=', $line, 2);
                if (count($parts) !== 2) continue;
                $key = trim($parts[0]);
                $value = trim($parts[1]);

                // Allow lines like: export KEY=VALUE
                if (stripos($key, 'export ') === 0) {
                    $key = trim(substr($key, 7));
                }

                // Strip surrounding quotes if present
                $first = substr($value, 0, 1);
                $last = substr($value, -1);
                if (($first === '"' && $last === '"') || ($first === "'" && $last === "'")) {
                    $value = substr($value, 1, -1);
                } else {
                    // Remove inline comments starting with # if not quoted
                    $value = preg_replace('/\s+#.*$/', '', $value);
                }
                $value = trim($value);

                // Validate key to avoid invalid putenv assignments
                if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $key)) {
                    // Skip invalid keys silently
                    continue;
                }

                // Export to environments
                if (!array_key_exists($key, $_ENV)) $_ENV[$key] = $value;
                if (!array_key_exists($key, $_SERVER)) $_SERVER[$key] = $value;
                // Only call putenv with a valid assignment string
                putenv($key . '=' . $value);
            }
        }

        self::$loaded = true;
    }

    public static function get(string $key, $default = null) {
        self::load();
        $val = $_ENV[$key] ?? getenv($key) ?? $_SERVER[$key] ?? null;
        return ($val === null || $val === '') ? $default : $val;
    }
}
