<?php
// PDO connection + config accessor.
function config($key = null) {
  static $c = null;
  if ($c === null) {
    require_once __DIR__ . '/env.php';
    // Optional: set APP_ENV_FILE (real server env or .htaccess `SetEnv`) to a
    // .env stored OUTSIDE the web root, e.g. /home/USER/ntppa.env
    load_env(env('APP_ENV_FILE') ?: dirname(__DIR__) . '/.env');
    $f = __DIR__ . '/config.php';
    $c = file_exists($f) ? require $f : [];
    // Secrets belong in .env (or real server env vars) — those override config.php.
    foreach (['db_host' => 'DB_HOST', 'db_name' => 'DB_NAME', 'db_user' => 'DB_USER',
              'db_pass' => 'DB_PASS', 'base_url' => 'BASE_URL', 'site_url' => 'SITE_URL',
              'app_key' => 'APP_KEY'] as $k => $e) {   // app_key: HMAC secret for the HQ status API
      $v = env($e);
      if ($v !== null) { $c[$k] = $v; }
    }
    if (!$c) {
      exit('Setup needed: copy .env.example to .env (recommended) or app/config.sample.php to app/config.php, and add your database details.');
    }
  }
  return $key ? ($c[$key] ?? null) : $c;
}

function db() {
  static $pdo = null;
  if ($pdo === null) {
    $c = config();
    try {
      $pdo = new PDO(
        "mysql:host={$c['db_host']};dbname={$c['db_name']};charset=utf8mb4",
        $c['db_user'], $c['db_pass'],
        [
          PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
          PDO::ATTR_EMULATE_PREPARES   => false,
        ]
      );
    } catch (PDOException $ex) {
      http_response_code(500);
      exit('Database connection failed. Check app/config.php. (' . e_safe($ex->getMessage()) . ')');
    }
  }
  return $pdo;
}
function e_safe($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
