<?php
/**
 * Environment Configuration Loader
 * Loads variables from .env file and makes them available throughout the application
 */

class EnvLoader {
    private static $instance;
    private $env = [];
    
    private function __construct() {
        $this->loadEnv();
    }
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function loadEnv() {
        $envPath = dirname(__DIR__) . '/.env';
        
        if (!file_exists($envPath)) {
            error_log("Warning: .env file not found at {$envPath}");
            return;
        }
        
        $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
            if (strpos($line, '=') !== false) {
                [$key, $value] = explode('=', $line, 2);
                $key = trim($key);
                $value = trim($value);
                
                // Remove quotes if present
                if ((strpos($value, '"') === 0 && strrpos($value, '"') === strlen($value) - 1) ||
                    (strpos($value, "'") === 0 && strrpos($value, "'") === strlen($value) - 1)) {
                    $value = substr($value, 1, -1);
                }
                
                $this->env[$key] = $value;
                $_ENV[$key] = $value;
            }
        }
    }
    
    public function get($key, $default = null) {
        return $this->env[$key] ?? $default;
    }
    
    public function all() {
        return $this->env;
    }
    
    public function has($key) {
        return isset($this->env[$key]);
    }
}

/**
 * Global helper function to get env variables
 */
if (!function_exists('env')) {
    function env($key, $default = null) {
        return EnvLoader::getInstance()->get($key, $default);
    }
}

// Auto-load on include
EnvLoader::getInstance();
?>
