<?php
declare(strict_types=1);

function db(): PDO {
    static $pdo = null;
    if ($pdo instanceof PDO) return $pdo;

    $host = app_config('DB_HOST', '127.0.0.1');
    $port = app_config('DB_PORT', '3306');
    $name = app_config('DB_NAME', '');
    $user = app_config('DB_USER', '');
    $pass = app_config('DB_PASS', '');

    $dsn = "mysql:host={$host};port={$port};dbname={$name};charset=utf8mb4";
    $pdo = new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    return $pdo;
}

function db_all(string $sql, array $params=[]): array {
    $st = db()->prepare($sql);
    $st->execute($params);
    return $st->fetchAll();
}

function db_one(string $sql, array $params=[]): ?array {
    $st = db()->prepare($sql);
    $st->execute($params);
    $row = $st->fetch();
    return $row ?: null;
}
// Convenience alias used by import module
if (!function_exists("db_first")) {
  function db_first(string $sql, array $params = []): ?array {
    return db_one($sql, $params);
  }
}


function db_exec(string $sql, array $params=[]): int {
    $st = db()->prepare($sql);
    $st->execute($params);
    return $st->rowCount();
}

function db_insert(string $sql, array $params=[]): int {
    $st = db()->prepare($sql);
    $st->execute($params);
    return intval(db()->lastInsertId());
}
if (!function_exists('db_has_column')) {
  function db_has_column(string $table, string $column): bool {
    static $cache = [];
    $key = $table . '.' . $column;
    if (array_key_exists($key, $cache)) return (bool)$cache[$key];
    try {
      $row = db_one(
        "SELECT COUNT(*) AS c
         FROM information_schema.COLUMNS
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = ?
           AND COLUMN_NAME = ?",
        [$table, $column]
      );
      $cache[$key] = ($row && intval($row['c']) > 0);
    } catch (Throwable $e) {
      $cache[$key] = false;
    }
    return (bool)$cache[$key];
  }
}
