<?php
// app/lib/db.php - PDO helper (PHP 7.0)
function db() {
    static $pdo = null;
    if ($pdo !== null) return $pdo;

    $cfgPath = __DIR__ . '/../config.php';
    if (!file_exists($cfgPath)) {
        header('Location: install.php'); exit;
    }
    $cfg = require $cfgPath;

    $dsn = 'mysql:host=' . $cfg['db_host'] . ';dbname=' . $cfg['db_name'] . ';charset=utf8mb4';
    $pdo = new PDO($dsn, $cfg['db_user'], $cfg['db_pass'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    return $pdo;
}

function q($sql, $params = []) {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    return $stmt;
}

function one($sql, $params = []) {
    return q($sql, $params)->fetch();
}

function all($sql, $params = []) {
    return q($sql, $params)->fetchAll();
}
