<?php
// =============================================================
//  include/env_loader.php
//
//  Minimal .env reader — no Composer dependency needed for
//  something this small. Reads KEY=VALUE pairs from the .env
//  file at the project root (gitignored — never commit real
//  secrets there; see .env.example for the documented shape).
//
//  Usage: env('DB_HOST', 'localhost')
// =============================================================

if (!function_exists('env')) {
    function env(string $key, $default = null)
    {
        static $vars = null;

        if ($vars === null) {
            $vars = [];
            $path = __DIR__ . '/../.env';
            if (file_exists($path)) {
                foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
                    $line = trim($line);
                    if ($line === '' || $line[0] === '#' || !str_contains($line, '=')) continue;
                    [$k, $v] = explode('=', $line, 2);
                    $k = trim($k);
                    $v = trim($v);
                    $len = strlen($v);
                    if ($len >= 2 && (($v[0] === '"' && $v[$len - 1] === '"') || ($v[0] === "'" && $v[$len - 1] === "'"))) {
                        $v = substr($v, 1, -1);
                    }
                    $vars[$k] = $v;
                }
            }
        }

        if (array_key_exists($key, $vars)) return $vars[$key];

        $fromEnv = getenv($key);
        if ($fromEnv !== false) return $fromEnv;

        return $default;
    }
}
