<?php
/**
 * Lightweight .env loader (no Composer dependency).
 * Loads KEY=VALUE pairs into $_ENV / putenv / $_SERVER.
 */

if (!function_exists('load_dotenv')) {
    function load_dotenv($path)
    {
        if (!is_file($path) || !is_readable($path)) {
            return false;
        }

        $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if ($lines === false) {
            return false;
        }

        foreach ($lines as $line) {
            $line = trim($line);
            if ($line === '' || $line[0] === '#' || strpos($line, '=') === false) {
                continue;
            }

            list($name, $value) = explode('=', $line, 2);
            $name = trim($name);
            $value = trim($value);

            // Strip matching quotes
            if (
                strlen($value) >= 2
                && (($value[0] === '"' && substr($value, -1) === '"')
                    || ($value[0] === "'" && substr($value, -1) === "'"))
            ) {
                $value = substr($value, 1, -1);
            }

            if ($name === '') {
                continue;
            }

            // Do not overwrite real environment variables already set by the server
            if (getenv($name) !== false) {
                continue;
            }

            putenv($name . '=' . $value);
            $_ENV[$name] = $value;
            $_SERVER[$name] = $value;
        }

        return true;
    }
}

if (!function_exists('env')) {
    /**
     * @param string $key
     * @param mixed  $default
     * @return mixed
     */
    function env($key, $default = null)
    {
        $value = getenv($key);
        if ($value === false) {
            if (array_key_exists($key, $_ENV)) {
                $value = $_ENV[$key];
            } elseif (array_key_exists($key, $_SERVER)) {
                $value = $_SERVER[$key];
            } else {
                return $default;
            }
        }

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

        return $value;
    }
}

// Auto-load .env from project root when this file is included
if (!defined('KOHA_ENV_LOADED')) {
    define('KOHA_ENV_LOADED', true);
    $envPath = dirname(__FILE__) . DIRECTORY_SEPARATOR . '.env';
    load_dotenv($envPath);
}
