<?php
/**
 * env_loader.php
 *
 * Tiny dependency-free .env parser. Looks for ".osce_env" outside the
 * webroot so secrets never sit in public_html. Returns an associative
 * array of variables; also pushes them into $_ENV / getenv() so other
 * libraries that read environment variables continue to work.
 */

if (!function_exists('osce_load_env')) {

    function osce_env_candidates(): array
    {
        $appDir = __DIR__;
        $docRoot = $_SERVER['DOCUMENT_ROOT'] ?? '';
        $candidates = [];

        if ($docRoot !== '') {
            $candidates[] = rtrim($docRoot, '/\\') . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '.osce_env';
        }
        $candidates[] = dirname($appDir) . DIRECTORY_SEPARATOR . '.osce_env';
        $candidates[] = $appDir   . DIRECTORY_SEPARATOR . '.osce_env';

        return $candidates;
    }

    function osce_load_env(?string $path = null): array
    {
        static $cache = null;
        if ($cache !== null && $path === null) {
            return $cache;
        }

        $paths = $path ? [$path] : osce_env_candidates();
        $found = null;
        foreach ($paths as $p) {
            if (is_readable($p)) {
                $found = $p;
                break;
            }
        }

        $vars = [];
        if ($found !== null) {
            $lines = @file($found, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
            foreach ($lines as $line) {
                $line = trim($line);
                if ($line === '' || $line[0] === '#') continue;
                if (!str_contains($line, '=')) continue;
                [$k, $v] = explode('=', $line, 2);
                $k = trim($k);
                $v = trim($v);
                // strip optional surrounding quotes
                if (strlen($v) >= 2 && (
                    ($v[0] === '"' && substr($v, -1) === '"') ||
                    ($v[0] === "'" && substr($v, -1) === "'")
                )) {
                    $v = substr($v, 1, -1);
                }
                $vars[$k] = $v;
                if (getenv($k) === false) {
                    putenv("$k=$v");
                }
                $_ENV[$k] = $v;
            }
        }

        $cache = $vars;
        return $vars;
    }

    function osce_env(string $key, $default = null)
    {
        $vars = osce_load_env();
        if (array_key_exists($key, $vars)) return $vars[$key];
        $g = getenv($key);
        return $g === false ? $default : $g;
    }

    /** Is any .osce_env file readable in the candidate locations? */
    function osce_env_present(): bool
    {
        foreach (osce_env_candidates() as $p) {
            if (is_readable($p)) return true;
        }
        return false;
    }

    /**
     * Pick the best writable location for .osce_env, preferring outside-webroot.
     * Returns full path that is writable (creates the file empty if needed).
     */
    function osce_env_pick_write_path(): ?string
    {
        foreach (osce_env_candidates() as $p) {
            $dir = dirname($p);
            if (!is_dir($dir)) continue;
            if (is_writable($dir) || (file_exists($p) && is_writable($p))) {
                return $p;
            }
        }
        return null;
    }
}
