<?php
// /elms/admin/courses/modules.php
declare(strict_types=1);

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

$PAGE_TITLE = 'Course Modules';
$ACTIVE = 'courses';

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

$mysqli = $mysqli ?? ($conn ?? null);
if (!$mysqli instanceof mysqli) {
    http_response_code(500);
    exit('DB connection failed.');
}
$mysqli->set_charset('utf8mb4');

if (!function_exists('esc')) {
    function esc($s): string {
        return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

function tbl_exists(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();
    $ok = (bool)$st->get_result()->fetch_row();
    $st->close();
    return $ok;
}

function col_exists(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();
    $ok = (bool)$st->get_result()->fetch_row();
    $st->close();
    return $ok;
}

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

$mysqli->query("
CREATE TABLE IF NOT EXISTS `elms_module_semesters` (
  `module_id` INT NOT NULL,
  `semester_no` TINYINT NOT NULL DEFAULT 1,
  `position` INT 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
");

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

if (!$moduleTable) {
    http_response_code(500);
    exit('No modules table found.');
}

$titleCol = col_exists($mysqli, $moduleTable, 'title')
    ? 'title'
    : (col_exists($mysqli, $moduleTable, 'name')
        ? 'name'
        : (col_exists($mysqli, $moduleTable, 'module_name') ? 'module_name' : 'id'));

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

$courseName = 'Course #' . $course_id;
$semesterCount = 4;

if (tbl_exists($mysqli, 'courses')) {
    $nameCol = col_exists($mysqli, 'courses', 'course_name')
        ? 'course_name'
        : (col_exists($mysqli, 'courses', 'name')
            ? 'name'
            : (col_exists($mysqli, 'courses', 'title') ? 'title' : 'id'));

    $monthCol = col_exists($mysqli, 'courses', 'months')
        ? 'months'
        : (col_exists($mysqli, 'courses', 'duration') ? 'duration' : null);

    $sql = $monthCol
        ? "SELECT `$nameCol` AS course_name, `$monthCol` AS months_val FROM courses WHERE id=? LIMIT 1"
        : "SELECT `$nameCol` AS course_name, 12 AS months_val FROM courses WHERE id=? LIMIT 1";

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

    if ($row) {
        $courseName = (string)$row['course_name'];
        $months = max(1, (int)($row['months_val'] ?? 12));
        $semesterCount = max(1, min(12, (int)ceil($months / 3)));
    }
}

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

    $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;
}

$modules = [];

$st = $mysqli->prepare("
    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->bind_param('i', $course_id);
$st->execute();
$rs = $st->get_result();
while ($r = $rs->fetch_assoc()) {
    $modules[] = $r;
}
$st->close();

$totalModules = count($modules);
$assignedSemesters = 0;
foreach ($modules as $m) {
    if ((int)$m['semester_no'] > 0) $assignedSemesters++;
}
$unassignedModules = max(0, $totalModules - $assignedSemesters);

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

require_once __DIR__ . '/../../includes/admin_layout_top.php';
?>

<style>
.module-hero{
    background:linear-gradient(135deg,#1e3a8a,#2563eb);
    color:#fff;
    border-radius:20px;
    padding:22px;
    box-shadow:0 16px 40px rgba(37,99,235,.18);
}
.kpi-card{
    border:1px solid #e5e7eb;
    border-radius:18px;
    background:#fff;
    padding:18px;
    box-shadow:0 8px 24px rgba(15,23,42,.06);
}
.module-table-card{
    border:1px solid #e5e7eb;
    border-radius:18px;
    background:#fff;
    overflow:hidden;
    box-shadow:0 10px 30px rgba(15,23,42,.07);
}
.module-title{
    font-weight:800;
}
.form-select{
    border-radius:12px;
}
.action-btns .btn{
    border-radius:999px;
}
</style>

<div class="module-hero mb-4">
    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
        <div>
            <h1 class="h4 mb-1">Semesters & Modules</h1>
            <div class="small opacity-75"><?= esc($courseName) ?> · Course ID <?= (int)$course_id ?></div>
        </div>
        <div class="d-flex gap-2">
            <a href="content.php?course_id=<?= (int)$course_id ?>" class="btn btn-light btn-sm">
                Content
            </a>
            <a href="releases.php?course_id=<?= (int)$course_id ?>" class="btn btn-outline-light btn-sm">
                Releases
            </a>
            <a href="index.php" class="btn btn-outline-light btn-sm">
                ← Back
            </a>
        </div>
    </div>
</div>

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

<div class="row g-3 mb-4">
    <div class="col-md-4">
        <div class="kpi-card">
            <div class="text-muted small">Total Modules</div>
            <div class="h3 mb-0"><?= (int)$totalModules ?></div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="kpi-card">
            <div class="text-muted small">Assigned Semesters</div>
            <div class="h3 mb-0 text-success"><?= (int)$assignedSemesters ?></div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="kpi-card">
            <div class="text-muted small">Unassigned</div>
            <div class="h3 mb-0 text-secondary"><?= (int)$unassignedModules ?></div>
        </div>
    </div>
</div>

<div class="module-table-card">
    <div class="p-3 border-bottom d-flex justify-content-between align-items-center">
        <div>
            <strong>Assign semester numbers</strong>
            <div class="text-muted small">Module source: <?= esc($moduleTable) ?></div>
        </div>
        <span class="badge bg-primary rounded-pill"><?= (int)$semesterCount ?> semester options</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 align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th style="width:42%">Module</th>
                        <th style="width:18%">Semester</th>
                        <th class="text-end" style="width:40%">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$modules): ?>
                    <tr>
                        <td colspan="3" class="text-center text-muted py-5">
                            No modules found for this course.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($modules as $m): ?>
                        <?php $moduleId = (int)$m['id']; ?>
                        <tr>
                            <td>
                                <div class="module-title"><?= esc($m['title']) ?></div>
                                <div class="small text-muted">Module ID: <?= $moduleId ?></div>
                            </td>

                            <td>
                                <select class="form-select form-select-sm" name="sem[<?= $moduleId ?>]">
                                    <?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>

                            <td class="text-end">
                                <div class="d-flex justify-content-end flex-wrap gap-2 action-btns">
                                    <a class="btn btn-sm btn-outline-warning"
                                       href="quiz_builder.php?course_id=<?= (int)$course_id ?>&module_id=<?= $moduleId ?>">
                                        <i class="bi bi-question-circle me-1"></i>
                                        Quiz Builder
                                    </a>
                                    <a class="btn btn-sm btn-outline-info"
   href="game_builder.php?course_id=<?= (int)$course_id ?>&module_id=<?= $moduleId ?>">
    <i class="bi bi-controller me-1"></i>
    Game Builder
</a>

                                    <a class="btn btn-sm btn-outline-success"
                                       href="content.php?course_id=<?= (int)$course_id ?>&module_id=<?= $moduleId ?>">
                                        <i class="bi bi-file-earmark-text me-1"></i>
                                        Content
                                    </a>

                                    <a class="btn btn-sm btn-outline-dark"
                                       href="releases.php?course_id=<?= (int)$course_id ?>#module-<?= $moduleId ?>">
                                        <i class="bi bi-send-check me-1"></i>
                                        Release
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <div class="p-3 border-top bg-white d-flex justify-content-end">
            <button class="btn btn-primary rounded-pill">
                <i class="bi bi-save me-1"></i>
                Save Changes
            </button>
        </div>
    </form>
</div>

<?php require_once __DIR__ . '/../../includes/admin_layout_bottom.php'; ?>