<?php
// /elms/admin/courses/modules.php
// Admin › Courses › Modules / Semester Assignment

declare(strict_types=1);

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

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

require_once __DIR__ . '/../../includes/db.php';

$mysqli = $mysqli ?? ($conn ?? null);

if (!$mysqli instanceof mysqli) {
  http_response_code(500);
  exit('DB connection failed. Check /elms/includes/db.php');
}

$mysqli->set_charset('utf8mb4');

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

function table_exists(mysqli $db, string $table): bool {
  $table = $db->real_escape_string($table);
  $q = $db->query("SHOW TABLES LIKE '{$table}'");
  return $q && $q->num_rows > 0;
}

function col_exists(mysqli $db, string $table, string $col): bool {
  $table = $db->real_escape_string($table);
  $col = $db->real_escape_string($col);
  $q = $db->query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
  return $q && $q->num_rows > 0;
}

function fail_page(string $title, string $msg): void {
  http_response_code(200);
  ?>
  <!doctype html>
  <html lang="en">
  <head>
    <meta charset="utf-8">
    <title><?= h($title) ?></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">
  </head>
  <body class="bg-light">
    <div class="container py-5">
      <div class="alert alert-danger shadow-sm">
        <h4 class="alert-heading"><?= h($title) ?></h4>
        <div><?= h($msg) ?></div>
      </div>
      <a href="index.php" class="btn btn-secondary">Back</a>
    </div>
  </body>
  </html>
  <?php
  exit;
}

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

if ($course_id <= 0) {
  fail_page('Missing course_id', 'Open this page like: modules.php?course_id=2');
}

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

if (!$mysqli->query($createSql)) {
  fail_page('Table Create Error', $mysqli->error);
}

/* find modules table */
$moduleTable = null;

foreach (['course_modules', 'lms_modules'] as $tbl) {
  if (
    table_exists($mysqli, $tbl) &&
    col_exists($mysqli, $tbl, 'id') &&
    col_exists($mysqli, $tbl, 'course_id')
  ) {
    $moduleTable = $tbl;
    break;
  }
}

if (!$moduleTable) {
  fail_page('No modules table found', 'Need course_modules or lms_modules table with id and course_id columns.');
}

$titleCol = col_exists($mysqli, $moduleTable, 'title') ? 'title' : 'id';
$orderCol = col_exists($mysqli, $moduleTable, 'sort_order') ? 'sort_order' : 'id';

/* course info */
$courseName = 'Course #' . $course_id;
$semesterCount = 8;

if (table_exists($mysqli, 'courses')) {
  $nameCol = col_exists($mysqli, 'courses', 'course_name') ? 'course_name' : (col_exists($mysqli, 'courses', 'title') ? 'title' : 'id');
  $monthCol = col_exists($mysqli, 'courses', 'months') ? 'months' : (col_exists($mysqli, 'courses', 'duration') ? 'duration' : null);

  if ($monthCol) {
    $sql = "SELECT `$nameCol` AS course_name, `$monthCol` AS months_val FROM courses WHERE id=? LIMIT 1";
  } else {
    $sql = "SELECT `$nameCol` AS course_name, 8 AS months_val FROM courses WHERE id=? LIMIT 1";
  }

  $st = $mysqli->prepare($sql);
  if ($st) {
    $st->bind_param('i', $course_id);
    $st->execute();
    $row = $st->get_result()->fetch_assoc();
    $st->close();

    if ($row) {
      $courseName = (string)($row['course_name'] ?? $courseName);
      $semesterCount = max(1, min(24, (int)($row['months_val'] ?? 8)));
    }
  }
}

/* save */
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST' && ($_POST['action'] ?? '') === 'save') {
  $semData = $_POST['sem'] ?? [];

  if (!is_array($semData)) {
    $semData = [];
  }

  $allow = [];

  $st = $mysqli->prepare("SELECT id FROM `$moduleTable` WHERE course_id=?");
  $st->bind_param('i', $course_id);
  $st->execute();
  $rs = $st->get_result();

  while ($r = $rs->fetch_assoc()) {
    $allow[(int)$r['id']] = true;
  }

  $st->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)
  ");

  if (!$ins) {
    fail_page('Prepare Error', $mysqli->error);
  }

  $saved = 0;

  foreach ($semData as $moduleId => $semNo) {
    $moduleId = (int)$moduleId;
    $semNo = max(1, min(99, (int)$semNo));

    if (!$moduleId || empty($allow[$moduleId])) {
      continue;
    }

    $ins->bind_param('ii', $moduleId, $semNo);

    if ($ins->execute()) {
      $saved++;
    }
  }

  $ins->close();

  header("Location: modules.php?course_id={$course_id}&saved={$saved}");
  exit;
}

