<?php

namespace App\Core;

/**
 * Lightweight secure environment variable loader
 */
class Env
{
    /**
     * Load environment variables from a file path
     *
     * @param string $path
     * @throws \Exception
     */
    public static function load(string $path): void
    {
        if (!file_exists($path)) {
            // Create a default if it doesn't exist to prevent crash, or throw
            if (file_exists($path . '.example')) {
                copy($path . '.example', $path);
            } else {
                throw new \Exception("Environment file not found at: {$path}");
            }
        }

        $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            $line = trim($line);

            // Skip comments and empty lines
            if (empty($line) || strpos($line, '#') === 0) {
                continue;
            }

            // Split by the first equals sign
            if (strpos($line, '=') !== false) {
                list($key, $value) = explode('=', $line, 2);
                $key = trim($key);
                $value = trim($value);

                // Strip surrounding quotes
                if (preg_match('/^"(.+)"$/', $value, $matches) || preg_match("/^'(.+)'$/", $value, $matches)) {
                    $value = $matches[1];
                }

                // Inject into PHP superglobals and env
                putenv("{$key}={$value}");
                $_ENV[$key] = $value;
                $_SERVER[$key] = $value;
            }
        }
    }

    /**
     * Retrieve environment variable with optional default value
     *
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    public static function get(string $key, $default = null)
    {
        $val = getenv($key);
        if ($val === false) {
            return $default;
        }

        switch (strtolower($val)) {
            case 'true':
            case '(true)':
                return true;
            case 'false':
            case '(false)':
                return false;
            case 'null':
            case '(null)':
                return null;
            case 'empty':
            case '(empty)':
                return '';
        }

        return $val;
    }
}
