';
}).join('');
}
// CMS search & filter
document.addEventListener('input', function(e) {
if (e.target.id === 'cms-search') filterCmsContent();
});
document.addEventListener('change', function(e) {
if (e.target.id === 'cms-filter-status' || e.target.id === 'cms-filter-category') filterCmsContent();
});
function filterCmsContent() {
var items = window._cmsContentData || [];
var search = (document.getElementById('cms-search') || {}).value || '';
var statusFilter = (document.getElementById('cms-filter-status') || {}).value || 'all';
var catFilter = (document.getElementById('cms-filter-category') || {}).value || 'all';
search = search.toLowerCase().trim();
var filtered = items.filter(function(item) {
if (search && item.title.toLowerCase().indexOf(search) === -1 && (item.subject || '').toLowerCase().indexOf(search) === -1) return false;
if (statusFilter === 'published' && !item.published) return false;
if (statusFilter === 'draft' && item.published) return false;
if (catFilter !== 'all' && String(item.category_id) !== catFilter) return false;
return true;
});
renderCmsContentList(filtered);
}
// ── Quill tooltip fix ─────────────────────────────────────
// Moves the tooltip element to document.body so overflow:hidden on
// ancestor containers cannot clip it. Recalculates position to
// viewport (fixed) coordinates on every show.
function patchQuillTooltip(q) {
var tooltip = q && q.theme && q.theme.tooltip;
if (!tooltip || !tooltip.root) return;
var el = tooltip.root;
document.body.appendChild(el);
el.style.position = 'fixed';
el.style.zIndex = '10000';
var origPosition = tooltip.position.bind(tooltip);
tooltip.position = function(reference) {
origPosition(reference);
// Quill sets left/top as container-relative; convert to viewport coords
var rect = q.container.getBoundingClientRect();
var l = rect.left + parseFloat(el.style.left || 0);
var t = rect.top + parseFloat(el.style.top || 0);
// Clamp to viewport
var tw = el.offsetWidth || 200;
var th = el.offsetHeight || 40;
if (l + tw > window.innerWidth - 8) l = window.innerWidth - tw - 8;
if (l < 8) l = 8;
if (t + th > window.innerHeight - 8) t = rect.top + parseFloat(el.style.top || 0) - th - 8;
if (t < 8) t = 8;
el.style.left = l + 'px';
el.style.top = t + 'px';
};
}
// ── Quill body editor ─────────────────────────────────────
function initBodyEditor() {
var container = document.getElementById('lh-body-editor');
if (!container || _bodyQuill) return;
_bodyQuill = new Quill(container, {
theme: 'snow',
modules: {
toolbar: [
[{ header: [2, 3, false] }],
['bold', 'italic', 'underline', 'strike'],
[{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
['blockquote', 'code-block'],
['link'],
[{ color: [] }],
['clean']
]
}
});
patchQuillTooltip(_bodyQuill);
}
// Mini Quill for question text or option text
function makeMinQuill(container, existingHtml, isOption) {
var toolbar = isOption
? [['bold', 'italic'], ['link']]
: [['bold', 'italic'], [{ list: 'ordered' }, { list: 'bullet' }], ['link'], ['clean']];
var q = new Quill(container, {
theme: 'snow',
modules: { toolbar: toolbar }
});
patchQuillTooltip(q);
if (existingHtml) q.clipboard.dangerouslyPasteHTML(existingHtml);
return q;
}
// Toggle rich text on a question text area or option text area
function toggleRichText(btn) {
var isActive = btn.classList.contains('active');
var target = btn.dataset.target; // 'question' or 'option'
var block = btn.closest(target === 'question' ? '.lh-question-block' : '.lh-option-row');
if (!block) return;
if (target === 'question') {
var ta = block.querySelector('.lh-q-text');
var wrap = block.querySelector('.lh-q-richtext-wrap');
if (!isActive) {
// Enable: hide textarea, show quill
var currentVal = ta ? ta.value : '';
btn.classList.add('active');
btn.textContent = 'Plain Text';
if (ta) ta.style.display = 'none';
if (!wrap) {
wrap = document.createElement('div');
wrap.className = 'lh-q-richtext-wrap';
ta.parentNode.insertBefore(wrap, ta.nextSibling);
}
wrap.style.display = '';
if (!block._questionQuill) {
block._questionQuill = makeMinQuill(wrap, currentVal, false);
} else {
wrap.style.display = '';
}
} else {
// Disable: get HTML from quill, restore textarea
btn.classList.remove('active');
btn.textContent = 'Rich Text';
if (block._questionQuill) {
var html = block._questionQuill.root.innerHTML;
if (html === '
') html = '';
if (ta) { ta.value = html; ta.style.display = ''; }
}
if (wrap) wrap.style.display = 'none';
}
} else {
// option
var row = block;
var optInput = row.querySelector('.lh-opt-text');
var optWrap = row.querySelector('.lh-opt-richtext-wrap');
if (!isActive) {
var curVal = optInput ? optInput.value : '';
btn.classList.add('active');
btn.textContent = 'Plain';
if (optInput) optInput.style.display = 'none';
if (!optWrap) {
optWrap = document.createElement('div');
optWrap.className = 'lh-opt-richtext-wrap';
optInput.parentNode.insertBefore(optWrap, optInput.nextSibling);
}
optWrap.style.display = '';
if (!row._optQuill) {
row._optQuill = makeMinQuill(optWrap, curVal, true);
}
} else {
btn.classList.remove('active');
btn.textContent = 'Rich';
if (row._optQuill) {
var optHtml = row._optQuill.root.innerHTML;
if (optHtml === '
') optHtml = '';
if (optInput) { optInput.value = optHtml; optInput.style.display = ''; }
}
if (optWrap) optWrap.style.display = 'none';
}
}
}
// Read question text whether in rich text mode or plain
function getQText(block) {
if (block._questionQuill && block.querySelector('.lh-q-richtext-wrap') &&
block.querySelector('.lh-q-richtext-wrap').style.display !== 'none') {
var html = block._questionQuill.root.innerHTML;
return html === '
' ? '' : html;
}
var ta = block.querySelector('.lh-q-text');
return ta ? ta.value.trim() : '';
}
// Read option text whether in rich text mode or plain
function getOptText(row) {
if (row._optQuill && row.querySelector('.lh-opt-richtext-wrap') &&
row.querySelector('.lh-opt-richtext-wrap').style.display !== 'none') {
var html = row._optQuill.root.innerHTML;
return html === '
' ? '' : html;
}
var inp = row.querySelector('.lh-opt-text');
return inp ? inp.value.trim() : '';
}
function openEditor(contentId, contentType) {
var editor = document.getElementById('lh-cms-editor');
var listView = document.getElementById('cms-list-view');
if (!editor) return;
editor.classList.remove('hidden');
if (listView) listView.classList.add('hidden');
// Reset
document.getElementById('lh-cms-edit-id').value = '';
document.getElementById('lh-cms-edit-title').value = '';
document.getElementById('lh-cms-edit-subject').value = '';
document.getElementById('lh-cms-edit-category').value = '';
document.getElementById('lh-cms-edit-type').value = contentType || 'article';
document.getElementById('lh-cms-edit-published').value = 'false';
document.getElementById('lh-cms-questions').innerHTML = '';
document.getElementById('btn-lh-delete-content').classList.add('hidden');
initBodyEditor();
if (_bodyQuill) _bodyQuill.setContents([{ insert: '\n' }]);
// For quiz type, add a starter question
if (contentType === 'quiz' && !contentId) {
addQuestionBlock();
}
if (!contentId) return;
// Load existing content
fetch('/api/admin/learning/content/' + contentId, { headers: getAuthHeaders() })
.then(function(r) { return r.json(); })
.then(function(data) {
if (!data.success) { showToast('Failed to load', 'error'); return; }
var c = data.content;
document.getElementById('lh-cms-edit-id').value = c.id;
document.getElementById('lh-cms-edit-title').value = c.title;
document.getElementById('lh-cms-edit-subject').value = c.subject || '';
if (_bodyQuill) _bodyQuill.clipboard.dangerouslyPasteHTML(c.body || '');
document.getElementById('lh-cms-edit-category').value = c.category_id || '';
document.getElementById('lh-cms-edit-type').value = c.content_type || 'article';
document.getElementById('lh-cms-edit-published').value = c.published ? 'true' : 'false';
document.getElementById('btn-lh-delete-content').classList.remove('hidden');
// Load questions
var qContainer = document.getElementById('lh-cms-questions');
qContainer.innerHTML = '';
if (c.questions && c.questions.length > 0) {
c.questions.forEach(function(q) { addQuestionBlock(q); });
}
editor.scrollIntoView({ behavior: 'smooth' });
});
}
function closeEditor() {
var editor = document.getElementById('lh-cms-editor');
var listView = document.getElementById('cms-list-view');
if (editor) editor.classList.add('hidden');
if (listView) listView.classList.remove('hidden');
}
function saveContent() {
var id = document.getElementById('lh-cms-edit-id').value;
var title = document.getElementById('lh-cms-edit-title').value.trim();
var subject = document.getElementById('lh-cms-edit-subject').value.trim();
var body = _bodyQuill ? (_bodyQuill.root.innerHTML === '
' ? '' : _bodyQuill.root.innerHTML) : '';
var category_id = document.getElementById('lh-cms-edit-category').value || null;
var content_type = document.getElementById('lh-cms-edit-type').value;
var published = document.getElementById('lh-cms-edit-published').value === 'true';
if (!title) { showToast('Title required', 'error'); return; }
// Gather questions with validation
var questions = [];
var validationError = false;
var qBlocks = document.querySelectorAll('#lh-cms-questions .lh-question-block');
for (var qi = 0; qi < qBlocks.length; qi++) {
var qBlock = qBlocks[qi];
var qText = getQText(qBlock);
if (!qText) continue;
var qType = qBlock.querySelector('.lh-q-type').value;
var qExpl = qBlock.querySelector('.lh-q-explanation').value.trim();
var qId = qBlock.dataset.questionId || null;
var options = [];
qBlock.querySelectorAll('.lh-option-row').forEach(function(row) {
var optText = getOptText(row);
if (!optText) return;
options.push({
option_text: optText,
is_correct: row.querySelector('.lh-opt-correct').checked,
explanation: row.querySelector('.lh-opt-expl').value.trim()
});
});
// Validate: must have a correct answer marked
var hasCorrect = options.some(function(o) { return o.is_correct; });
if (options.length > 0 && !hasCorrect) {
showToast('Question "' + qText.substring(0, 50) + '..." needs a correct answer marked', 'error');
qBlock.style.outline = '2px solid var(--red)';
qBlock.scrollIntoView({ behavior: 'smooth', block: 'center' });
validationError = true;
break;
}
qBlock.style.outline = '';
questions.push({
id: qId,
question_text: qText,
question_type: qType,
explanation: qExpl,
options: options
});
}
if (validationError) return;
var payload = { title: title, body: body, category_id: category_id, subject: subject, content_type: content_type, published: published };
var method = id ? 'PUT' : 'POST';
var url = id ? '/api/admin/learning/content/' + id : '/api/admin/learning/content';
showLoading('Saving...');
fetch(url, { method: method, headers: getAuthHeaders(), body: JSON.stringify(payload) })
.then(function(r) { return r.json(); })
.then(function(data) {
if (!data.success) { hideLoading(); showToast(data.error || 'Save failed', 'error'); return; }
var contentId = id || data.id;
// Save questions sequentially
saveQuestions(contentId, questions, 0, function() {
hideLoading();
showToast('Content saved', 'success');
closeEditor();
loadCmsContent();
loadCmsStats();
loaded = false; // force refresh user feed
});
})
.catch(function() { hideLoading(); showToast('Save failed', 'error'); });
}
function saveQuestions(contentId, questions, index, callback) {
if (index >= questions.length) { callback(); return; }
var q = questions[index];
var qId = q.id;
var method, url;
if (qId) {
method = 'PUT';
url = '/api/admin/learning/questions/' + qId;
} else {
method = 'POST';
url = '/api/admin/learning/content/' + contentId + '/questions';
}
fetch(url, {
method: method,
headers: getAuthHeaders(),
body: JSON.stringify({
question_text: q.question_text,
question_type: q.question_type,
explanation: q.explanation,
options: q.options
})
})
.then(function(r) { return r.json(); })
.then(function() {
saveQuestions(contentId, questions, index + 1, callback);
})
.catch(function() {
saveQuestions(contentId, questions, index + 1, callback);
});
}
function deleteContent() {
var id = document.getElementById('lh-cms-edit-id').value;
if (!id) return;
if (!confirm('Delete this content and all its questions? This cannot be undone.')) return;
fetch('/api/admin/learning/content/' + id, { method: 'DELETE', headers: getAuthHeaders() })
.then(function(r) { return r.json(); })
.then(function(data) {
if (data.success) {
showToast('Content deleted', 'info');
closeEditor();
loadCmsContent();
loadCmsStats();
loaded = false;
} else showToast(data.error || 'Failed', 'error');
});
}
function addQuestionBlock(existingQ) {
var container = document.getElementById('lh-cms-questions');
if (!container) return;
var block = document.createElement('div');
block.className = 'lh-question-block';
if (existingQ && existingQ.id) block.dataset.questionId = existingQ.id;
var qNum = container.querySelectorAll('.lh-question-block').length + 1;
block.innerHTML =
'
' +
'
' +
'Q' + qNum + '' +
'' +
'' +
'
' +
'' +
'
' +
'' +
'
' +
'' +
'
' +
'' +
'' +
'
' +
'' +
'' +
'
';
container.appendChild(block);
// Set textarea values after insertion (can't use value="" attr on textarea)
block.querySelector('.lh-q-text').value = existingQ ? existingQ.question_text || '' : '';
block.querySelector('.lh-q-explanation').value = existingQ ? existingQ.explanation || '' : '';
var optList = block.querySelector('.lh-options-list');
if (existingQ && existingQ.options && existingQ.options.length > 0) {
existingQ.options.forEach(function(opt) { addOptionRow(optList, opt); });
} else if (existingQ && existingQ.question_type === 'true_false') {
addOptionRow(optList, { option_text: 'True', is_correct: false, explanation: '' });
addOptionRow(optList, { option_text: 'False', is_correct: false, explanation: '' });
} else {
// Add 4 blank MCQ options
for (var i = 0; i < 4; i++) addOptionRow(optList, null);
}
}
function addOptionRow(container, opt) {
if (!container) return;
var row = document.createElement('div');
row.className = 'lh-option-row';
row.innerHTML =
'' +
'
' +
'' +
'' +
'
' +
'' +
'';
container.appendChild(row);
// Set option text value after insertion (can't use value="" on nested input via innerHTML)
row.querySelector('.lh-opt-text').value = opt ? opt.option_text || '' : '';
}
// ── Helpers ──────────────────────────────────────────────────
function esc(str) {
if (!str) return '';
return String(str).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"');
}
function sanitizeHtml(html) {
// Allowlist-based sanitizer: only safe tags and no event handlers
var ALLOWED_TAGS = ['p','br','b','strong','i','em','u','s','h1','h2','h3','h4','h5','h6',
'ul','ol','li','a','blockquote','code','pre','table','thead','tbody','tr','th','td',
'hr','div','span','sub','sup','dl','dt','dd'];
var ALLOWED_ATTRS = { 'a': ['href'], 'td': ['colspan','rowspan'], 'th': ['colspan','rowspan'], 'li': ['class'], 'ol': ['class'], 'ul': ['class'], 'span': ['class'], 'p': ['class'] };
var div = document.createElement('div');
div.innerHTML = html;
function clean(node) {
var children = Array.prototype.slice.call(node.childNodes);
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (child.nodeType === 3) continue; // text nodes OK
if (child.nodeType !== 1) { child.remove(); continue; } // remove comments etc
var tag = child.tagName.toLowerCase();
if (ALLOWED_TAGS.indexOf(tag) === -1) {
// Replace with text content
var text = document.createTextNode(child.textContent);
node.replaceChild(text, child);
continue;
}
// Remove all attributes except explicitly allowed ones
var allowed = ALLOWED_ATTRS[tag] || [];
var attrs = Array.prototype.slice.call(child.attributes);
for (var j = 0; j < attrs.length; j++) {
if (allowed.indexOf(attrs[j].name) === -1) {
child.removeAttribute(attrs[j].name);
}
}
// For tags, validate href is not javascript:
if (tag === 'a') {
var href = (child.getAttribute('href') || '').trim().toLowerCase();
if (href.indexOf('javascript:') === 0 || href.indexOf('data:') === 0 || href.indexOf('vbscript:') === 0) {
child.setAttribute('href', '#');
}
child.setAttribute('rel', 'noopener noreferrer');
child.setAttribute('target', '_blank');
}
clean(child);
}
}
clean(div);
return div.innerHTML;
}
})();