<?php // /elms/includes/rms_bridge.php
declare(strict_types=1);

require_once __DIR__ . '/db.php';     // ELMS local DB ($mysqli)
require_once __DIR__ . '/rms_db.php'; // RMS readonly connection

function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'); }

/**
 * Resolve RMS student id for an ELMS student:
 * 1) check mapping table
 * 2) try by email match (ELMS studentss.email == RMS students.email)
 * 3) if found by email, store mapping
 */
function rms_resolve_student_id(mysqli $elms, mysqli $rms, int $elmsStudentId): ?int {
  // 1) mapping
  $q = $elms->prepare("SELECT rms_student_id FROM elms_student_rms_map WHERE elms_student_id=?");
  $q->bind_param('i', $elmsStudentId); $q->execute();
  $q->bind_result($rid);
  if ($q->fetch()) { $q->close(); return (int)$rid; }
  $q->close();

  // 2) find ELMS email
  $email = null;
  if ($st = $elms->prepare("SELECT email FROM studentss WHERE id=? LIMIT 1")) {
    $st->bind_param('i', $elmsStudentId);
    $st->execute(); $res = $st->get_result()->fetch_assoc();
    $st->close();
    $email = $res['email'] ?? null;
  }
  if (!$email) return null;

  // 3) RMS lookup by email (adjust RMS students table name/column if needed)
  $rid = null;
  if ($st = $rms->prepare("SELECT id FROM students WHERE email = ? LIMIT 1")) {
    $st->bind_param('s', $email);
    $st->execute(); $st->bind_result($rid);
    if ($st->fetch()) { $rid = (int)$rid; } else { $rid = null; }
    $st->close();
  }
  if (!$rid) return null;

  // 4) store mapping
  if ($ins = $elms->prepare("INSERT INTO elms_student_rms_map (elms_student_id, rms_student_id, matched_by) VALUES (?,?, 'email')
                              ON DUPLICATE KEY UPDATE rms_student_id=VALUES(rms_student_id)")) {
    $ins->bind_param('ii', $elmsStudentId, $rid);
    $ins->execute(); $ins->close();
  }
  return $rid;
}

/** Programs for ELMS student (from RMS views). Returns array of {program_id, program_name, cohort_key, enrolled_at} */
function rms_programs_for_elms_student(mysqli $elms, int $elmsStudentId): array {
  $rms = rms_connect();
  try {
    $rid = rms_resolve_student_id($elms, $rms, $elmsStudentId);
    if (!$rid) return [];

    $sql = "SELECT p.program_id, p.program_name, spe.cohort_key, spe.enrolled_at
            FROM vw_student_program_enrollments spe
            JOIN vw_programs p ON p.program_id = spe.program_id
            WHERE spe.student_id = ?
            ORDER BY p.program_name";
    $st = $rms->prepare($sql);
    $st->bind_param('i', $rid);
    $st->execute(); $rows = $st->get_result()->fetch_all(MYSQLI_ASSOC);
    $st->close();
    return $rows;
  } finally {
    $rms->close();
  }
}

/** Keep a simple session cache for the logged-in student */
function rms_cache_student_programs(mysqli $elms): array {
  if (!isset($_SESSION['user']['id'])) return [];
  if (!empty($_SESSION['rms_programs_cache']) && is_array($_SESSION['rms_programs_cache'])) {
    return $_SESSION['rms_programs_cache'];
  }
  $rows = rms_programs_for_elms_student($elms, (int)$_SESSION['user']['id']);
  $_SESSION['rms_programs_cache'] = $rows;
  return $rows;
}
