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

class EnvLoader {
    private static $loaded = false;
    private static $variables = [];
    
    /**
     * Resolve .env path (project root or document root on shared hosting)
     */
    public static function resolveEnvPath() {
        $candidates = [
            __DIR__ . '/../.env',
            dirname(__DIR__) . DIRECTORY_SEPARATOR . '.env',
        ];
        if (!empty($_SERVER['DOCUMENT_ROOT'])) {
            $docRoot = rtrim($_SERVER['DOCUMENT_ROOT'], '/\\');
            $candidates[] = $docRoot . DIRECTORY_SEPARATOR . '.env';
        }
        foreach ($candidates as $candidate) {
            $resolved = realpath($candidate);
            if ($resolved && is_readable($resolved)) {
                return $resolved;
            }
            if (file_exists($candidate) && is_readable($candidate)) {
                return $candidate;
            }
        }
        return __DIR__ . '/../.env';
    }

    /**
     * Load .env file
     */
    public static function load($path = null) {
        if (self::$loaded) {
            return;
        }

        if ($path === null) {
            $path = self::resolveEnvPath();
        }
        
        if (file_exists($path) && is_readable($path)) {
            self::parseEnvFile($path);
        } else {
            self::loadDefaults();
        }

        // env.local.php overrides .env (fixes broken .env with localhost on InfinityFree)
        self::loadFromPhpFile();

        self::$loaded = true;
    }

    private static function parseEnvFile($path) {
        $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        foreach ($lines as $line) {
            $line = preg_replace('/^\xEF\xBB\xBF/', '', $line);
            $line = trim($line);

            if ($line === '' || strpos($line, '#') === 0) {
                continue;
            }

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

                if (preg_match('/^"(.+)"$/', $value, $matches)) {
                    $value = $matches[1];
                } elseif (preg_match('/^\'(.+)\'$/', $value, $matches)) {
                    $value = $matches[1];
                }

                self::setVariable($key, $value);
            }
        }
    }

    private static function setVariable($key, $value) {
        self::$variables[$key] = $value;
        putenv("$key=$value");
        $_ENV[$key] = $value;
    }
    
    /**
     * Load env.local.php when .env is missing (common on InfinityFree)
     */
    private static function loadFromPhpFile() {
        $candidates = [
            __DIR__ . '/../env.local.php',
            dirname(__DIR__) . DIRECTORY_SEPARATOR . 'env.local.php',
        ];
        if (!empty($_SERVER['DOCUMENT_ROOT'])) {
            $candidates[] = rtrim($_SERVER['DOCUMENT_ROOT'], '/\\') . DIRECTORY_SEPARATOR . 'env.local.php';
        }
        foreach ($candidates as $file) {
            if (!file_exists($file) || !is_readable($file)) {
                continue;
            }
            $vars = include $file;
            if (!is_array($vars)) {
                continue;
            }
            foreach ($vars as $key => $value) {
                if (!is_string($key)) {
                    continue;
                }
                self::setVariable($key, (string) $value);
            }
            return true;
        }
        return false;
    }

    /**
     * Load default values if .env doesn't exist
     */
    private static function loadDefaults() {
        $defaults = [
            'DB_HOST' => 'localhost',
            'DB_NAME' => 'school_management',
            'DB_USER' => 'root',
            'DB_PASS' => 'root',
            'DB_CHARSET' => 'utf8mb4',
            'APP_NAME' => 'Bidda School Management',
            'APP_ENV' => 'development',
            'APP_DEBUG' => 'true',
            'APP_URL' => 'http://localhost/bidda',
            'APP_TIMEZONE' => 'Asia/Dhaka',
            'CSRF_TOKEN_LIFETIME' => '3600',
            'SESSION_LIFETIME' => '7200',
            'SMS_ENABLED' => 'false',
            'ENABLE_DEBUG' => 'true',
            'MAX_UPLOAD_SIZE' => '50M'
        ];
        
        foreach ($defaults as $key => $value) {
            self::$variables[$key] = $value;
            putenv("$key=$value");
            $_ENV[$key] = $value;
        }
        
        self::$loaded = true;
    }
    
    /**
     * Get environment variable
     */
    public static function get($key, $default = null) {
        if (!self::$loaded) {
            self::load();
        }
        
        return isset(self::$variables[$key]) ? self::$variables[$key] : $default;
    }
    
    /**
     * Get boolean value
     */
    public static function getBool($key, $default = false) {
        $value = self::get($key, $default);
        return in_array(strtolower($value), ['true', '1', 'yes', 'on']);
    }
    
    /**
     * Get integer value
     */
    public static function getInt($key, $default = 0) {
        return (int) self::get($key, $default);
    }
}

// Load environment variables
EnvLoader::load();
