<?php
// admin/db_schema_helpers.php
// Central schema-inspection helpers shared by pages and setup scripts.

if (!function_exists('col_exists')) {
  function col_exists(mysqli $conn, string $table, string $col): bool {
    static $cache = [];
    $key = spl_object_id($conn) . '|' . $table . '|' . $col;
    // Cache positive results only. Migrations may add a column later during
    // the same request, so a cached negative result would become stale.
    if (!empty($cache[$key])) return true;

    $tableEsc = $conn->real_escape_string($table);
    $colEsc = $conn->real_escape_string($col);
    $q = @$conn->query("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
      WHERE TABLE_SCHEMA = DATABASE()
        AND TABLE_NAME = '$tableEsc'
        AND COLUMN_NAME = '$colEsc'
      LIMIT 1");
    $exists = ($q && $q->num_rows > 0);
    if ($exists) $cache[$key] = true;
    return $exists;
  }
}

if (!function_exists('table_exists')) {
  function table_exists(mysqli $conn, string $table): bool {
    static $cache = [];
    $key = spl_object_id($conn) . '|' . $table;
    if (!empty($cache[$key])) return true;

    $tableEsc = $conn->real_escape_string($table);
    $q = @$conn->query("SELECT 1 FROM INFORMATION_SCHEMA.TABLES
      WHERE TABLE_SCHEMA = DATABASE()
        AND TABLE_NAME = '$tableEsc'
      LIMIT 1");
    $exists = ($q && $q->num_rows > 0);
    if ($exists) $cache[$key] = true;
    return $exists;
  }
}
