<?php
// /elms/coordinator/_common.php  — PHP-7 compatible
declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();

/* ---------- DB ---------- */
$mysqli = null;
$inc = __DIR__ . '/../includes/db.php';
if (is_file($inc)) {
  require_once $inc;                 // your project usually defines $conn (mysqli)
  if (isset($conn) && $conn instanceof mysqli) {
    $mysqli = $conn;
  }
}
if (!$mysqli) {
  $mysqli = @new mysqli("localhost", "root", "", "edencamp_edencampus");
}
if ($mysqli->connect_errno) {
  http_response_code(500);
  echo "DB connect failed: (" . (int)$mysqli->connect_errno . ") " . htmlspecialchars($mysqli->connect_error, ENT_QUOTES, 'UTF-8');
  exit;
}
$mysqli->set_charset('utf8mb4');

/* ---------- Utils ---------- */
function h($s) { return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

function qcount(mysqli $db, string $sql, array $params = [], string $types = ''): int {
  $st = $db->prepare($sql);
  if ($params) { $st->bind_param($types ? $types : str_repeat('s', count($params)), ...$params); }
  $st->execute();
  $res = $st->get_result();
  $n = 0;
  if ($res) {
    $row = $res->fetch_row();
    if ($row && isset($row[0])) { $n = (int)$row[0]; }
  }
  $st->close();
  return $n;
}

function qall(mysqli $db, string $sql, array $params = [], string $types = ''): array {
  $st = $db->prepare($sql);
  if ($params) { $st->bind_param($types ? $types : str_repeat('s', count($params)), ...$params); }
  $st->execute();
  $res = $st->get_result();
  $rows = [];
  if ($res) { while ($row = $res->fetch_assoc()) { $rows[] = $row; } }
  $st->close();
  return $rows;
}

/* ---------- Auth ---------- */
function ec_current_role(): ?string {
  $r = isset($_SESSION['role']) ? $_SESSION['role'] : (isset($_SESSION['user']['role']) ? $_SESSION['user']['role'] : null);
  if (is_array($r)) { return isset($r[0]) ? (string)$r[0] : null; }
  return $r ? (string)$r : null;
}

function ec_require_coordinator(): void {
  $role = ec_current_role();
  $ok   = in_array((string)$role, ['coordinator','course_coordinator'], true);
  if (!$ok) { header('Location: /elms/coordinator/login.php'); exit; }  // <-- never go to /elms/admin/*
}

/* ---------- Branch scope ---------- */
function coord_branch_scope(string $alias = 'b'): array {
  $ids = [];
  if (!empty($_SESSION['branch_ids']) && is_array($_SESSION['branch_ids'])) {
    foreach ($_SESSION['branch_ids'] as $v) { $ids[] = (int)$v; }
  } else {
    $s = isset($_SESSION['user']['branch_ids']) ? (string)$_SESSION['user']['branch_ids'] : '';
    if ($s !== '') {
      foreach (explode(',', $s) as $v) { $v = trim($v); if ($v !== '') $ids[] = (int)$v; }
    } elseif (isset($_SESSION['user']['branch_id'])) {
      $ids[] = (int)$_SESSION['user']['branch_id'];
    }
  }
  if (!$ids) { return ['1=1', []]; } // change to ['0=1', []] if you want deny-by-default
  $ph = implode(',', array_fill(0, count($ids), '?'));
  return ["{$alias}.branch_id IN ($ph)", $ids];
}

/* ---------- Optional schema helpers ---------- */
function tbl(mysqli $db, string $t): bool {
  $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? LIMIT 1");
  $st->bind_param('s', $t); $st->execute();
  $res = $st->get_result(); $ok = false;
  if ($res) { $row = $res->fetch_row(); $ok = (bool)$row; }
  $st->close(); return $ok;
}
function col(mysqli $db, string $t, string $c): bool {
  $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ? LIMIT 1");
  $st->bind_param('ss', $t, $c); $st->execute();
  $res = $st->get_result(); $ok = false;
  if ($res) { $row = $res->fetch_row(); $ok = (bool)$row; }
  $st->close(); return $ok;
}
