<?php declare(strict_types=1);
/* ELMS Admin → Courses → Semesters & Modules (drag & drop, safe)
 * Reads:  courses, lms_semesters, course_modules (or your modules table)
 * Writes: lms_semester_modules (ELMS-only, auto-create if missing)
 * RMS:    NEVER touched.
 */

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

require_once __DIR__ . '/../../includes/db.php';
if (is_file(__DIR__ . '/../../includes/auth.php')) {
  require_once __DIR__ . '/../../includes/auth.php';
  if (function_exists('require_role')) require_role(['super_admin','branch_admin']);
}

header('Content-Type: text/html; charset=utf-8');

/* ---------- helpers ---------- */
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }
function t_exists(mysqli $db,string $t):bool{
  $t=$db->real_escape_string($t);
  $q=$db->query("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t' LIMIT 1");
  return (bool)$q->num_rows;
}
function c_exists(mysqli $db,string $t,string $c):bool{
  $t=$db->real_escape_string($t); $c=$db->real_escape_string($c);
  $q=$db->query("SHOW COLUMNS FROM `$t` LIKE '$c'"); return $q?(bool)$q->num_rows:false;
}
function first_available_col(mysqli $db,string $tbl,array $cands, string $fallback='id'): string {
  foreach ($cands as $c) if (c_exists($db,$tbl,$c)) return $c;
  return $fallback;
}

