<?php
// /elms/includes/auth.php  — unified auth helpers for ELMS
// ----------------------------------------------------------
if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }

/* App base (works even if ELMS is in /admin.edencampus.lk/elms) */
function _app_base(): string {
  $base = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/');
  // strip module folders to return to the app root
  $base = preg_replace('#/(admin|lecturer|coordinator|student)(/.*)?$#', '', $base);
  return $base === '' ? '/' : $base;
}

/* url_for — keep only one definition app-wide */
if (!function_exists('url_for')) {
  function url_for(string $path): string {
    if ($path === '' || $path[0] !== '/') $path = '/'.$path;
    return _app_base().$path;
  }
}

/* ---- Roles ---- */
function role_slug(?string $r): string {
  $r = strtolower(trim((string)$r));
  $map = [
    'super admin' => 'super_admin',
    'superadmin'  => 'super_admin',
    'branch admin'=> 'branch_admin',
    'course coordinator' => 'course_coordinator',
    'coordinator' => 'coordinator',
    'lecturer'    => 'lecturer',
    'admin'       => 'admin',
    'student'     => 'student',
  ];
  return $map[$r] ?? $r;
}

/* Current user helpers (support several session shapes) */
function current_user_id(): ?int {
  if (isset($_SESSION['user_id'])) return (int)$_SESSION['user_id'];
  if (isset($_SESSION['user']['id'])) return (int)$_SESSION['user']['id'];
  if (isset($_SESSION['student_id'])) return (int)$_SESSION['student_id']; // student portal
  return null;
}
function current_user_role(): string {
  $r = $_SESSION['role'] ?? ($_SESSION['user_role'] ?? ($_SESSION['user']['role'] ?? 'guest'));
  return role_slug((string)$r);
}
function is_logged_in(): bool { return current_user_id() !== null; }

/* Staff convenience */
function can_grade(): bool {
  // your rule: lecturer + coordinator can grade
  return in_array(current_user_role(), ['lecturer','coordinator','course_coordinator'], true);
}
function can_approve(): bool {
  // your rule: only coordinator (or course_coordinator)
  return in_array(current_user_role(), ['coordinator','course_coordinator'], true);
}

/**
 * Gate a page to certain roles.
 * If not logged in → redirect to correct login with ?next=
 *   use student login when $allowed is only ['student'] or $loginTarget === 'student'
 */
function require_role(array $allowed, ?string $loginTarget = 'auto'): void {
  $allowed = array_map('role_slug', $allowed);
  $have    = current_user_role();

  if ($have !== 'guest' && in_array($have, $allowed, true)) return;

  $studentOnly = (count(array_diff($allowed, ['student'])) === 0);
  $login = '/auth/login.php';                            // staff login by default
  if ($loginTarget === 'student' || ($loginTarget === 'auto' && $studentOnly)) {
    $login = '/student/login.php';
  }

  $next = urlencode($_SERVER['REQUEST_URI'] ?? '/');
  header('Location: ' . url_for($login) . '?next=' . $next);
  exit;
}
 
// auth.php — canonical RBAC helpers
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
require_once __DIR__ . '/config.php';

/* Fallback URL helpers (in case helpers.php wasn't loaded yet) */
if (!function_exists('app_url')) {
  function app_url(string $path=''): string {
    $p = ($path !== '' && $path[0] !== '/') ? '/'.$path : $path;
    $base = defined('BASE_URL') ? BASE_URL : '';
    return $base . $p;
  }
}
if (!function_exists('go')) {
  function go(string $path='/'){ header('Location: '.app_url($path)); exit; }
}

/* RBAC */
if (!function_exists('has_role')) {
  /** @param string|array $roles */
  function has_role($roles): bool {
    $have  = $_SESSION['user']['role'] ?? ($_SESSION['role_code'] ?? '');
    $roles = is_array($roles) ? $roles : [$roles];
    return in_array($have, $roles, true);
  }
}
if (!function_exists('require_role')) {
  /** @param string|array $roles */
  function require_role($roles, bool $redirect = true): bool {
    $ok = has_role($roles);
    if (!$ok && $redirect) { go('/'); }
    return $ok;
  }
}



 
if (session_status() === PHP_SESSION_NONE) session_start();

function ec_is_logged_in(){ return !empty($_SESSION['user']); }
function ec_current_user(){ return $_SESSION['user'] ?? null; }

function ec_require_login(){
  if (!ec_is_logged_in()){
    header('Location: /elms/admin/coordinator/login.php'); // <-- your preferred login URL
    exit;
  }
}












