<?php
class EnvironmentLoader {
    private static $loaded = false;
    private static $config = [];
    
    public static function load($envFile = '.env') {
        if (self::$loaded) return;
        
        $envPath = __DIR__ . '/../' . $envFile;
        
        if (!file_exists($envPath)) {
            throw new Exception("Environment file not found: $envPath");
        }
        
        $lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        
        foreach ($lines as $line) {
            if (strpos($line, '#') === 0) continue; // Skip comments
            
            if (strpos($line, '=') !== false) {
                list($key, $value) = explode('=', $line, 2);
                $key = trim($key);
                $value = trim($value);
                
                // Remove quotes if present
                if (preg_match('/^"(.*)"$/', $value, $matches)) {
                    $value = $matches[1];
                } elseif (preg_match("/^'(.*)'$/", $value, $matches)) {
                    $value = $matches[1];
                }
                
                self::$config[$key] = $value;
                $_ENV[$key] = $value;
                putenv("$key=$value");
            }
        }
        
        self::$loaded = true;
    }
    
    public static function get($key, $default = null) {
        return self::$config[$key] ?? $_ENV[$key] ?? getenv($key) ?: $default;
    }
    
    public static function getBoolean($key, $default = false) {
        $value = self::get($key);
        return filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? $default;
    }
    
    public static function getInt($key, $default = 0) {
        return (int) self::get($key, $default);
    }
    
    public static function isProduction() {
        return self::get('APP_ENV') === 'production';
    }
    
    public static function isDevelopment() {
        return self::get('APP_ENV') === 'development';
    }
}

// Auto-load environment on include
try {
    // Try production first, then fallback to development
    if (file_exists(__DIR__ . '/../.env')) {
        EnvironmentLoader::load('.env');
    } elseif (file_exists(__DIR__ . '/../.env.production')) {
        EnvironmentLoader::load('.env.production');
    } elseif (file_exists(__DIR__ . '/../.env.example')) {
        EnvironmentLoader::load('.env.example');
    }
} catch (Exception $e) {
    // Fallback to default values if no env file found
    $_ENV['APP_ENV'] = 'development';
    $_ENV['APP_DEBUG'] = 'true';
}
?>