<?php
/**
 * Environment Variable Loader
 * 
 * Loads and manages environment variables from .env file
 * 
 * @author ESDN Development Team
 * @version 1.0.0
 */

class EnvLoader
{

    private static $loaded = false;
    private static $vars = [];

    /**
     * Load environment variables from .env file
     * 
     * @param string $path Path to .env file
     * @return bool
     */
    public static function load(?string $path = null): bool
    {
        if (self::$loaded) {
            return true;
        }

        if ($path === null) {
            $path = dirname(dirname(dirname(__DIR__))) . '/.env';
        }

        if (!file_exists($path)) {
            error_log("Environment file not found: {$path}");
            return false;
        }

        $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        foreach ($lines as $line) {
            // Skip comments
            if (strpos(trim($line), '#') === 0) {
                continue;
            }

            // Parse key=value
            if (strpos($line, '=') !== false) {
                list($key, $value) = explode('=', $line, 2);
                $key = trim($key);
                $value = trim($value);

                // Remove quotes if present
                if (preg_match('/^(["\'])(.*)\1$/', $value, $matches)) {
                    $value = $matches[2];
                }

                // Store in static array
                self::$vars[$key] = $value;

                // Also set as environment variable
                if (!array_key_exists($key, $_ENV)) {
                    $_ENV[$key] = $value;
                    putenv("{$key}={$value}");
                }
            }
        }

        self::$loaded = true;
        return true;
    }

    /**
     * Get environment variable
     * 
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    public static function get(string $key, $default = null)
    {
        self::load();

        // Check static vars first
        if (isset(self::$vars[$key])) {
            return self::$vars[$key];
        }

        // Check $_ENV
        if (isset($_ENV[$key])) {
            return $_ENV[$key];
        }

        // Check getenv()
        $value = getenv($key);
        if ($value !== false) {
            return $value;
        }

        return $default;
    }

    /**
     * Check if environment variable exists
     * 
     * @param string $key
     * @return bool
     */
    public static function has(string $key): bool
    {
        self::load();
        return isset(self::$vars[$key]) || isset($_ENV[$key]) || getenv($key) !== false;
    }

    /**
     * Get all environment variables
     * 
     * @return array
     */
    public static function all(): array
    {
        self::load();
        return self::$vars;
    }
}

// Auto-load on include
EnvLoader::load();
