<?php
/**
 * admin/courses.php (Units-only)
 * UI:
 *  - Course dropdown (courses.course_name)
 *  - Unit dropdown (built from courses.modules)
 *  - Manual unit textbox (overrides dropdown if filled)
 *  - List of units with Update/Delete
 */

session_start();
require_once "../includes/db.php";

/* ---- mysqli handle ---- */
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 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);
}
function colExists(mysqli $db, string $table, string $col): bool {
  $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 ($r && $r->num_rows>0);
}
function parseModulesString(?string $raw): array {
  $raw = (string)$raw;
  if ($raw === '') return [];
  // if JSON array provided (like your course details), use it
  $decoded = json_decode($raw, true);
  if (is_array($decoded)) {
    // handle array of strings or array of objects with "title" or "name"
    $out=[];
    foreach ($decoded as $item) {
      if (is_array($item)) {
        $t = $item['title'] ?? ($item['name'] ?? '');
        if ($t!=='') $out[] = trim((string)$t);
      } else {
        $out[] = trim((string)$item);
      }
    }
    return array_values(array_filter($out));
  }
  // fallback: comma-separated
  return array_values(array_filter(array_map('trim', preg_split('/\s*,\s*/', $raw))));
}

$HAS_UNITS_COURSE_NAME = colExists($conn,'units','course_name');

$message = "";

/* ======================================================================
   AJAX endpoint: return modules for course_id as JSON
   ====================================================================== */
if (($_GET['action'] ?? '') === 'modules') {
  header('Content-Type: application/json; charset=utf-8');
  $course_id = (int)($_GET['course_id'] ?? 0);
  $mods = [];
  if ($course_id > 0 && tableExists($conn,'courses')) {
    $st = $conn->prepare("SELECT modules FROM courses WHERE id=? LIMIT 1");
    $st->bind_param("i",$course_id);
    $st->execute();
    if ($row = $st->get_result()->fetch_assoc()) {
      $mods = parseModulesString($row['modules'] ?? '');
    }
    $st->close();
  }
  echo json_encode(['ok'=>true,'modules'=>$mods]);
  exit;
}

/* ======================================================================
   UNITS: Add / Update / Delete
   ====================================================================== */
if (isset($_POST['add_unit'])) {
  $course_id  = (int)($_POST['unit_course_id'] ?? 0);
  $pick_name  = trim($_POST['unit_pick'] ?? "");     // from modules dropdown
  $manual     = trim($_POST['unit_manual'] ?? "");   // manual override
  $unit_name  = $manual !== "" ? $manual : $pick_name;

  if ($course_id && $unit_name !== "") {
    // verify course + get course_name for denormalized units.course_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(); $chk->close();
    if (!$courseRow) {
      $message = "<div class='alert alert-danger mb-3'>Invalid course selected.</div>";
    } else {
      if ($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']);
      } 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>";
      $st->close();
    }
  } else {
    $message = "<div class='alert alert-warning mb-3'>Please select a course and pick/type a unit.</div>";
  }
}

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'] ?? "");
  if ($id && $course_id && $unit_name !== "") {
    if ($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);
    } 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>";
    $st->close();
  }
}

if (isset($_GET['del_unit'])) {
  $id = (int)$_GET['del_unit'];
  if ($id) {
    $st = $conn->prepare("DELETE FROM units WHERE id=?");
    $st->bind_param("i", $id);
    $message = $st->execute()
      ? "<div class='alert alert-warning mb-3'>Unit deleted.</div>"
      : "<div class='alert alert-danger mb-3'>".$conn->error."</div>";
    $st->close();
  }
}

/* ======================================================================
   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, 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
");
$self = basename($_SERVER['PHP_SELF']);
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Units</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; }
  </style>
</head>
<body class="bg-light">
<div class="container py-4">

  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="m-0">Units</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 ?>

  <!-- UNITS (only) -->
  <div class="card shadow-sm">
    <div class="card-header">Units</div>
    <div class="card-body">

      <!-- Add Unit: Course dropdown + Modules dropdown + Manual textbox -->
      <form method="post" class="row g-2 mb-3">
        <div class="col-md-4">
          <select id="unit_course_id" name="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-md-4">
          <select id="unit_pick" name="unit_pick" class="form-select" disabled>
            <option value="">-- Select Unit (from course modules) --</option>
          </select>
        </div>

        <div class="col-md-3">
          <input type="text" name="unit_manual" id="unit_manual" class="form-control"
                 placeholder="Or type a new unit">
          <div class="form-text">Manual name overrides dropdown.</div>
        </div>

        <div class="col-md-1">
          <button class="btn btn-success w-100" name="add_unit">Add</button>
        </div>
      </form>

      <!-- List Units -->
      <div class="table-responsive">
        <table class="table table-striped align-middle">
          <thead class="table-light">
            <tr>
              <th style="width:40%">Course</th>
              <th style="width:40%">Unit</th>
              <th style="width:20%" class="text-end">Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php if ($units && $units->num_rows): while($u=$units->fetch_assoc()): ?>
            <tr>
              <td>
                <form method="post" class="d-flex form-inline-gap">
                  <select name="unit_course_id" class="form-select">
                    <?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="<?= (int)$u['id'] ?>">
                  <input type="text" name="unit_name" value="<?= h($u['unit_name']) ?>" class="form-control" required>
              </td>
              <td class="text-end">
                  <button class="btn btn-warning btn-sm" name="update_unit">Update</button>
                  <a class="btn btn-danger btn-sm"
                     href="<?= h($self) ?>?del_unit=<?= (int)$u['id'] ?>"
                     onclick="return confirm('Delete unit?');">Delete</a>
                </form>
              </td>
            </tr>
          <?php endwhile; else: ?>
            <tr><td colspan="3">No units yet.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>

    </div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// Load modules when a course is selected
$('#unit_course_id').on('change', function(){
  const id = $(this).val();
  const $pick = $('#unit_pick');
  $pick.prop('disabled', true).html('<option value="">-- Select Unit (from course modules) --</option>');
  if(!id){ return; }
  $.get('?action=modules', { course_id:id }, function(res){
    if(res && res.ok){
      let opts = '<option value="">-- Select Unit (from course modules) --</option>';
      (res.modules || []).forEach(m => {
        const safe = $('<div/>').text(m).html();
        opts += `<option value="${safe}">${safe}</option>`;
      });
      $pick.html(opts).prop('disabled', false);
    }
  }, 'json');
});
</script>
</body>
</html>
