<?php
// includes/coordinator_auth.php

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

require_once __DIR__ . '/db.php';

if (!function_exists('h')) {
    function h($value) {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

$user_id = $_SESSION['user_id']
    ?? $_SESSION['admin_id']
    ?? ($_SESSION['user']['id'] ?? null);

$role = strtolower((string)(
    $_SESSION['user_role']
    ?? $_SESSION['admin_role']
    ?? $_SESSION['role']
    ?? ($_SESSION['user']['role'] ?? '')
));

if ($role === 'course_coordinator') {
    $role = 'coordinator';
}

if (empty($user_id) || $role !== 'coordinator') {
    header("Location: /elms/coordinator/login.php");
    exit;
}

$_SESSION['user_id']   = $user_id;
$_SESSION['user_role'] = 'coordinator';

if (empty($_SESSION['user_name'])) {
    $_SESSION['user_name'] = $_SESSION['admin_name']
        ?? ($_SESSION['user']['name'] ?? 'Coordinator');
}