<?php
/* Admin › Courses › Modules
 * Minimal: choose a semester number per module (writes only to elms_module_semesters)
 * - Reads: courses, lms_modules (or course_modules)
 * - Writes: elms_module_semesters  (NO RMS touch)
 */
declare(strict_types=1);
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']);
}

/* 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 && $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 (bool)($q && $q->num_rows);
}

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

/* ensure mapping table (module_id PK) */
$mysqli->query("
CREATE TABLE IF NOT EXISTS `elms_module_semesters` (
  `module_id`   INT(11)     NOT NULL,
  `semester_no` TINYINT(4)  NOT NULL DEFAULT 1,
  `updated_at`  TIMESTAMP   NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `position`    INT(11)     NOT NULL DEFAULT 0,
  PRIMARY KEY (`module_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/* modules table */
$MOD_TBL = null;
foreach (['lms_modules','course_modules'] as $t) {
  if (t_exists($mysqli,$t) && c_exists($mysqli,$t,'id') && c_exists($mysqli,$t,'course_id')) { $MOD_TBL=$t; break; }
}
if (!$MOD_TBL) { http_response_code(500); exit('No modules table found.'); }
$TITLE_COL = c_exists($mysqli,$MOD_TBL,'title') ? 'title' : (c_exists($mysqli,$MOD_TBL,'name') ? 'name' : 'id');
$ORDER_COL = c_exists($mysqli,$MOD_TBL,'sort_order') ? 'sort_order' : 'id';

/* course name + how many semesters to show */
$course_name = 'Course #'.$course_id; $SEM_COUNT = 8;
if (t_exists($mysqli,'courses')) {
  $st=$mysqli->prepare("SELECT COALESCE(course_name, CONCAT('Course ',id)) AS nm, COALESCE(months, duration, 8) AS mm FROM courses WHERE id=? LIMIT 1");
  $st->bind_param('i',$course_id); $st->execute();
  $res=$st->get_result(); if ($res && ($row=$res->fetch_assoc())) { $course_name=$row['nm']; $SEM_COUNT=max(1,(int)$row['mm']); }
  $st->close();
}

/* POST: save assignments */
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST' && ($_POST['action'] ?? '') === 'save_assignments') {
  if ((int)($_POST['course_id'] ?? 0) !== $course_id) { http_response_code(400); exit('Bad course'); }
  $pairs = isset($_POST['sem']) && is_array($_POST['sem']) ? $_POST['sem'] : [];

  // whitelist module ids for this course
  $allow = [];
  $q=$mysqli->prepare("SELECT id FROM `$MOD_TBL` WHERE course_id=?");
  $q->bind_param('i',$course_id); $q->execute();
  $rs=$q->get_result(); while($r=$rs->fetch_assoc()) $allow[(int)$r['id']] = 1; $q->close();

  $ins=$mysqli->prepare("
    INSERT INTO elms_module_semesters (module_id, semester_no, position)
    VALUES (?, ?, 0)
    ON DUPLICATE KEY UPDATE semester_no=VALUES(semester_no)
  ");
  $n=0;
  foreach ($pairs as $midStr=>$semStr){
    $mid=(int)$midStr; if (!isset($allow[$mid])) continue;
    $sem=max(1, min(99, (int)$semStr));
    $ins->bind_param('ii',$mid,$sem); $ins->execute(); $n++;
  }
  $ins->close();
  header("Location: modules.php?course_id={$course_id}&saved={$n}"); exit;
}

/* fetch modules + current mapping */
$mods=[];
$st=$mysqli->prepare("SELECT id, `$TITLE_COL` AS title FROM `$MOD_TBL` WHERE course_id=? ORDER BY `$ORDER_COL`, id");
$st->bind_param('i',$course_id); $st->execute();
$r=$st->get_result(); while($m=$r->fetch_assoc()){ $mods[(int)$m['id']] = ['id'=>(int)$m['id'], 'title'=>$m['title'], 'sem'=>1]; }
$st->close();

if ($mods){
  $ids = implode(',', array_map('intval', array_keys($mods)));
  $qr = $mysqli->query("SELECT module_id, semester_no FROM elms_module_semesters WHERE module_id IN ($ids)");
  while($x=$qr->fetch_assoc()){ $mods[(int)$x['module_id']]['sem'] = (int)$x['semester_no']; }
}

$saved = (int)($_GET['saved'] ?? 0);

/* layout – keep your admin chrome */
$PAGE_TITLE = 'Semesters & Modules';
$ACTIVE_MENU = 'courses';
$__layoutOpened=false;
foreach(['admin_layout_top.php','layout_top.php','admin_header.php','header_admin.php'] as $f){
  $p=__DIR__.'/../../includes/'.$f; if(is_file($p)){ require_once $p; $__layoutOpened=true; break; }
}
if(!$__layoutOpened) echo '<div class="container-fluid p-3">'; ?>
<style>.hint{color:#6b7280}</style>

<div class="d-flex align-items-center justify-content-between mb-3">
  <h1 class="h5 m-0"><?= esc($PAGE_TITLE) ?> — <span class="text-muted"><?= esc($course_name) ?></span></h1>
  <a href="index.php" class="btn btn-outline-secondary btn-sm">← Back</a>
</div>

<?php if ($saved): ?><div class="alert alert-success py-2"><?= (int)$saved ?> change(s) saved.</div><?php endif; ?>

<div class="card">
  <div class="card-header d-flex align-items-center justify-content-between">
    <strong>Assign semester numbers</strong>
    <div class="hint small">Writes only to <code>elms_module_semesters</code></div>
  </div>
  <form method="post">
    <input type="hidden" name="action" value="save_assignments">
    <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
    <div class="table-responsive">
      <table class="table table-striped table-hover align-middle m-0">
        <thead class="table-light"><tr><th style="width:70%">Module</th><th style="width:30%">Semester</th></tr></thead>
        <tbody>
        <?php if (!$mods): ?>
          <tr><td colspan="2" class="text-muted">No modules yet for this course.</td></tr>
        <?php else: foreach ($mods as $m): ?>
          <tr>
            <td><?= esc($m['title']) ?></td>
            <td>
              <select class="form-select" name="sem[<?= (int)$m['id'] ?>]">
                <?php for($i=1; $i<=$SEM_COUNT; $i++): ?>
                  <option value="<?= $i ?>" <?= ($i===$m['sem'])?'selected':'' ?>>Semester <?= $i ?></option>
                <?php endfor; ?>
                <option value="<?= $SEM_COUNT+1 ?>">Semester <?= $SEM_COUNT+1 ?>+</option>
              </select>
            </td>
          </tr>
        <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
    <div class="card-footer d-flex justify-content-end"><button class="btn btn-primary">Save</button></div>
  </form>
</div>

<?php
$__layoutClosed=false;
foreach(['admin_layout_bottom.php','layout_bottom.php','admin_footer.php','footer_admin.php'] as $f){
  $p=__DIR__.'/../../includes/'.$f; if(is_file($p)){ require_once $p; $__layoutClosed=true; break; }
}
if(!$__layoutClosed) echo '</div>';
