<?php
if (!function_exists('load_dotenv')) {
    function load_dotenv($dir, $filename = '.env') {
        $path = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $filename;
        if (!is_file($path) || !is_readable($path)) return false;
        $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        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);
            if ((substr($value,0,1)==='"' && substr($value,-1)==='"') || (substr($value,0,1)==="'" && substr($value,-1)==="'")) {
                $value = substr($value, 1, -1);
            }
            $value = preg_replace_callback('/\${([A-Z0-9_]+)}/i', function($m){
                $k = $m[1];
                $v = getenv($k);
                if ($v === false && isset($_ENV[$k])) $v = $_ENV[$k];
                if ($v === false && isset($_SERVER[$k])) $v = $_SERVER[$k];
                return $v !== false ? $v : $m[0];
            }, $value);
            putenv("$name=$value");
            $_ENV[$name] = $value;
            $_SERVER[$name] = $value;
        }
        return true;
    }
}
if (!function_exists('env')) {
    function env($key, $default = null) {
        $v = getenv($key);
        if ($v === false && isset($_ENV[$key])) $v = $_ENV[$key];
        if ($v === false && isset($_SERVER[$key])) $v = $_SERVER[$key];
        return ($v === false || $v === null || $v === '') ? $default : $v;
    }
}