/* fetch modules */
$modules = [];

$sql = "
  SELECT 
    m.id,
    m.`$titleCol` AS title,
    COALESCE(ms.semester_no, 1) AS semester_no
  FROM `$moduleTable` m
  LEFT JOIN elms_module_semesters ms ON ms.module_id = m.id
  WHERE m.course_id = ?
  ORDER BY semester_no ASC, m.`$orderCol` ASC, m.id ASC
";

$st = $mysqli->prepare($sql);

if (!$st) {
  fail_page('Module Query Prepare Error', $mysqli->error);
}

$st->bind_param('i', $course_id);
$st->execute();
$rs = $st->get_result();

while ($r = $rs->fetch_assoc()) {
  $modules[] = $r;
}

$st->close();

$saved = (int)($_GET['saved'] ?? 0);
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Course Modules</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">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

  <style>
    body{
      background:#f6f8fb;
      color:#0f172a;
    }
    .page-wrap{
      max-width:1100px;
      margin:0 auto;
      padding:28px 16px;
    }
    .page-head{
      background:linear-gradient(135deg,#1e3a8a,#2563eb);
      color:#fff;
      border-radius:20px;
      padding:22px;
      margin-bottom:20px;
      box-shadow:0 18px 45px rgba(37,99,235,.22);
    }
    .page-head h1{
      font-size:24px;
      font-weight:900;
      margin:0;
    }
    .card{
      border:0;
      border-radius:18px;
      box-shadow:0 14px 35px rgba(15,23,42,.08);
      overflow:hidden;
    }
    .table th{
      font-size:13px;
      color:#475569;
      text-transform:uppercase;
      letter-spacing:.04em;
    }
    .module-title{
      font-weight:700;
    }
    .form-select{
      max-width:220px;
    }
  </style>
</head>
<body>

<div class="page-wrap">

  <div class="page-head d-flex justify-content-between align-items-center gap-3">
    <div>
      <h1>Semesters & Modules</h1>
      <div class="small opacity-75 mt-1"><?= h($courseName) ?> · Course ID <?= (int)$course_id ?></div>
    </div>

    <a href="index.php" class="btn btn-light btn-sm">
      <i class="bi bi-arrow-left me-1"></i> Back
    </a>
  </div>

  <?php if ($saved > 0): ?>
    <div class="alert alert-success">
      <?= (int)$saved ?> module assignment(s) saved.
    </div>
  <?php endif; ?>

  <div class="card">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
      <strong>Assign semester numbers</strong>
      <span class="badge text-bg-primary"><?= h($moduleTable) ?></span>
    </div>

    <form method="post">
      <input type="hidden" name="action" value="save">
      <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">

      <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
          <thead class="table-light">
            <tr>
              <th style="width:70%">Module</th>
              <th style="width:30%">Semester</th>
            </tr>
          </thead>

          <tbody>
          <?php if (!$modules): ?>
            <tr>
              <td colspan="2" class="text-center text-muted py-5">
                <i class="bi bi-journal-x fs-1 d-block mb-2"></i>
                No modules found for this course.
                <div class="small mt-1">Check course_modules / lms_modules table where course_id = <?= (int)$course_id ?></div>
              </td>
            </tr>
          <?php else: ?>
            <?php foreach ($modules as $m): ?>
              <tr>
                <td>
                  <div class="module-title"><?= h($m['title']) ?></div>
                  <div class="small text-muted">Module ID: <?= (int)$m['id'] ?></div>
                </td>
                <td>
                  <select class="form-select form-select-sm" name="sem[<?= (int)$m['id'] ?>]">
                    <?php for ($i = 1; $i <= $semesterCount; $i++): ?>
                      <option value="<?= $i ?>" <?= ((int)$m['semester_no'] === $i) ? 'selected' : '' ?>>
                        Semester <?= $i ?>
                      </option>
                    <?php endfor; ?>
                    <option value="<?= $semesterCount + 1 ?>" <?= ((int)$m['semester_no'] === ($semesterCount + 1)) ? 'selected' : '' ?>>
                      Semester <?= $semesterCount + 1 ?>+
                    </option>
                  </select>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
          </tbody>
        </table>
      </div>

      <div class="card-footer bg-white d-flex justify-content-end">
        <button class="btn btn-primary">
          <i class="bi bi-save me-1"></i> Save Changes
        </button>
      </div>
    </form>
  </div>

</div>


<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>