<?php
/**
 * Environment Variables Loader
 * Loads configuration from .env file securely
 */

class EnvLoader {
    private static $loaded = false;
    
    public static function load($envFile = '.env') {
        if (self::$loaded) {
            return; // Already loaded
        }
        
        $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) {
            // Skip comments
            if (strpos(trim($line), '#') === 0) {
                continue;
            }
            
            // Parse key=value pairs
            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];
                }
                
                // Set environment variable if not already set
                if (!getenv($key)) {
                    putenv("{$key}={$value}");
                    $_ENV[$key] = $value;
                }
            }
        }
        
        self::$loaded = true;
    }
    
    /**
     * Get environment variable with optional default
     */
    public static function get($key, $default = null) {
        $value = getenv($key);
        return $value !== false ? $value : $default;
    }
    
    /**
     * Get required environment variable (throws exception if missing)
     */
    public static function getRequired($key) {
        $value = self::get($key);
        if ($value === null) {
            throw new Exception("Required environment variable '{$key}' is not set");
        }
        return $value;
    }
    
    /**
     * Check if running in production
     */
    public static function isProduction() {
        return self::get('APP_ENV', 'production') === 'production';
    }
    
    /**
     * Check if debug mode is enabled
     */
    public static function isDebug() {
        return filter_var(self::get('APP_DEBUG', 'false'), FILTER_VALIDATE_BOOLEAN);
    }
}

// Auto-load environment variables when this file is included
try {
    EnvLoader::load();
} catch (Exception $e) {
    // In production, fail gracefully
    if (EnvLoader::get('APP_ENV', 'production') === 'production') {
        error_log('Environment loading failed: ' . $e->getMessage());
        // You might want to show a maintenance page here
        die('Configuration error. Please contact support.');
    } else {
        // In development, show the error
        throw $e;
    }
}
?>
