<?php
declare(strict_types=1);

/* Use a distinct session to avoid RMS leakage */
if (session_status() !== PHP_SESSION_ACTIVE) {
  session_name('ELMSSESSID');
  session_start();
}

/* Pull canonical role + user id */
function elms_user_id(): int { return (int)($_SESSION['elms_user']['id'] ?? 0); }
function elms_role(): string { return (string)($_SESSION['elms_user']['role_code'] ?? ''); }

/* Quick checks */
function elms_is(string $role): bool { return elms_role() === $role; }
function elms_is_any(array $roles): bool { return in_array(elms_role(), $roles, true); }

/* Require certain roles */
function elms_require(array $allowed): void {
  if (!elms_is_any($allowed)) {
    http_response_code(403);
    exit('403 — Forbidden');
  }
}

/* ---- DB handle ---- */
function elms_db(): mysqli {
  static $db;
  if ($db instanceof mysqli) return $db;
  // Prefer your existing includes/db.php that sets $conn
  $maybe = __DIR__ . '/db.php';
  if (is_file($maybe)) {
    require_once $maybe;
    if (isset($conn) && $conn instanceof mysqli) { $db = $conn; return $db; }
  }
  // Fallback (adjust if needed)
  $db = new mysqli("localhost","root","","edencamp_edencampus");
  if ($db->connect_error) { die("DB error: ".$db->connect_error); }
  $db->set_charset('utf8mb4');
  return $db;
}

/* ---- Branch scope: Admin/Coordinator/Lecturer may be scoped to branches ----
 * user_scopes: (user_id, 'branch', scope_id)
 */
function elms_branch_scope_ids(): array {
  $uid = elms_user_id();
  if ($uid <= 0) return [];
  $db = elms_db();
  $out = [];
  if ($st = $db->prepare("SELECT scope_id FROM elms_user_scopes WHERE user_id=? AND scope_type='branch'")) {
    $st->bind_param('i', $uid);
    $st->execute();
    $rs = $st->get_result();
    while ($r = $rs->fetch_row()) { $out[] = (int)$r[0]; }
    $st->close();
  }
  return $out; // empty => global access (for super_admin) or no scope set yet
}

/* Build SQL fragment to restrict by branch scope via batches.branch_id */
function elms_sql_branch_scope_clause(string $aliasBatches = 'b'): string {
  $scope = elms_branch_scope_ids();
  if (elms_is('super_admin') || empty($scope)) return '1=1';
  $in = implode(',', array_map('intval', $scope));
  return "$aliasBatches.branch_id IN ($in)";
}

/* ---- Audit helper (thin wrapper; see audit.php for richer logging) ---- */
function elms_audit(string $action, ?string $targetType=null, ?string $targetId=null, array $details=[]): void {
  require_once __DIR__ . '/audit.php';
  elms_audit_log($action, $targetType, $targetId, $details);
}

/* ---- Read-only impersonation session flags ---- */
function elms_is_impersonating(): bool { return !empty($_SESSION['impersonate']); }
function elms_impersonation_readonly(): bool { return (bool)($_SESSION['impersonate']['readonly'] ?? true); }
