<?php
require_once __DIR__ . "/auth.php";
require_role(['super','admin']);
require_once __DIR__ . "/../includes/db.php";

/* ---- get mysqli $conn safely ---- */
if (!isset($conn) || !($conn instanceof mysqli)) {
  if (function_exists('db')) { $conn = db(); }
}
if (!($conn instanceof mysqli)) { die("DB connection missing."); }

/* ---- auth ---- */
if (!isset($_SESSION['admin'])) { header("Location: index.php"); exit; }

/* ---- helpers ---- */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

function colExists(mysqli $db, string $table, string $col): bool {
  static $cache=[]; $k="$table.$col";
  if(isset($cache[$k])) return $cache[$k];
  $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
                    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
  $st->bind_param("ss",$table,$col); $st->execute();
  $r=$st->get_result();
  return $cache[$k]=($r && $r->num_rows>0);
}
function tableExists(mysqli $db, string $table): bool {
  $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES
                    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME=? LIMIT 1");
  $st->bind_param("s",$table); $st->execute();
  $r=$st->get_result();
  return ($r && $r->num_rows>0);
}

/* ---- feature flags / schema checks ---- */
$HAS_UNITS_COURSE_NAME = colExists($conn,'units','course_name');
$HAS_COURSE_MODULES    = tableExists($conn,'course_modules');
$HAS_UNITS_MODULE_ID   = colExists($conn,'units','module_id');

