<?php
// PDO connection + config accessor.
function config($key = null) {
  static $c = null;
  if ($c === null) {
    $f = __DIR__ . '/config.php';
    if (!file_exists($f)) {
      exit('Setup needed: copy app/config.sample.php to app/config.php and add your database details.');
    }
    $c = require $f;
  }
  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'); }
