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

if (isset($_GET['debug']) && $_GET['debug'] === '1') {
    ini_set('display_errors', '1');
    error_reporting(E_ALL);
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
}

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

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

$auth = __DIR__ . '/../../includes/auth.php';
$hlp  = __DIR__ . '/../../includes/helpers.php';

if (is_file($auth)) require_once $auth;
if (function_exists('require_role')) require_role(['super_admin','admin','branch_admin']);
if (is_file($hlp)) require_once $hlp;

$mysqli = $mysqli ?? ($conn ?? null);
if (!$mysqli instanceof mysqli) die('Database connection not found.');
$mysqli->set_charset('utf8mb4');

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

function table_exists_local(string $table): bool {
    global $mysqli;
    $st = $mysqli->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 column_exists_local(string $table, string $column): bool {
    global $mysqli;
    $st = $mysqli->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
    $st->bind_param('ss', $table, $column);
    $st->execute();
    $ok = (bool)$st->get_result()->fetch_row();
    $st->close();
    return $ok;
}

function clean_filename(string $name): string {
    $name = preg_replace('/[^A-Za-z0-9._-]+/', '_', $name);
    return trim((string)$name, '._');
}

function flash(string $k, ?string $v = null): ?string {
    if ($v === null) {
        $x = $_SESSION['flash'][$k] ?? null;
        unset($_SESSION['flash'][$k]);
        return $x;
    }
    $_SESSION['flash'][$k] = $v;
    return null;
}

function redirect_self(int $course_id, int $module_id, string $extra = ''): void {
    header("Location: content.php?course_id={$course_id}&module_id={$module_id}{$extra}");
    exit;
}

function admin_file_href(?string $p): string {
    if (!$p) return '';
    $p = str_replace('\\', '/', trim($p));
    if ($p === '') return '';
    if (preg_match('#^https?://#i', $p)) return $p;

    $script = $_SERVER['SCRIPT_NAME'] ?? '/elms/admin/courses/content.php';
    $app = preg_match('~^(.*/elms)(?:/|$)~', $script, $m) ? rtrim($m[1], '/') : '/elms';

    if (str_starts_with($p, $app . '/uploads/')) return $p;
    if (str_starts_with($p, '/elms/uploads/')) return $p;
    if (str_starts_with($p, '/uploads/')) return $app . $p;
    if (preg_match('#^(uploads/|content/)#i', $p)) return $app . '/' . ltrim($p, '/');
    if (str_starts_with($p, '/')) return $p;

    return $app . '/uploads/content/' . ltrim($p, '/');
}

function first_module_of_course(int $cid): int {
    global $mysqli;
    foreach (['course_modules', 'lms_modules'] as $t) {
        if (!table_exists_local($t)) continue;
        $order = column_exists_local($t, 'sort_order') ? 'sort_order, id' : 'id';
        $st = $mysqli->prepare("SELECT id FROM `$t` WHERE course_id=? ORDER BY $order LIMIT 1");
        $st->bind_param('i', $cid);
        $st->execute();
        if ($row = $st->get_result()->fetch_assoc()) {
            $st->close();
            return (int)$row['id'];
        }
        $st->close();
    }
    return 0;
}

function derive_course_by_module(int $mid): int {
    global $mysqli;
    foreach (['course_modules', 'lms_modules'] as $t) {
        if (!table_exists_local($t)) continue;
        $st = $mysqli->prepare("SELECT course_id FROM `$t` WHERE id=? LIMIT 1");
        $st->bind_param('i', $mid);
        $st->execute();
        if ($row = $st->get_result()->fetch_assoc()) {
            $st->close();
            return (int)$row['course_id'];
        }
        $st->close();
    }
    return 0;
}

function next_sort_for_module(int $mid): int {
    global $mysqli;
    $st = $mysqli->prepare("SELECT COALESCE(MAX(sort_order),0)+1 AS n FROM lms_content WHERE module_id=?");
    $st->bind_param('i', $mid);
    $st->execute();
    $row = $st->get_result()->fetch_assoc();
    $st->close();
    return (int)($row['n'] ?? 1);
}

function next_session_sort(int $module_id): int {
    global $mysqli;
    $st = $mysqli->prepare("SELECT COALESCE(MAX(sort_order),0)+1 AS n FROM lms_content_sessions WHERE module_id=?");
    $st->bind_param('i', $module_id);
    $st->execute();
    $row = $st->get_result()->fetch_assoc();
    $st->close();
    return (int)($row['n'] ?? 1);
}

function is_local_windows_path(string $url): bool {
    return (bool)preg_match('#^[A-Za-z]:[\\\\/]#', trim($url));
}

$RAW = file_get_contents('php://input');
$JSON = null;
if (isset($_SERVER['CONTENT_TYPE']) && stripos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
    $JSON = json_decode($RAW, true);
    if (!is_array($JSON)) $JSON = null;
}

$course_id = (int)($_GET['course_id'] ?? $_POST['course_id'] ?? ($JSON['course_id'] ?? 0));
$module_id = (int)($_GET['module_id'] ?? $_GET['id'] ?? $_POST['module_id'] ?? ($JSON['module_id'] ?? 0));
$q = trim((string)($_GET['q'] ?? ''));

if ($module_id > 0 && $course_id <= 0) $course_id = derive_course_by_module($module_id);

if ($course_id > 0 && $module_id <= 0) {
    $first = first_module_of_course($course_id);
    if ($first > 0) redirect_self($course_id, $first);
    header("Location: modules.php?course_id={$course_id}&msg=" . urlencode('Create a module to add content.'));
    exit;
}

if ($course_id <= 0 && $module_id <= 0) {
    foreach (['course_modules', 'lms_modules'] as $t) {
        if (!table_exists_local($t)) continue;
        $order = column_exists_local($t, 'sort_order') ? 'sort_order, id' : 'id';
        $rs = $mysqli->query("SELECT id AS mid, course_id AS cid FROM `$t` ORDER BY $order LIMIT 1");
        if ($pair = $rs->fetch_assoc()) redirect_self((int)$pair['cid'], (int)$pair['mid']);
    }
    header("Location: modules.php?msg=" . urlencode('No modules found. Create one first.'));
    exit;
}

$MOD_TBL = null;
foreach (['course_modules', 'lms_modules'] as $tryTbl) {
    if (!table_exists_local($tryTbl)) continue;
    if (!column_exists_local($tryTbl, 'id') || !column_exists_local($tryTbl, 'course_id')) continue;

    $chk = $mysqli->prepare("SELECT id FROM `$tryTbl` WHERE id=? AND course_id=? LIMIT 1");
    $chk->bind_param('ii', $module_id, $course_id);
    $chk->execute();
    $found = $chk->get_result()->fetch_assoc();
    $chk->close();

    if ($found) {
        $MOD_TBL = $tryTbl;
        break;
    }
}

if ($MOD_TBL === null) {
    http_response_code(404);
    exit('No modules table found for this course');
}

$TITLE_COL = column_exists_local($MOD_TBL, 'title') ? 'title' : (column_exists_local($MOD_TBL, 'name') ? 'name' : 'id');
$ORDER_COL = column_exists_local($MOD_TBL, 'sort_order') ? 'sort_order' : 'id';
$HAS_GAMEMODE = ($MOD_TBL === 'lms_modules' && column_exists_local('lms_modules', 'game_mode'));

$labelCol = column_exists_local('courses', 'course_name') ? 'course_name'
    : (column_exists_local('courses', 'name') ? 'name'
    : (column_exists_local('courses', 'title') ? 'title' : 'id'));

$st = $mysqli->prepare("SELECT id, `$labelCol` AS label FROM courses WHERE id=? LIMIT 1");
$st->bind_param('i', $course_id);
$st->execute();
$COURSE = $st->get_result()->fetch_assoc();
$st->close();

if (!$COURSE) {
    http_response_code(404);
    exit('Course not found');
}

$sql = "SELECT id, `$TITLE_COL` AS title" . ($HAS_GAMEMODE ? ", game_mode" : ", 0 AS game_mode") . "
        FROM `$MOD_TBL`
        WHERE id=? AND course_id=?
        LIMIT 1";

$st = $mysqli->prepare($sql);
$st->bind_param('ii', $module_id, $course_id);
$st->execute();
$MODULE = $st->get_result()->fetch_assoc();
$st->close();

if (!$MODULE) {
    http_response_code(404);
    exit('Module not found for this course');
}

/* Core tables / columns */
if (!table_exists_local('lms_content')) {
    $mysqli->query("
        CREATE TABLE IF NOT EXISTS `lms_content` (
            `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
            `module_id` INT UNSIGNED NOT NULL,
            `session_id` INT UNSIGNED NULL,
            `title` VARCHAR(255) NOT NULL,
            `content_type` ENUM('link','pdf','video','text','quiz','game') NOT NULL DEFAULT 'link',
            `description` TEXT NULL,
            `available_from` DATETIME NULL,
            `available_to` DATETIME NULL,
            `file_path` VARCHAR(255) NULL,
            `url` VARCHAR(500) NULL,
            `duration_seconds` INT NULL,
            `sort_order` INT NOT NULL DEFAULT 0,
            `active` TINYINT(1) NOT NULL DEFAULT 1,
            `require_paid` TINYINT(1) NOT NULL DEFAULT 0,
            `created_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            `updated_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            KEY `idx_module_order` (`module_id`,`sort_order`),
            KEY `idx_session_order` (`session_id`,`sort_order`),
            KEY `idx_active` (`active`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
} else {
    if (!column_exists_local('lms_content', 'session_id')) {
        $mysqli->query("ALTER TABLE lms_content ADD COLUMN session_id INT UNSIGNED NULL AFTER module_id");
    }
}

if (!table_exists_local('lms_content_sessions')) {
    $mysqli->query("
        CREATE TABLE IF NOT EXISTS lms_content_sessions (
            id INT UNSIGNED NOT NULL AUTO_INCREMENT,
            course_id INT UNSIGNED NOT NULL,
            module_id INT UNSIGNED NOT NULL,
            title VARCHAR(255) NOT NULL,
            description TEXT NULL,
            sort_order INT NOT NULL DEFAULT 0,
            active TINYINT(1) NOT NULL DEFAULT 1,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_module_order (module_id, sort_order),
            KEY idx_course_module (course_id, module_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
}

$ELMS_ROOT = dirname(__DIR__, 2);
$UPLOAD_DIR = $ELMS_ROOT . '/uploads/content';

$script = $_SERVER['SCRIPT_NAME'] ?? '';
$APP_ROOT = preg_match('~^(.*/elms)(?:/|$)~', $script, $m) ? rtrim($m[1], '/') : '/elms';
$PUBLIC_PREFIX = $APP_ROOT . '/uploads/content';

$ALLOWED_EXT = ['pdf','mp4','webm','mov','m4v','ogg','ogv','zip','ppt','pptx','doc','docx','xls','xlsx','png','jpg','jpeg','gif','txt','csv'];
$VIDEO_EXT   = ['mp4','webm','mov','m4v','ogg','ogv'];
$MAX_MB      = 500;

$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();
$rs = $st->get_result();
while ($row = $rs->fetch_assoc()) $MODS[] = $row;
$st->close();

$action = $_POST['action'] ?? ($JSON['action'] ?? '');

/* Add Session */
if ($action === 'add_session') {
    $sessionTitle = trim((string)($_POST['session_title'] ?? ''));
    $sessionDesc  = trim((string)($_POST['session_description'] ?? ''));

    if ($sessionTitle === '') {
        flash('err', 'Session title is required.');
        redirect_self($course_id, $module_id);
    }

    $sort = next_session_sort($module_id);

    $st = $mysqli->prepare("
        INSERT INTO lms_content_sessions (course_id, module_id, title, description, sort_order, active)
        VALUES (?, ?, ?, ?, ?, 1)
    ");
    $st->bind_param('iissi', $course_id, $module_id, $sessionTitle, $sessionDesc, $sort);
    $st->execute();
    $st->close();

    flash('ok', 'Session added.');
    redirect_self($course_id, $module_id);
}

/* Delete Session */
if ($action === 'delete_session') {
    $sid = (int)($_POST['session_id'] ?? 0);

    if ($sid > 0) {
        $st = $mysqli->prepare("UPDATE lms_content SET session_id=NULL WHERE session_id=? AND module_id=?");
        $st->bind_param('ii', $sid, $module_id);
        $st->execute();
        $st->close();

        $st = $mysqli->prepare("DELETE FROM lms_content_sessions WHERE id=? AND module_id=?");
        $st->bind_param('ii', $sid, $module_id);
        $st->execute();
        $st->close();

        flash('ok', 'Session deleted. Content moved to Unassigned.');
    }

    redirect_self($course_id, $module_id);
}

/* Reorder Content */
if ($action === 'reorder_content') {
    header('Content-Type: application/json; charset=utf-8');

    $ids = $_POST['ids'] ?? ($JSON['ids'] ?? []);
    if (is_string($ids)) $ids = preg_split('/[,\s]+/', trim($ids), -1, PREG_SPLIT_NO_EMPTY);
    if (!is_array($ids)) $ids = [];
    $ids = array_values(array_unique(array_map('intval', $ids)));

    $allowed = [];
    $qst = $mysqli->prepare("SELECT id FROM lms_content WHERE module_id=?");
    $qst->bind_param('i', $module_id);
    $qst->execute();
    $res = $qst->get_result();
    while ($row = $res->fetch_assoc()) $allowed[] = (int)$row['id'];
    $qst->close();

    $set = array_flip($allowed);
    $ordered = [];

    foreach ($ids as $id) {
        if (isset($set[$id])) $ordered[] = $id;
    }
    foreach ($allowed as $id) {
        if (!in_array($id, $ordered, true)) $ordered[] = $id;
    }

    $mysqli->begin_transaction();
    try {
        $ord = 1;
        $u = $mysqli->prepare("UPDATE lms_content SET sort_order=? WHERE id=? AND module_id=?");
        foreach ($ordered as $id) {
            $u->bind_param('iii', $ord, $id, $module_id);
            $u->execute();
            $ord++;
        }
        $u->close();
        $mysqli->commit();
        echo json_encode(['ok' => true]);
    } catch (Throwable $e) {
        $mysqli->rollback();
        echo json_encode(['ok' => false, 'error' => 'DB error']);
    }
    exit;
}

/* Toggle */
if ($action === 'toggle' && isset($_POST['field'], $_POST['id'])) {
    header('Content-Type: application/json; charset=utf-8');

    $id = (int)$_POST['id'];
    $field = (string)$_POST['field'];

    if (!in_array($field, ['active', 'require_paid'], true)) {
        echo json_encode(['ok' => false]);
        exit;
    }

    $st = $mysqli->prepare("UPDATE lms_content SET `$field` = 1 - `$field` WHERE id=? AND module_id=?");
    $st->bind_param('ii', $id, $module_id);
    $ok = $st->execute();
    $st->close();

    echo json_encode(['ok' => $ok]);
    exit;
}

/* Add / Update / Delete Content */
if ($action && !in_array($action, ['reorder_content', 'toggle', 'add_session', 'delete_session'], true)) {
    if ($action === 'add' || $action === 'update') {
        $id = (int)($_POST['id'] ?? 0);
        $session_id = (int)($_POST['session_id'] ?? 0);
        $title = trim((string)($_POST['title'] ?? ''));
        $type = strtolower(trim((string)($_POST['content_type'] ?? 'link')));
        $desc = trim((string)($_POST['description'] ?? ''));
        $url = trim((string)($_POST['url'] ?? ''));
        $active = isset($_POST['active']) ? 1 : 0;
        $paid = isset($_POST['require_paid']) ? 1 : 0;

        $allowedTypes = ['video','pdf','link','text'];
        if (!in_array($type, $allowedTypes, true)) $type = 'link';

        if ($session_id > 0) {
            $chk = $mysqli->prepare("SELECT id FROM lms_content_sessions WHERE id=? AND module_id=? LIMIT 1");
            $chk->bind_param('ii', $session_id, $module_id);
            $chk->execute();
            $okSession = $chk->get_result()->fetch_assoc();
            $chk->close();

            if (!$okSession) $session_id = 0;
        }

        if (is_local_windows_path($url)) $url = '';
        if ($type === 'video') $url = '';

        $file_path = null;
        
        $uploadErr = $_FILES['file']['error'] ?? UPLOAD_ERR_NO_FILE;

if ($uploadErr !== UPLOAD_ERR_OK && $uploadErr !== UPLOAD_ERR_NO_FILE) {
    $errMap = [
        UPLOAD_ERR_INI_SIZE   => 'Uploaded file exceeds server upload_max_filesize.',
        UPLOAD_ERR_FORM_SIZE  => 'Uploaded file exceeds form MAX_FILE_SIZE.',
        UPLOAD_ERR_PARTIAL    => 'File uploaded partially. Try again.',
        UPLOAD_ERR_NO_TMP_DIR => 'Server temp folder missing.',
        UPLOAD_ERR_CANT_WRITE => 'Server cannot write uploaded file.',
        UPLOAD_ERR_EXTENSION  => 'PHP extension blocked upload.',
    ];

    flash('err', $errMap[$uploadErr] ?? ('Upload error code: ' . $uploadErr));
    redirect_self($course_id, $module_id, $id ? '&edit=' . $id : '');
}

        if (
    isset($_FILES['file']) &&
    ($_FILES['file']['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_OK &&
    is_uploaded_file($_FILES['file']['tmp_name'])
) {
            $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));

            if (!in_array($ext, $ALLOWED_EXT, true)) {
                flash('err', 'File type not allowed.');
                redirect_self($course_id, $module_id, $id ? '&edit=' . $id : '');
            }

            if ($type === 'video' && !in_array($ext, $VIDEO_EXT, true)) {
                flash('err', 'Video must be MP4, WEBM, MOV, M4V, OGG or OGV.');
                redirect_self($course_id, $module_id, $id ? '&edit=' . $id : '');
            }

            if ($_FILES['file']['size'] > ($MAX_MB * 1024 * 1024)) {
                flash('err', "File too large. Max {$MAX_MB}MB. Also check PHP upload_max_filesize/post_max_size.");
                redirect_self($course_id, $module_id, $id ? '&edit=' . $id : '');
            }

            if (!is_dir($UPLOAD_DIR)) @mkdir($UPLOAD_DIR, 0775, true);

            $fname = date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
            $dest = rtrim($UPLOAD_DIR, '/\\') . DIRECTORY_SEPARATOR . clean_filename($fname);

            if (!move_uploaded_file($_FILES['file']['tmp_name'], $dest)) {
                flash('err', 'Upload failed. Check uploads/content folder permission and PHP file upload limits.');
                redirect_self($course_id, $module_id, $id ? '&edit=' . $id : '');
            }

            $file_path = rtrim($PUBLIC_PREFIX, '/') . '/' . basename($dest);
        }

        if ($title === '') {
            flash('err', 'Title is required.');
            redirect_self($course_id, $module_id, $id ? '&edit=' . $id : '');
        }

        if ($type === 'video' && $action === 'add' && !$file_path) {
    flash('err', 'Please choose MP4/WEBM/MOV/M4V/OGG/OGV file. If you already selected a file, check PHP upload_max_filesize and post_max_size.');
    redirect_self($course_id, $module_id);
}

        $af = null;
        $at = null;
        $dur = null;
        $sidDb = $session_id > 0 ? $session_id : null;

        if ($action === 'add') {
            $sort = next_sort_for_module($module_id);

            $st = $mysqli->prepare("
                INSERT INTO lms_content
                (module_id, session_id, title, content_type, description, available_from, available_to, file_path, url, duration_seconds, sort_order, active, require_paid)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $fp = $file_path;
            $st->bind_param('iisssssssiiii', $module_id, $sidDb, $title, $type, $desc, $af, $at, $fp, $url, $dur, $sort, $active, $paid);
            $st->execute();
            $st->close();

            flash('ok', 'Content added.');
        } else {
            if ($id <= 0) {
                flash('err', 'Invalid content ID.');
                redirect_self($course_id, $module_id);
            }

            if ($file_path !== null) {
                $st = $mysqli->prepare("
                    UPDATE lms_content
                    SET session_id=?, title=?, content_type=?, description=?, available_from=?, available_to=?, file_path=?, url=?, duration_seconds=?, active=?, require_paid=?
                    WHERE id=? AND module_id=?
                ");
                $st->bind_param('issssssssiiii', $sidDb, $title, $type, $desc, $af, $at, $file_path, $url, $dur, $active, $paid, $id, $module_id);
            } else {
                $st = $mysqli->prepare("
                    UPDATE lms_content
                    SET session_id=?, title=?, content_type=?, description=?, available_from=?, available_to=?, url=?, duration_seconds=?, active=?, require_paid=?
                    WHERE id=? AND module_id=?
                ");
                $st->bind_param('issssssiiiii', $sidDb, $title, $type, $desc, $af, $at, $url, $dur, $active, $paid, $id, $module_id);
            }

            $st->execute();
            $st->close();

            flash('ok', 'Content updated.');
        }

        redirect_self($course_id, $module_id);
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            $st = $mysqli->prepare("DELETE FROM lms_content WHERE id=? AND module_id=?");
            $st->bind_param('ii', $id, $module_id);
            $st->execute();
            $st->close();
            flash('ok', 'Content deleted.');
        }
        redirect_self($course_id, $module_id);
    }
}

/* Fetch Sessions */
$sessions = [];
$st = $mysqli->prepare("
    SELECT id, title, description, sort_order, active
    FROM lms_content_sessions
    WHERE course_id=? AND module_id=?
    ORDER BY sort_order, id
");
$st->bind_param('ii', $course_id, $module_id);
$st->execute();
$rs = $st->get_result();
while ($row = $rs->fetch_assoc()) {
    $sessions[(int)$row['id']] = $row;
}
$st->close();

/* Fetch Content */
$items = [];

$sql = "
    SELECT id, module_id, session_id, title, content_type, description, file_path, url, sort_order, active, require_paid
    FROM lms_content
    WHERE module_id=?
";

if ($q !== '') $sql .= " AND (title LIKE CONCAT('%',?,'%') OR description LIKE CONCAT('%',?,'%'))";
$sql .= " ORDER BY COALESCE(session_id, 0), sort_order, id";

if ($q !== '') {
    $st = $mysqli->prepare($sql);
    $st->bind_param('iss', $module_id, $q, $q);
} else {
    $st = $mysqli->prepare($sql);
    $st->bind_param('i', $module_id);
}

$st->execute();
$rs = $st->get_result();
while ($row = $rs->fetch_assoc()) $items[] = $row;
$st->close();

$grouped = [];
foreach ($sessions as $sid => $s) {
    $grouped[$sid] = [];
}
$grouped[0] = [];

foreach ($items as $it) {
    $sid = (int)($it['session_id'] ?? 0);
    if ($sid > 0 && isset($sessions[$sid])) $grouped[$sid][] = $it;
    else $grouped[0][] = $it;
}

$edit_id = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$editing = null;
foreach ($items as $it) {
    if ((int)$it['id'] === $edit_id) {
        $editing = $it;
        break;
    }
}

$typeCounts = ['video'=>0,'pdf'=>0,'link'=>0,'text'=>0,'quiz'=>0,'game'=>0];
$activeCount = 0;
foreach ($items as $it) {
    $t = strtolower((string)$it['content_type']);
    if (isset($typeCounts[$t])) $typeCounts[$t]++;
    if (!empty($it['active'])) $activeCount++;
}

$PAGE_TITLE = 'Content';
$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>
.ec-content-wrap{max-width:100%;margin:0 auto}
.ec-hero{background:linear-gradient(135deg,#0f172a,#1d4ed8);border-radius:20px;padding:20px 22px;color:#fff;box-shadow:0 16px 40px rgba(29,78,216,.18)}
.ec-hero h1{font-size:22px;font-weight:800;margin:0}
.ec-hero .sub{opacity:.82;font-size:13px;margin-top:4px}
.ec-toolbar{background:#fff;border:1px solid #e5e7eb;border-radius:18px;padding:14px;box-shadow:0 8px 24px rgba(15,23,42,.05)}
.ec-stat{background:#fff;border:1px solid #e5e7eb;border-radius:16px;padding:14px;box-shadow:0 8px 22px rgba(15,23,42,.05)}
.ec-stat .label{font-size:12px;color:#64748b;font-weight:700;text-transform:uppercase}
.ec-stat .value{font-size:24px;font-weight:900;color:#0f172a;line-height:1}
.ec-card{border:1px solid #e5e7eb;border-radius:18px;background:#fff;box-shadow:0 10px 28px rgba(15,23,42,.06);overflow:hidden}
.ec-card-head{padding:15px 18px;background:#f8fafc;border-bottom:1px solid #e5e7eb;display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}
.ec-card-head strong{font-size:15px;color:#0f172a}
.ec-table{margin:0}
.ec-table thead th{background:#f8fafc;color:#475569;font-size:11px;text-transform:uppercase;letter-spacing:.04em;border-bottom:1px solid #e5e7eb;padding:12px}
.ec-table tbody td{padding:13px 12px;vertical-align:middle;border-color:#eef2f7}
.content-row{cursor:grab;user-select:none}
.content-row.dragging{opacity:.55}
.drag-handle{width:30px;text-align:center;color:#94a3b8;font-size:18px}
.type-badge{display:inline-flex;align-items:center;gap:6px;border-radius:999px;padding:5px 9px;font-size:12px;font-weight:800}
.type-pdf{background:#fee2e2;color:#991b1b}
.type-video{background:#dbeafe;color:#1d4ed8}
.type-link{background:#f1f5f9;color:#334155}
.type-text{background:#ede9fe;color:#5b21b6}
.type-quiz{background:#dcfce7;color:#166534}
.type-game{background:#cffafe;color:#155e75}
.source-link{font-weight:700;text-decoration:none}
.source-meta{font-size:12px;color:#64748b;margin-top:2px;max-width:360px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.badge-soft{background:#eef2ff;color:#3b5bdb}
.empty-state{padding:38px;text-align:center;color:#64748b}
.form-hint{font-size:12px;color:#64748b}
.btn-icon{display:inline-flex;align-items:center;gap:6px}
.session-title-row{background:#f8fafc}
.session-title-row td{padding:14px 16px!important}
.session-pill{background:#0f172a;color:#fff;border-radius:999px;padding:6px 12px;font-size:12px;font-weight:900}
.session-desc{font-size:12px;color:#64748b;margin-top:4px}
</style>

<div class="ec-content-wrap">

    <div class="ec-hero mb-3 d-flex justify-content-between align-items-center flex-wrap gap-3">
        <div>
            <h1>Content Manager</h1>
            <div class="sub"><?= esc($COURSE['label']) ?> · <?= esc($MODULE['title']) ?></div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <a class="btn btn-light btn-sm btn-icon" href="quiz_builder.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>">+ Create Quiz</a>
            <a class="btn btn-info btn-sm btn-icon" href="game_builder.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>">Game Builder</a>
            <a href="modules.php?course_id=<?= (int)$course_id ?>" class="btn btn-outline-light btn-sm">← Back to Modules</a>
        </div>
    </div>

    <div class="ec-toolbar mb-3">
        <form method="get" class="row g-2 align-items-end">
            <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">
            <div class="col-md-5">
                <label class="form-label small fw-bold text-muted mb-1">Module</label>
                <select name="module_id" class="form-select" onchange="this.form.submit()">
                    <?php foreach ($MODS as $m): ?>
                        <option value="<?= (int)$m['id'] ?>" <?= (int)$m['id'] === $module_id ? 'selected' : '' ?>>
                            <?= esc($m['title']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-5">
                <label class="form-label small fw-bold text-muted mb-1">Search content</label>
                <input type="text" class="form-control" name="q" placeholder="Search title or description..." value="<?= esc($q) ?>">
            </div>
            <div class="col-md-2 d-grid">
                <button class="btn btn-primary">Search</button>
            </div>
        </form>
    </div>

    <?php if ($msg = flash('ok')): ?>
        <div class="alert alert-success py-2"><?= esc($msg) ?></div>
    <?php endif; ?>

    <?php if ($msg = flash('err')): ?>
        <div class="alert alert-danger py-2"><?= esc($msg) ?></div>
    <?php endif; ?>

    <div class="row g-3 mb-3">
        <div class="col-md-3 col-6"><div class="ec-stat"><div class="label">Sessions</div><div class="value"><?= count($sessions) ?></div></div></div>
        <div class="col-md-3 col-6"><div class="ec-stat"><div class="label">Total Content</div><div class="value"><?= count($items) ?></div></div></div>
        <div class="col-md-3 col-6"><div class="ec-stat"><div class="label">Active</div><div class="value"><?= (int)$activeCount ?></div></div></div>
        <div class="col-md-3 col-6"><div class="ec-stat"><div class="label">Files / Videos</div><div class="value"><?= (int)($typeCounts['pdf'] + $typeCounts['video']) ?></div></div></div>
    </div>

    <div class="ec-card mb-3">
        <div class="ec-card-head">
            <strong>Add Session</strong>
        </div>
        <div class="p-3">
            <form method="post" class="row g-2 align-items-end">
                <input type="hidden" name="action" value="add_session">
                <div class="col-md-5">
                    <label class="form-label fw-semibold">Session Title</label>
                    <input type="text" name="session_title" class="form-control" placeholder="Session 1 - Understanding the Basics of ICT" required>
                </div>
                <div class="col-md-5">
                    <label class="form-label fw-semibold">Description</label>
                    <input type="text" name="session_description" class="form-control" placeholder="Optional short description">
                </div>
                <div class="col-md-2 d-grid">
                    <button class="btn btn-dark">Add Session</button>
                </div>
            </form>
        </div>
    </div>

    <div class="ec-card mb-3">
    <div class="ec-card-head">
        <div data-bs-toggle="collapse"
             data-bs-target="#moduleContentCollapse"
             style="cursor:pointer;">
            <strong>Module Content by Sessions</strong>

            <div class="small text-muted">
                <?= esc($MODULE['title']) ?>
                <?php if (!empty($MODULE['game_mode']) && $HAS_GAMEMODE): ?>
                    <span class="badge badge-soft ms-2">Game Mode ON</span>
                <?php endif; ?>
            </div>
        </div>

        <div class="d-flex gap-2 align-items-center">
            <button id="btn-save-order"
                    class="btn btn-sm btn-primary d-none"
                    type="button">
                Save Order
            </button>

            <button type="button"
                    class="btn btn-sm btn-outline-secondary"
                    data-bs-toggle="collapse"
                    data-bs-target="#moduleContentCollapse">
                Open / Close
            </button>
        </div>
    </div>

    <div id="moduleContentCollapse" class="collapse show">
        <div class="card-body p-0">
            
            <?php if (!$items && !$sessions): ?>
                <div class="empty-state">
                    <h6 class="mb-1">No sessions or content yet</h6>
                    <div>Add a session first, then add PDF, video, link or text content.</div>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table ec-table align-middle">
                        <thead>
                            <tr>
                                <th style="width:42px;"></th>
                                <th>Title</th>
                                <th style="width:110px;">Type</th>
                                <th>Source</th>
                                <th style="width:90px;">Active</th>
                                <th style="width:90px;">Paid?</th>
                                <th style="width:190px;" class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="content-list">
                            <?php foreach ($sessions as $sid => $sess): ?>
                                <tr class="session-title-row">
                                    <td colspan="7">
                                        <div class="d-flex justify-content-between align-items-start gap-3">
                                            <div>
                                                <span class="session-pill"><?= esc($sess['title']) ?></span>
                                                <?php if (!empty($sess['description'])): ?>
                                                    <div class="session-desc"><?= esc($sess['description']) ?></div>
                                                <?php endif; ?>
                                            </div>
                                            <form method="post" onsubmit="return confirm('Delete this session? Content will move to Unassigned.');">
                                                <input type="hidden" name="action" value="delete_session">
                                                <input type="hidden" name="session_id" value="<?= (int)$sid ?>">
                                                <button class="btn btn-sm btn-outline-danger">Delete Session</button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>

                                <?php if (empty($grouped[$sid])): ?>
                                    <tr>
                                        <td colspan="7" class="text-muted small ps-4">No content in this session.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($grouped[$sid] as $it): ?>
                                        <?php
$cid = (int)$it['id'];
$type = strtolower((string)$it['content_type']);
$fileUrl = admin_file_href($it['file_path'] ?? '');
$urlVal = trim((string)($it['url'] ?? ''));
$typeClass = 'type-' . preg_replace('/[^a-z0-9_-]/', '', $type);
?>
<tr class="content-row" draggable="true" data-id="<?= $cid ?>">
    <td class="drag-handle">☰</td>

    <td>
        <div class="fw-bold text-dark"><?= esc($it['title']) ?></div>
        <?php if (!empty($it['description'])): ?>
            <div class="small text-muted">
                <?= esc(mb_strimwidth((string)$it['description'], 0, 90, '...')) ?>
            </div>
        <?php endif; ?>
    </td>

    <td>
        <span class="type-badge <?= esc($typeClass) ?>">
            <?= esc(strtoupper($type)) ?>
        </span>
    </td>

    <td>
        <?php if ($type === 'video' && $fileUrl): ?>
            <a class="source-link" href="<?= esc($fileUrl) ?>" target="_blank" rel="noopener">Open video</a>
            <div class="source-meta"><?= esc(basename(parse_url($fileUrl, PHP_URL_PATH) ?: $fileUrl)) ?></div>

        <?php elseif ($fileUrl): ?>
            <a class="source-link" href="<?= esc($fileUrl) ?>" target="_blank" rel="noopener">Open file</a>
            <div class="source-meta"><?= esc(basename(parse_url($fileUrl, PHP_URL_PATH) ?: $fileUrl)) ?></div>

        <?php elseif ($urlVal): ?>
            <a class="source-link" href="<?= esc($urlVal) ?>" target="_blank" rel="noopener">Open URL</a>
            <div class="source-meta"><?= esc($urlVal) ?></div>

        <?php else: ?>
            <span class="text-muted">—</span>
        <?php endif; ?>
    </td>

    <td>
        <button class="btn btn-sm <?= !empty($it['active']) ? 'btn-success' : 'btn-outline-secondary' ?> toggle"
                data-id="<?= $cid ?>" data-field="active">
            <?= !empty($it['active']) ? 'On' : 'Off' ?>
        </button>
    </td>

    <td>
        <button class="btn btn-sm <?= !empty($it['require_paid']) ? 'btn-warning' : 'btn-outline-secondary' ?> toggle"
                data-id="<?= $cid ?>" data-field="require_paid">
            <?= !empty($it['require_paid']) ? 'Yes' : 'No' ?>
        </button>
    </td>

    <td class="text-end">
        <?php if ($type === 'quiz'): ?>
            <a class="btn btn-sm btn-outline-primary"
               href="quiz_builder.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>&content_id=<?= $cid ?>">
                Edit Quiz
            </a>

        <?php elseif ($type === 'game'): ?>
            <a class="btn btn-sm btn-outline-primary"
               href="game_builder.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>&content_id=<?= $cid ?>">
                Edit Game
            </a>

        <?php else: ?>
            <button type="button"
        class="btn btn-sm btn-outline-primary btnEditContent"
        data-id="<?= $cid ?>"
        data-session="<?= (int)($it['session_id'] ?? 0) ?>"
        data-title="<?= esc($it['title']) ?>"
        data-type="<?= esc($type) ?>"
        data-description="<?= esc($it['description'] ?? '') ?>"
        data-url="<?= esc($it['url'] ?? '') ?>"
        data-active="<?= !empty($it['active']) ? 1 : 0 ?>"
        data-paid="<?= !empty($it['require_paid']) ? 1 : 0 ?>">
    Edit
</button>
        <?php endif; ?>

        <form method="post" class="d-inline" onsubmit="return confirm('Delete this item?');">
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" value="<?= $cid ?>">
            <button class="btn btn-sm btn-outline-danger">Delete</button>
        </form>
    </td>
</tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            <?php endforeach; ?>

                            <?php if (!empty($grouped[0])): ?>
                                <tr class="session-title-row">
                                    <td colspan="7">
                                        <span class="session-pill">Unassigned Content</span>
                                        <div class="session-desc">These items are not assigned to a session yet.</div>
                                    </td>
                                </tr>

                                <?php foreach ($grouped[0] as $it): ?>
    <?php
    $cid = (int)$it['id'];
    $type = strtolower((string)$it['content_type']);
    $fileUrl = admin_file_href($it['file_path'] ?? '');
    $urlVal = trim((string)($it['url'] ?? ''));
    $typeClass = 'type-' . preg_replace('/[^a-z0-9_-]/', '', $type);
    ?>
    <tr class="content-row" draggable="true" data-id="<?= $cid ?>">
        <td class="drag-handle">☰</td>
        <td>
            <div class="fw-bold text-dark"><?= esc($it['title']) ?></div>
            <?php if (!empty($it['description'])): ?>
                <div class="small text-muted">
                    <?= esc(mb_strimwidth((string)$it['description'], 0, 90, '...')) ?>
                </div>
            <?php endif; ?>
        </td>
        <td>
            <span class="type-badge <?= esc($typeClass) ?>">
                <?= esc(strtoupper($type)) ?>
            </span>
        </td>
        <td>
            <?php if ($fileUrl): ?>
                <a class="source-link" href="<?= esc($fileUrl) ?>" target="_blank" rel="noopener">
                    <?= $type === 'video' ? 'Open video' : 'Open file' ?>
                </a>
                <div class="source-meta"><?= esc(basename(parse_url($fileUrl, PHP_URL_PATH) ?: $fileUrl)) ?></div>
            <?php elseif ($urlVal): ?>
                <a class="source-link" href="<?= esc($urlVal) ?>" target="_blank" rel="noopener">Open URL</a>
                <div class="source-meta"><?= esc($urlVal) ?></div>
            <?php else: ?>
                <span class="text-muted">—</span>
            <?php endif; ?>
        </td>
        <td>
            <button class="btn btn-sm <?= !empty($it['active']) ? 'btn-success' : 'btn-outline-secondary' ?> toggle"
                    data-id="<?= $cid ?>" data-field="active">
                <?= !empty($it['active']) ? 'On' : 'Off' ?>
            </button>
        </td>
        <td>
            <button class="btn btn-sm <?= !empty($it['require_paid']) ? 'btn-warning' : 'btn-outline-secondary' ?> toggle"
                    data-id="<?= $cid ?>" data-field="require_paid">
                <?= !empty($it['require_paid']) ? 'Yes' : 'No' ?>
            </button>
        </td>
        <td class="text-end">
            <?php if ($type === 'quiz'): ?>
                <a class="btn btn-sm btn-outline-primary"
                   href="quiz_builder.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>&content_id=<?= $cid ?>">
                    Edit Quiz
                </a>
            <?php elseif ($type === 'game'): ?>
                <a class="btn btn-sm btn-outline-primary"
                   href="game_builder.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>&content_id=<?= $cid ?>">
                    Edit Game
                </a>
            <?php else: ?>
    <button type="button"
            class="btn btn-sm btn-outline-primary btnEditContent"
            data-id="<?= $cid ?>"
            data-session="<?= (int)($it['session_id'] ?? 0) ?>"
            data-title="<?= esc($it['title']) ?>"
            data-type="<?= esc($type) ?>"
            data-description="<?= esc($it['description'] ?? '') ?>"
            data-url="<?= esc($it['url'] ?? '') ?>"
            data-active="<?= !empty($it['active']) ? 1 : 0 ?>"
            data-paid="<?= !empty($it['require_paid']) ? 1 : 0 ?>">
        Edit
    </button>
<?php endif; ?>

            <form method="post" class="d-inline" onsubmit="return confirm('Delete this item?');">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= $cid ?>">
                <button class="btn btn-sm btn-outline-danger">Delete</button>
            </form>
        </td>
    </tr>
<?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
    </div>

    <div class="ec-card mb-4">
    <div class="ec-card-head" data-bs-toggle="collapse" data-bs-target="#addContentCollapse" style="cursor:pointer;">
        <strong>Add New Content</strong>
        <span class="btn btn-sm btn-outline-secondary">Open / Close</span>
    </div>

    <div id="addContentCollapse" class="collapse">
        <div class="p-3">
            
        <form method="post" enctype="multipart/form-data" class="row g-3">
            <input type="hidden" name="action" value="add">

            <div class="col-md-4">
                <label class="form-label fw-semibold">Session</label>
                <select name="session_id" class="form-select">
                    <option value="0">Unassigned</option>
                    <?php foreach ($sessions as $sid => $sess): ?>
                        <option value="<?= (int)$sid ?>"><?= esc($sess['title']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-4">
                <label class="form-label fw-semibold">Title</label>
                <input type="text" name="title" class="form-control" required>
            </div>

            <div class="col-md-4">
                <label class="form-label fw-semibold">Type</label>
                <select name="content_type" class="form-select contentTypeSelect">
                    <option value="link">Link</option>
                    <option value="pdf">PDF</option>
                    <option value="video">Video</option>
                    <option value="text">Text</option>
                </select>
            </div>

            <div class="col-12">
                <label class="form-label fw-semibold">Description</label>
                <textarea name="description" class="form-control" rows="2"></textarea>
            </div>

            <div class="col-md-6 urlBox">
                <label class="form-label fw-semibold">URL</label>
                <input type="url" name="url" class="form-control" placeholder="https://...">
                <div class="form-hint mt-1">Use only for external links. Do not paste C:\Users\ paths.</div>
            </div>

            <div class="col-md-6">
                <label class="form-label fw-semibold">Upload file</label>
                <input type="file" name="file" class="form-control">
                <div class="form-hint mt-1">Allowed: PDF, video MP4/WEBM/MOV/M4V/OGG/OGV, documents, images, CSV, ZIP. Max <?= (int)$MAX_MB ?>MB.</div>
            </div>

            <div class="col-12 d-flex align-items-center gap-4">
                <label class="form-check mb-0">
                    <input class="form-check-input" type="checkbox" name="active" checked>
                    Active
                </label>

                <label class="form-check mb-0">
                    <input class="form-check-input" type="checkbox" name="require_paid">
                    Require paid
                </label>
            </div>

            <div class="col-12">
                <button class="btn btn-primary">Add Content</button>
            </div>
        </form>
    </div>
</div>
</div>

<div class="modal fade" id="contentEditModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content" style="border-radius:18px;overflow:hidden;">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title fw-bold">Edit Content</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>

            <form method="post" enctype="multipart/form-data" id="editContentForm">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update">
                    <input type="hidden" name="id" id="edit_id">

                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label fw-semibold">Session</label>
                            <select name="session_id" id="edit_session_id" class="form-select">
                                <option value="0">Unassigned</option>
                                <?php foreach ($sessions as $sid => $sess): ?>
                                    <option value="<?= (int)$sid ?>"><?= esc($sess['title']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label fw-semibold">Title</label>
                            <input type="text" name="title" id="edit_title" class="form-control" required>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label fw-semibold">Type</label>
                            <select name="content_type" id="edit_content_type" class="form-select contentTypeSelect">
                                <option value="link">Link</option>
                                <option value="pdf">PDF</option>
                                <option value="video">Video</option>
                                <option value="text">Text</option>
                            </select>
                        </div>

                        <div class="col-12">
                            <label class="form-label fw-semibold">Description</label>
                            <textarea name="description" id="edit_description" class="form-control" rows="2"></textarea>
                        </div>

                        <div class="col-md-6 urlBox">
                            <label class="form-label fw-semibold">URL</label>
                            <input type="url" name="url" id="edit_url" class="form-control" placeholder="https://...">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Replace file</label>
                            <input type="file" name="file" class="form-control">
                            <div class="form-hint mt-1">Leave empty to keep current file.</div>
                        </div>

                        <div class="col-12 d-flex gap-4">
                            <label class="form-check mb-0">
                                <input class="form-check-input" type="checkbox" name="active" id="edit_active">
                                Active
                            </label>

                            <label class="form-check mb-0">
                                <input class="form-check-input" type="checkbox" name="require_paid" id="edit_paid">
                                Require paid
                            </label>
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button class="btn btn-primary">Update Content</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
(function () {
    const list = document.getElementById('content-list');
    const saveBtn = document.getElementById('btn-save-order');

    if (list && saveBtn) {
        function markDirty() {
            saveBtn.classList.remove('d-none');
        }

        list.addEventListener('dragstart', function (e) {
            const tr = e.target.closest('.content-row');
            if (!tr) return;

            tr.classList.add('dragging');
            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setData('text/plain', tr.dataset.id);
        });

        list.addEventListener('dragend', function (e) {
            const tr = e.target.closest('.content-row');
            if (tr) tr.classList.remove('dragging');
            markDirty();
        });

        list.addEventListener('dragover', function (e) {
            e.preventDefault();

            const dragging = list.querySelector('.content-row.dragging');
            if (!dragging) return;

            const after = getAfter(list, e.clientY);

            if (after == null) {
                list.appendChild(dragging);
            } else {
                list.insertBefore(dragging, after);
            }
        });

        saveBtn.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();

            const ids = Array.from(list.querySelectorAll('.content-row')).map(function (r) {
                return r.dataset.id;
            });

            fetch('content.php?course_id=<?= (int)$course_id ?>&module_id=<?= (int)$module_id ?>', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    action: 'reorder_content',
                    ids: ids
                })
            })
            .then(function (r) { return r.json(); })
            .then(function (j) {
                if (!j || !j.ok) {
                    alert((j && j.error) || 'Failed to save order');
                    return;
                }

                saveBtn.classList.add('d-none');
            })
            .catch(function () {
                alert('Network error');
            });
        });
    }

    function getAfter(container, y) {
        const rows = Array.from(container.querySelectorAll('.content-row:not(.dragging)'));
        let closest = {offset: Number.NEGATIVE_INFINITY, element: null};

        rows.forEach(function (row) {
            const box = row.getBoundingClientRect();
            const offset = y - box.top - box.height / 2;

            if (offset < 0 && offset > closest.offset) {
                closest = {offset: offset, element: row};
            }
        });

        return closest.element;
    }

    document.addEventListener('click', function (e) {
        const btn = e.target.closest('.toggle');
        if (!btn) return;

        e.preventDefault();

        const form = new FormData();
        form.append('action', 'toggle');
        form.append('id', btn.dataset.id || '');
        form.append('field', btn.dataset.field || '');

        fetch(location.href, {
            method: 'POST',
            body: form
        })
        .then(function (r) { return r.json(); })
        .then(function (j) {
            if (j && j.ok) {
                location.reload();
            } else {
                alert('Failed to toggle');
            }
        })
        .catch(function () {
            alert('Network error');
        });
    });

    function applyTypeBehaviour(selectEl) {
        const form = selectEl.closest('form');
        if (!form) return;

        const urlBox = form.querySelector('.urlBox');
        const urlInput = form.querySelector('[name="url"]');

        if (!urlBox || !urlInput) return;

        if (selectEl.value === 'video') {
            urlInput.value = '';
            urlInput.disabled = true;
            urlInput.placeholder = 'Upload video file instead';
            urlBox.classList.add('opacity-50');
        } else {
            urlInput.disabled = false;
            urlInput.placeholder = 'https://...';
            urlBox.classList.remove('opacity-50');
        }
    }

    document.querySelectorAll('.contentTypeSelect').forEach(function (selectEl) {
        selectEl.addEventListener('change', function () {
            applyTypeBehaviour(selectEl);
        });

        applyTypeBehaviour(selectEl);
    });

    document.querySelectorAll('.btnEditContent').forEach(function (btn) {
        btn.addEventListener('click', function () {
            document.getElementById('edit_id').value = btn.dataset.id || '';
            document.getElementById('edit_session_id').value = btn.dataset.session || '0';
            document.getElementById('edit_title').value = btn.dataset.title || '';
            document.getElementById('edit_content_type').value = btn.dataset.type || 'link';
            document.getElementById('edit_description').value = btn.dataset.description || '';
            document.getElementById('edit_url').value = btn.dataset.url || '';
            document.getElementById('edit_active').checked = btn.dataset.active === '1';
            document.getElementById('edit_paid').checked = btn.dataset.paid === '1';

            applyTypeBehaviour(document.getElementById('edit_content_type'));

            bootstrap.Modal.getOrCreateInstance(
                document.getElementById('contentEditModal')
            ).show();
        });
    });
})();
</script>
<?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>';