<?php
// ─── Tiny .env loader (no dependencies) ─────────────────────────
// Loads KEY=VALUE pairs from a .env file into the process environment.
// Precedence: real server environment > .env file > app/config.php.
// .env is git-ignored and blocked from the web (.htaccess) — database
// passwords and other secrets belong there, never in committed files.

function load_env($file) {
  static $done = [];
  if (isset($done[$file])) { return; }
  $done[$file] = true;
  if (!is_readable($file)) { return; }
  foreach (file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
    $line = trim($line);
    if ($line === '' || $line[0] === '#' || strpos($line, '=') === false) { continue; }
    list($k, $v) = explode('=', $line, 2);
    $k = trim($k);
    $v = trim($v);
    if ($k === '' || !preg_match('/^[A-Za-z0-9_]+$/', $k)) { continue; }
    if (getenv($k) !== false) { continue; } // real environment always wins
    $len = strlen($v);
    if ($len > 1 && ($v[0] === '"' || $v[0] === "'") && $v[$len - 1] === $v[0]) {
      $v = substr($v, 1, $len - 2);
    }
    putenv($k . '=' . $v);
    $_ENV[$k] = $v;
  }
}

function env($key, $default = null) {
  $v = getenv($key);
  return $v === false ? $default : $v;
}
