<?php
declare(strict_types=1);

// Use the existing connection & helpers loaded elsewhere
// (index/admin pages already require auth.php, db.php, helpers.php)
if (!isset($mysqli)) {
  // Fallback only if this file is executed standalone
  @require_once __DIR__ . '/db.php';
}
if (!function_exists('table_exists') || !function_exists('column_exists')) {
  // Fallback to avoid fatals if helpers weren't included yet
  @require_once __DIR__ . '/helpers.php';
}

/**
 * Run a COUNT(*) (or any single-int) KPI query safely.
 * Example:
 *   $n = kpi_count("SELECT COUNT(*) FROM enrollments WHERE batch_id = ?", fn($st)=>$st->bind_param('i', $bid));
 */
function kpi_count(string $sql, ?callable $binder = null): int {
  global $mysqli;
  try {
    $stmt = $mysqli->prepare($sql);
    if ($binder) { $binder($stmt); }
    $stmt->execute();
    $stmt->bind_result($c);
    if ($stmt->fetch()) { return (int)$c; }
    return 0;
  } catch (Throwable $e) {
    return 0;
  }
}

/* Optional: KPI helpers that USE existing table_exists/column_exists without redefining them */

// Example:
// function kpi_table_has_rows(string $table): bool {
//   if (!table_exists($table)) return false;
//   global $mysqli;
//   $sql = "SELECT 1 FROM `{$table}` LIMIT 1";
//   try { $res = $mysqli->query($sql); return (bool)$res->fetch_row(); } catch (Throwable $e) { return false; }
// }