/* ---------- schema ensure (ELMS-only) ---------- */
function ensure_sem_mod_schema(mysqli $db): void {
  if (!t_exists($db,'lms_semester_modules')) {
    $db->query("CREATE TABLE `lms_semester_modules`(
      `id` INT AUTO_INCREMENT PRIMARY KEY,
      `course_id` INT NOT NULL,
      `semester_id` INT NOT NULL,
      `module_id` INT NOT NULL,
      `sort_order` INT NOT NULL DEFAULT 0,
      UNIQUE KEY uq (`course_id`,`semester_id`,`module_id`),
      KEY k1 (`course_id`,`semester_id`),
      KEY k2 (`module_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
  }
}
function ensure_semesters_seed_if_empty(mysqli $db, int $course_id): void {
  if (!t_exists($db,'lms_semesters')) return;
  $st=$db->prepare("SELECT COUNT(*) FROM lms_semesters WHERE course_id=?");
  $st->bind_param('i',$course_id); $st->execute(); $st->bind_result($n); $st->fetch(); $st->close();
  if ((int)$n===0) {
    // seed lightweight defaults 1..4 (rename later if you want)
    $ins=$db->prepare("INSERT INTO lms_semesters(course_id,title,sort_order,is_released) VALUES (?,?,?,0)");
    for($i=1;$i<=4;$i++){ $title="Semester $i"; $ins->bind_param('isi',$course_id,$title,$i); $ins->execute(); }
    $ins->close();
  }
}

/* ---------- inputs ---------- */
$course_id = (int)($_GET['course_id'] ?? 0);
if ($course_id <= 0) { http_response_code(400); exit('Missing course_id'); }

/* csrf */
if (empty($_SESSION['csrf'])) $_SESSION['csrf']=bin2hex(random_bytes(16));
$CSRF=$_SESSION['csrf'];

/* course name (header) */
$course_name = 'Course #'.$course_id;
if (t_exists($mysqli,'courses') && c_exists($mysqli,'courses','course_name')) {
  $st = $mysqli->prepare("SELECT course_name FROM courses WHERE id=? LIMIT 1");
  $st->bind_param('i',$course_id); $st->execute();
  if ($r=$st->get_result()->fetch_assoc()) $course_name = (string)$r['course_name'];
  $st->close();
}

/* ---------- discover modules table + columns ----------
   Adjust the preference list if your table name differs.
-------------------------------------------------------*/
$MOD_TBL = null;
foreach (['course_modules','lms_modules','modules'] as $t) {
  if (t_exists($mysqli,$t) && c_exists($mysqli,$t,'course_id') && c_exists($mysqli,$t,'id')) { $MOD_TBL = $t; break; }
}
if (!$MOD_TBL) { http_response_code(500); exit('No modules table found.'); }

$TITLE_COL = first_available_col($mysqli,$MOD_TBL,['module_name','name','title'],'id');
$SEQ_COL   = first_available_col($mysqli,$MOD_TBL,['seq_no','sort_order','position'],'id');

/* ---------- load modules (robust against col name differences) ---------- */
$modules=[]; $validModIds=[];
$sql = "SELECT m.id, m.`$TITLE_COL` AS title, m.`$SEQ_COL` AS seq
        FROM `$MOD_TBL` m
        WHERE m.course_id=?
        ORDER BY seq, m.id";
$st=$mysqli->prepare($sql);
$st->bind_param('i',$course_id); $st->execute();
$rs=$st->get_result();
while($m=$rs->fetch_assoc()){ $modules[(int)$m['id']]=$m; $validModIds[(int)$m['id']]=true; }
$st->close();

/* ---------- POST: save drag&drop assignments ---------- */
if (($_SERVER['REQUEST_METHOD']??'')==='POST' && isset($_POST['save_dnd'])) {
  if (!hash_equals($CSRF, $_POST['csrf'] ?? '')) { http_response_code(403); exit('CSRF'); }
  if ((int)($_POST['course_id'] ?? 0) !== $course_id) { http_response_code(400); exit('Bad course_id'); }

  ensure_sem_mod_schema($mysqli);

  // payload: assign[SEM_ID][]=module_id (SEM_ID=0 means Unassigned -> skip)
  $assign = (isset($_POST['assign']) && is_array($_POST['assign'])) ? $_POST['assign'] : [];

  $mysqli->begin_transaction();
  try {
    // clear all mappings for this course
    $del=$mysqli->prepare("DELETE FROM lms_semester_modules WHERE course_id=?");
    $del->bind_param('i',$course_id); $del->execute(); $del->close();

    // insert semester→modules in posted order
    $ins=$mysqli->prepare("INSERT INTO lms_semester_modules (course_id,semester_id,module_id,sort_order) VALUES (?,?,?,?)");
    foreach ($assign as $sidStr=>$list) {
      $sid=(int)$sidStr; if (!is_array($list)) continue;
      $order=1;
      foreach ($list as $midStr) {
        $mid=(int)$midStr;
        if ($sid>0 && isset($validModIds[$mid])) {
          $ins->bind_param('iiii',$course_id,$sid,$mid,$order);
          $ins->execute(); $order++;
        }
      }
    }
    $ins->close();
    $mysqli->commit();
    // FIX: redirect back to THIS PAGE (not modules.php)
    header("Location: semesters.php?course_id=".$course_id."&saved=1"); exit;
  } catch(Throwable $e){
    $mysqli->rollback();
    http_response_code(500); exit('Save failed: '.$e->getMessage());
  }
}

/* ---------- load semesters + existing mapping ---------- */
ensure_sem_mod_schema($mysqli);

$semesters=[];
if (t_exists($mysqli,'lms_semesters')) {
  ensure_semesters_seed_if_empty($mysqli,$course_id);
  $st=$mysqli->prepare("SELECT id,title,sort_order,is_released FROM lms_semesters WHERE course_id=? ORDER BY sort_order,id");
  $st->bind_param('i',$course_id); $st->execute();
  $rs=$st->get_result(); while($x=$rs->fetch_assoc()) $semesters[]=$x; $st->close();
}
if (!$semesters) {
  // Fallback columns (no lms_semesters table) — show only "Unassigned"
  $semesters = [];
}

// mapping semester -> [module ids] (respect saved sort_order)
$by_sem=[]; $placed=[];
$st=$mysqli->prepare("SELECT semester_id,module_id FROM lms_semester_modules WHERE course_id=? ORDER BY sort_order,id");
$st->bind_param('i',$course_id); $st->execute();
$rs=$st->get_result();
while($r=$rs->fetch_assoc()){
  $sid=(int)$r['semester_id']; $mid=(int)$r['module_id'];
  if (isset($modules[$mid])) { $by_sem[$sid][]=$mid; $placed[$mid]=true; }
}
$st->close();

// unassigned = modules not in mapping
$unassigned=[]; foreach ($modules as $mid=>$m) if (empty($placed[$mid])) $unassigned[]=$mid;

$saved = isset($_GET['saved']);
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Semesters & Modules · <?= esc($course_name) ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body{ background:#f8fafc; }
    .list-col{ background:#fff; border:1px solid #e5e7eb; border-radius:12px; padding:12px; }
    .dropcol{ min-height:48px; }
    .mod{ border:1px solid #e5e7eb; border-radius:10px; padding:8px 10px; background:#ffffff; margin-bottom:6px; cursor:move; }
    .ghost{ opacity:.5; }
    .empty-hint{ color:#94a3b8; font-size:.9rem; }
  </style>
  <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.2/Sortable.min.js"></script>
</head>
<body class="container py-4">

  <div class="d-flex align-items-center mb-3">
    <h3 class="m-0">Semesters & Modules — <span class="text-muted"><?= esc($course_name) ?></span></h3>
    <a class="btn btn-outline-secondary ms-auto" href="index.php">← Back to Courses</a>
  </div>

  <?php if ($saved): ?>
    <div class="alert alert-success py-2">Assignments & order saved.</div>
  <?php endif; ?>

  <form id="formDnD" method="post">
    <input type="hidden" name="csrf" value="<?= esc($CSRF) ?>">
    <input type="hidden" name="course_id" value="<?= $course_id ?>">
    <input type="hidden" name="save_dnd" value="1">

    <div class="row g-3">

      <!-- Unassigned -->
      <div class="col-12 <?= $semesters ? 'col-md-4 col-lg-3' : '' ?>">
        <div class="list-col">
          <div class="fw-semibold mb-1">Unassigned</div>
          <div id="sem_0" class="dropcol" data-sem="0">
            <?php if (!$unassigned): ?>
              <div class="empty-hint">No modules</div>
            <?php else: foreach($unassigned as $mid): $m=$modules[$mid]; ?>
              <div class="mod" data-id="<?= (int)$m['id'] ?>"><?= esc($m['title']) ?></div>
            <?php endforeach; endif; ?>
          </div>
        </div>
      </div>

      <?php if ($semesters): ?>
        <!-- One column per semester -->
        <?php foreach($semesters as $s): $sid=(int)$s['id']; $list=$by_sem[$sid] ?? []; ?>
        <div class="col-12 col-md-4 col-lg-3">
          <div class="list-col">
            <div class="fw-semibold mb-1">
              <?= esc($s['title']) ?>
              <?php if ((int)$s['is_released']===1): ?>
                <span class="badge bg-success ms-1">Released</span>
              <?php else: ?>
                <span class="badge bg-secondary ms-1">Hidden</span>
              <?php endif; ?>
            </div>
            <div id="sem_<?= $sid ?>" class="dropcol" data-sem="<?= $sid ?>">
              <?php if (!$list): ?>
                <div class="empty-hint">Drop modules here</div>
              <?php else: foreach($list as $mid): $m=$modules[$mid]; ?>
                <div class="mod" data-id="<?= (int)$m['id'] ?>"><?= esc($m['title']) ?></div>
              <?php endforeach; endif; ?>
            </div>
          </div>
        </div>
        <?php endforeach; ?>
      <?php endif; ?>

    </div>

    <!-- hidden inputs filled before submit -->
    <div id="dndHidden"></div>

    <div class="mt-3 d-flex gap-2">
      <button class="btn btn-primary">Save</button>
      <a class="btn btn-outline-secondary" href="semesters.php?course_id=<?= $course_id ?>">Reset</a>
    </div>
  </form>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    // make each column sortable & connected
    document.querySelectorAll('.dropcol').forEach(function(col){
      new Sortable(col, {
        group: 'mods',
        animation: 150,
        ghostClass: 'ghost',
        filter: '.empty-hint',
        onAdd: refreshHints, onSort: refreshHints, onRemove: refreshHints
      });
    });

    function refreshHints(evt){
      // remove hint from any column that now has modules
      evt.to.querySelectorAll('.empty-hint').forEach(e=>e.remove());
      // if source column became empty, add hint back
      if (evt.from && ![...evt.from.children].some(x=>x.classList && x.classList.contains('mod'))) {
        const hint=document.createElement('div');
        hint.className='empty-hint'; hint.textContent='Drop modules here';
        evt.from.appendChild(hint);
      }
    }

    // serialize board → hidden inputs assign[sem_id][] = module_id
    document.getElementById('formDnD').addEventListener('submit', function(){
      const wrap=document.getElementById('dndHidden'); wrap.innerHTML='';
      document.querySelectorAll('.dropcol').forEach(function(col){
        const sid=col.getAttribute('data-sem');
        col.querySelectorAll('.mod').forEach(function(item,idx){
          const input=document.createElement('input');
          input.type='hidden'; input.name='assign['+sid+'][]';
          input.value=item.getAttribute('data-id');
          wrap.appendChild(input);
        });
      });
    });
  </script>
</body>
</html>