/* ---- ensure units.module_id exists (nullable) if course_modules table exists ---- */
if ($HAS_COURSE_MODULES && !$HAS_UNITS_MODULE_ID) {
  try {
    $conn->query("ALTER TABLE `units`
                    ADD COLUMN `module_id` INT NULL DEFAULT NULL,
                    ADD KEY `idx_units_module` (`module_id`)");
    try {
      $conn->query("ALTER TABLE `units`
                      ADD CONSTRAINT `fk_units_module`
                      FOREIGN KEY (`module_id`) REFERENCES `course_modules`(`id`)
                      ON UPDATE CASCADE ON DELETE SET NULL");
    } catch (Throwable $e) { /* ignore if FK cannot be added */ }
    $HAS_UNITS_MODULE_ID = true;
  } catch (Throwable $e) { /* ignore if no perms */ }
}

$message = "";

/* ======================================================================
   UNITS: Add / Update / Delete
   ====================================================================== */

/* ADD */
if (isset($_POST['add_unit'])) {
  $course_id = (int)($_POST['unit_course_id'] ?? 0);
  $unit_name = trim($_POST['unit_name'] ?? "");
  $module_id = (int)($_POST['unit_module_id'] ?? 0);

  if ($course_id && $unit_name !== "") {
    $chk = $conn->prepare("SELECT course_name FROM courses WHERE id=?");
    $chk->bind_param("i", $course_id);
    $chk->execute(); $courseRow = $chk->get_result()->fetch_assoc();

    if (!$courseRow) {
      $message = "<div class='alert alert-danger mb-3'>Invalid course selected.</div>";
    } else {
      if ($HAS_UNITS_COURSE_NAME && $HAS_UNITS_MODULE_ID) {
        $st = $conn->prepare("INSERT INTO units (course_id, name, course_name, module_id) VALUES (?,?,?,?)");
        $st->bind_param("issi", $course_id, $unit_name, $courseRow['course_name'], $module_id);
      } elseif ($HAS_UNITS_COURSE_NAME) {
        $st = $conn->prepare("INSERT INTO units (course_id, name, course_name) VALUES (?,?,?)");
        $st->bind_param("iss", $course_id, $unit_name, $courseRow['course_name']);
      } elseif ($HAS_UNITS_MODULE_ID) {
        $st = $conn->prepare("INSERT INTO units (course_id, name, module_id) VALUES (?,?,?)");
        $st->bind_param("isi", $course_id, $unit_name, $module_id);
      } else {
        $st = $conn->prepare("INSERT INTO units (course_id, name) VALUES (?,?)");
        $st->bind_param("is", $course_id, $unit_name);
      }
      $message = $st->execute()
        ? "<div class='alert alert-success mb-3'>Unit added.</div>"
        : "<div class='alert alert-danger mb-3'>".$conn->error."</div>";
    }
  }
}

/* UPDATE */
if (isset($_POST['update_unit'])) {
  $id        = (int)($_POST['unit_id'] ?? 0);
  $course_id = (int)($_POST['unit_course_id'] ?? 0);
  $unit_name = trim($_POST['unit_name'] ?? "");
  $module_id = (int)($_POST['unit_module_id'] ?? 0);

  if ($id && $course_id && $unit_name !== "") {
    if ($HAS_UNITS_COURSE_NAME && $HAS_UNITS_MODULE_ID) {
      $st = $conn->prepare("
        UPDATE units u
        JOIN courses c ON c.id = ?
        SET u.course_id   = c.id,
            u.name        = ?,
            u.course_name = c.course_name,
            u.module_id   = ?
        WHERE u.id = ?
      ");
      $st->bind_param("isii", $course_id, $unit_name, $module_id, $id);
    } elseif ($HAS_UNITS_COURSE_NAME) {
      $st = $conn->prepare("
        UPDATE units u
        JOIN courses c ON c.id = ?
        SET u.course_id   = c.id,
            u.name        = ?,
            u.course_name = c.course_name
        WHERE u.id = ?
      ");
      $st->bind_param("isi", $course_id, $unit_name, $id);
    } elseif ($HAS_UNITS_MODULE_ID) {
      $st = $conn->prepare("UPDATE units SET course_id=?, name=?, module_id=? WHERE id=?");
      $st->bind_param("isii", $course_id, $unit_name, $module_id, $id);
    } else {
      $st = $conn->prepare("UPDATE units SET course_id=?, name=? WHERE id=?");
      $st->bind_param("isi", $course_id, $unit_name, $id);
    }
    $message = $st->execute()
      ? "<div class='alert alert-info mb-3'>Unit updated.</div>"
      : "<div class='alert alert-danger mb-3'>".$conn->error."</div>";
  }
}

/* DELETE — accept POST or GET */
$delId = 0;
if (isset($_POST['del_unit'])) { $delId = (int)$_POST['del_unit']; }
elseif (isset($_GET['del_unit'])) { $delId = (int)$_GET['del_unit']; }

if ($delId) {
  $st = $conn->prepare("DELETE FROM units WHERE id=?");
  $st->bind_param("i", $delId);
  $message = $st->execute()
    ? "<div class='alert alert-warning mb-3'>Unit deleted.</div>"
    : "<div class='alert alert-danger mb-3'>Cannot delete (FK link or rule). ".$conn->error."</div>";
}

/* ======================================================================
   Data for UI
   ====================================================================== */
$courseRows = [];
$cq = $conn->query("SELECT id, course_name FROM courses ORDER BY course_name ASC");
if ($cq) { while($r=$cq->fetch_assoc()) $courseRows[] = $r; }

$units = $conn->query("
  SELECT u.id, u.name AS unit_name, u.course_id, ".($HAS_UNITS_MODULE_ID ? "u.module_id," : "")." c.course_name
  FROM units u
  LEFT JOIN courses c ON c.id = u.course_id
  ORDER BY c.course_name ASC, u.name ASC, u.id DESC
");

/* build modules-by-course map for client filter */
$modsByCourse = [];
if ($HAS_COURSE_MODULES) {
  $res = $conn->query("SELECT id, course_id, title
                         FROM course_modules
                        ORDER BY course_id, sort_order, title, id");
  while ($res && $row = $res->fetch_assoc()) {
    $modsByCourse[(int)$row['course_id']][] = [
      'id'    => (int)$row['id'],
      'title' => $row['title']
    ];
  }
}

$self = basename($_SERVER['PHP_SELF']);
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Units Manager</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    .form-inline-gap{gap:.5rem}
    .table td { vertical-align: middle; }
    .nowrap { white-space: nowrap; }
  </style>
</head>
<body class="bg-light">
  <?php include __DIR__ . '/../includes/topbar.php'; ?>

<div class="container py-4">

  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="m-0">Units Manager</h3>
    <div class="d-flex gap-2">
      <a href="dashboard.php" class="btn btn-outline-secondary btn-sm">Dashboard</a>
      <a href="create_exam.php" class="btn btn-outline-primary btn-sm">Create Exam</a>
    </div>
  </div>

  <?= $message ?>

  <div class="card shadow-sm">
    <div class="card-header">Units</div>
    <div class="card-body">

      <?php if (empty($courseRows)): ?>
        <div class="alert alert-warning">No courses found. Please add courses first.</div>
      <?php endif; ?>

      <!-- Top bar: Course -> Module -> Unit name -> Add -->
      <form method="post" class="row g-2 mb-3 align-items-center" id="addForm" action="<?= h($self) ?>">
        <div class="col-lg-4">
          <select name="unit_course_id" id="unit_course_id" class="form-select" required>
            <option value="">-- Select Course --</option>
            <?php foreach($courseRows as $row): ?>
              <option value="<?= (int)$row['id'] ?>"><?= h($row['course_name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-lg-5">
          <select id="module_picker" name="unit_module_id" class="form-select" <?= $HAS_COURSE_MODULES ? '' : 'disabled' ?>>
            <option value=""><?= $HAS_COURSE_MODULES ? 'No modules for this course' : 'No course_modules table found' ?></option>
          </select>
        </div>
        <div class="col-lg-2">
          <input type="text" name="unit_name" id="unit_name" class="form-control" placeholder="Unit name" required>
        </div>
        <div class="col-lg-1">
          <button type="submit" class="btn btn-success w-100" name="add_unit" value="1">Add</button>
        </div>
      </form>

      <!-- Table -->
      <div class="table-responsive">
        <table class="table table-striped align-middle">
          <thead class="table-light">
            <tr>
              <th style="width:33%">Course</th>
              <th style="width:33%">Unit name</th>
              <th style="width:19%">Module</th>
              <th style="width:15%" class="text-end">Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php if ($units && $units->num_rows): while($u=$units->fetch_assoc()):
            $uid = (int)$u['id']; $formId = "upd-$uid";
            $selMod = $HAS_UNITS_MODULE_ID ? (int)$u['module_id'] : 0; ?>
            <tr data-row="<?= $uid ?>" <?= $HAS_UNITS_MODULE_ID ? 'data-selected-module="'.$selMod.'"' : '' ?>>
              <td>
                <select name="unit_course_id" class="form-select course-select" data-row="<?= $uid ?>" form="<?= $formId ?>">
                  <?php foreach($courseRows as $row2):
                    $sel = ((int)$row2['id'] === (int)$u['course_id']) ? 'selected' : ''; ?>
                    <option value="<?= (int)$row2['id'] ?>" <?= $sel ?>><?= h($row2['course_name']) ?></option>
                  <?php endforeach; ?>
                </select>
              </td>
              <td>
                <input type="hidden" name="unit_id" value="<?= $uid ?>" form="<?= $formId ?>">
                <input type="text" name="unit_name" class="form-control unit-input"
                       data-row="<?= $uid ?>" value="<?= h($u['unit_name']) ?>" required form="<?= $formId ?>">
              </td>
              <td class="nowrap">
                <select class="form-select module-picker" name="unit_module_id" data-row="<?= $uid ?>" form="<?= $formId ?>"></select>
              </td>
              <td class="text-end">
                <form method="post" id="<?= $formId ?>" class="d-inline" action="<?= h($self) ?>">
                  <button type="submit" class="btn btn-warning btn-sm" name="update_unit" value="1">Update</button>
                </form>
                <form method="post" class="d-inline" action="<?= h($self) ?>" onsubmit="return confirm('Delete unit?');">
                  <input type="hidden" name="del_unit" value="<?= $uid ?>">
                  <button type="submit" class="btn btn-danger btn-sm">Delete</button>
                </form>
              </td>
            </tr>
          <?php endwhile; else: ?>
            <tr><td colspan="4">No units yet.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>

    </div>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<?php if ($HAS_COURSE_MODULES): ?>
<script>
/* Map of course_id -> [{id, title}, ...] from PHP */
const MODS_BY_COURSE = <?= json_encode($modsByCourse, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE) ?>;

/* Populate a module <select> for a course; optional preselect; DO NOT overwrite unit name here */
function populateModuleSelect(selectEl, courseId, preselectId) {
  if (!selectEl) return;
  const cid = parseInt(courseId || '0', 10);
  selectEl.innerHTML = '';
  const opt0 = document.createElement('option');
  opt0.value = '';
  opt0.textContent = '-- Select course modules --';
  selectEl.appendChild(opt0);

  const list = MODS_BY_COURSE[cid] || [];
  if (!list.length) {
    selectEl.disabled = true;
    opt0.textContent = 'No modules for this course';
    return;
  }
  selectEl.disabled = false;
  for (const m of list) {
    const o = document.createElement('option');
    o.value = m.id;
    o.textContent = m.title;
    selectEl.appendChild(o);
  }
  if (preselectId) {
    selectEl.value = String(preselectId); // preselect only; DO NOT change the unit input here
  }
}

/* Add form: update modules when course changes (no auto-fill for Unit name) */
(function(){
  const addCourseSel = document.getElementById('unit_course_id');
  const addModuleSel = document.getElementById('module_picker');
  function refresh(){ populateModuleSelect(addModuleSel, addCourseSel.value, null); }
  addCourseSel && addCourseSel.addEventListener('change', refresh);
  refresh();
})();

/* Table rows: populate, preselect saved module_id; changing module copies title -> Unit name */
(function(){
  document.querySelectorAll('tr[data-row]').forEach(row => {
    const rid       = row.getAttribute('data-row');
    const courseSel = row.querySelector('.course-select');
    const moduleSel = row.querySelector('.module-picker');
    const unitInput = row.querySelector('.unit-input');
    const savedModId = parseInt(row.getAttribute('data-selected-module') || '0', 10);

    function refreshModules(){ populateModuleSelect(moduleSel, courseSel.value, savedModId || null); }
    function copyModuleTitle(){
      const txt = moduleSel.options[moduleSel.selectedIndex]?.text || '';
      if (txt) unitInput.value = txt; // only when the user changes module
    }

    courseSel && courseSel.addEventListener('change', () => populateModuleSelect(moduleSel, courseSel.value, null));
    moduleSel && moduleSel.addEventListener('change', copyModuleTitle);

    // initial fill & preselect without touching unit name
    refreshModules();
  });
})();
</script>
<?php endif; ?>
</body>
</html>
