<link href="<?php echo base_url('assets/css/admin-panel.css'); ?>" rel="stylesheet">

<style>
	.aoust-table-actions .btn { padding-inline: 0.75rem; }
	.aoust-muted { color: rgba(33, 37, 41, 0.7); }
</style>

<div class="care-admin" id="aoustQuiz">
	<div class="ca-hero">
		<div class="ca-hero-inner row align-items-center g-3">
			<div class="col-lg-8">
				<p class="ca-kicker">AOUST portal</p>
				<h1 class="ca-title"><?php echo isset($page_title) ? htmlspecialchars($page_title) : 'AOUST — Quiz Module'; ?></h1>
				<p class="ca-sub mb-0">Quiz list with Add/Edit/Delete and a modal to view questions (JS dummy array).</p>
			</div>
			<div class="col-lg-4">
				<div class="ca-nav justify-content-lg-end">
					<a class="btn btn-light" href="<?php echo base_url('admin/aoust'); ?>">Dashboard</a>
					<a class="btn btn-light" href="<?php echo base_url('admin/aoust_users'); ?>">Users</a>
					<a class="btn btn-primary" href="<?php echo base_url('admin/aoust_quiz'); ?>">Quiz</a>
				</div>
			</div>
		</div>
	</div>

	<div class="ca-card mb-4">
		<div class="ca-card-header d-flex flex-column flex-lg-row align-items-lg-center justify-content-lg-between gap-2">
			<div>
				<h5 class="ca-card-title mb-1"><i class="fa-solid fa-circle-question me-2 text-success"></i>Quizzes</h5>
				<p class="mb-0">Create and maintain quizzes. View questions in a modal.</p>
			</div>
			<div class="d-flex align-items-stretch gap-2 flex-wrap justify-content-lg-end">
				<span class="badge rounded-pill ca-pill bg-light text-dark border" id="quizCountLabel">Showing 0</span>
				<div class="input-group" style="min-width: 280px;">
					<span class="input-group-text bg-white"><i class="fa-solid fa-magnifying-glass"></i></span>
					<input type="search" class="form-control" id="quizSearch" placeholder="Search title or description">
				</div>
				<button type="button" class="btn btn-ca-success" id="btnAddQuiz"><i class="fa-solid fa-plus me-2"></i>Add quiz</button>
			</div>
		</div>
		<div class="ca-card-body p-0">
			<div class="ca-table-wrap border-0 rounded-0 border-top">
				<table class="table ca-table table-striped mb-0 align-middle">
					<thead>
						<tr>
							<th>Title</th>
							<th>Type</th>
							<th>Description</th>
							<th class="text-end">Actions</th>
						</tr>
					</thead>
					<tbody id="quizTbody"></tbody>
				</table>
			</div>
		</div>
		<div class="p-4 d-none" id="quizEmpty">
			<div class="text-center">
				<div class="mb-2"><i class="fa-regular fa-face-frown fs-2 text-muted"></i></div>
				<div class="fw-semibold">No quizzes found</div>
				<div class="aoust-muted small">Try a different search keyword.</div>
			</div>
		</div>
	</div>
</div>

<div class="modal fade" id="modalQuiz" tabindex="-1" aria-hidden="true">
	<div class="modal-dialog modal-dialog-centered">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="modalQuizTitle">Quiz</h5>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<form id="formQuiz">
				<div class="modal-body">
					<input type="hidden" id="quiz_id">
					<div class="mb-3">
						<label class="form-label">Type</label>
						<select class="form-select" id="quiz_type" required>
							<option value="au_pair">Au pair</option>
							<option value="family_host">Family host</option>
						</select>
					</div>
					<div class="mb-3">
						<label class="form-label">Title</label>
						<input class="form-control" id="quiz_title" required>
					</div>
					<div class="mb-0">
						<label class="form-label">Description</label>
						<textarea class="form-control" id="quiz_desc" rows="3" required></textarea>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-light border" data-bs-dismiss="modal">Cancel</button>
					<button type="submit" class="btn btn-primary">Save</button>
				</div>
			</form>
		</div>
	</div>
</div>

<div class="modal fade" id="modalQuizQuestions" tabindex="-1" aria-hidden="true">
	<div class="modal-dialog modal-lg modal-dialog-centered">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="modalQuizQuestionsTitle">Questions</h5>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<div class="modal-body">
				<div class="alert alert-light border mb-3">
					<strong id="qqTitle"></strong>
					<div class="text-muted small" id="qqDesc"></div>
				</div>
				<div class="ca-table-wrap border rounded-4 overflow-hidden">
					<table class="table ca-table mb-0 align-middle">
						<thead>
							<tr>
								<th>#</th>
								<th>Question</th>
								<th>Options</th>
								<th>Answer</th>
							</tr>
						</thead>
						<tbody id="quizQuestionsTbody"></tbody>
					</table>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-light border" data-bs-dismiss="modal">Close</button>
			</div>
		</div>
	</div>
</div>

<script>
(function () {
	var quizzes = [
		{
			id: 'q1',
			type: 'au_pair',
			title: 'IELTS Quiz',
			description: 'Quick check on IELTS basics and scoring.',
			questions: [
				{ text: 'How many bands are in IELTS scoring?', options: ['5', '7', '9', '10'], answer: '9' },
				{ text: 'IELTS has which modules?', options: ['Listening', 'Reading', 'Writing', 'All of these'], answer: 'All of these' }
			]
		},
		{
			id: 'q2',
			type: 'family_host',
			title: 'Study Abroad Quiz',
			description: 'General study abroad process & documentation.',
			questions: [
				{ text: 'Which is commonly required for admission?', options: ['SOP', 'PAN card', 'Ration card', 'None'], answer: 'SOP' },
				{ text: 'Tuition fee is usually paid in?', options: ['Local currency only', 'University currency / payment gateway', 'Cash only', 'Crypto only'], answer: 'University currency / payment gateway' }
			]
		}
	];
	var searchQuery = '';

	function el(id) { return document.getElementById(id); }
	function escapeHtml(str) {
		return String(str)
			.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
			.replaceAll('"', '&quot;').replaceAll("'", '&#039;');
	}
	function nextId(prefix, list) {
		var max = 0;
		list.forEach(function (x) {
			var m = String(x.id || '').match(/\d+$/);
			if (m) max = Math.max(max, parseInt(m[0], 10));
		});
		return prefix + String(max + 1);
	}
	function showModal(modalId) {
		var node = document.getElementById(modalId);
		var m = bootstrap.Modal.getOrCreateInstance(node);
		m.show();
		return m;
	}

	function render() {
		var qText = (searchQuery || '').trim().toLowerCase();
		var filtered = quizzes.filter(function (q) {
			if (!qText) return true;
			var typeStr = (q.type === 'family_host') ? 'family host' : 'au pair';
			return (q.title + ' ' + q.description + ' ' + typeStr).toLowerCase().indexOf(qText) !== -1;
		});

		var countLabel = el('quizCountLabel');
		if (countLabel) {
			var extra = qText ? ' · filtered' : '';
			countLabel.textContent = 'Showing ' + filtered.length + ' of ' + quizzes.length + extra;
		}

		el('quizTbody').innerHTML = filtered.map(function (q) {
			var typeLabel = (q.type === 'family_host') ? 'Family host' : 'Au pair';
			return '' +
				'<tr>' +
					'<td class="fw-semibold">' + escapeHtml(q.title) + '</td>' +
					'<td><span class="badge bg-light text-dark border">' + escapeHtml(typeLabel) + '</span></td>' +
					'<td class="text-muted">' + escapeHtml(q.description) + '</td>' +
					'<td class="text-end">' +
						'<div class="btn-group aoust-table-actions" role="group">' +
							'<button class="btn btn-sm btn-light border" data-action="questions" data-id="' + escapeHtml(q.id) + '" title="Questions"><i class="fa-regular fa-rectangle-list"></i></button>' +
							'<button class="btn btn-sm btn-light border" data-action="edit" data-id="' + escapeHtml(q.id) + '" title="Edit"><i class="fa-regular fa-pen-to-square"></i></button>' +
							'<button class="btn btn-sm btn-outline-danger" data-action="delete" data-id="' + escapeHtml(q.id) + '" title="Delete"><i class="fa-regular fa-trash-can"></i></button>' +
						'</div>' +
					'</td>' +
				'</tr>';
		}).join('');

		var empty = el('quizEmpty');
		if (empty) {
			if (filtered.length === 0) empty.classList.remove('d-none');
			else empty.classList.add('d-none');
		}
	}

	function openQuizModal(mode, id) {
		el('modalQuizTitle').textContent = mode === 'add' ? 'Add quiz' : 'Edit quiz';
		if (mode === 'add') {
			el('quiz_id').value = '';
			el('quiz_type').value = 'au_pair';
			el('quiz_title').value = '';
			el('quiz_desc').value = '';
		} else {
			var q = quizzes.find(function (x) { return x.id === id; });
			el('quiz_id').value = q.id;
			el('quiz_type').value = (q.type === 'family_host') ? 'family_host' : 'au_pair';
			el('quiz_title').value = q.title;
			el('quiz_desc').value = q.description;
		}
		showModal('modalQuiz');
	}

	function openQuestions(id) {
		var q = quizzes.find(function (x) { return x.id === id; });
		el('modalQuizQuestionsTitle').textContent = 'Questions — ' + q.title;
		el('qqTitle').textContent = q.title;
		el('qqDesc').textContent = q.description;
		el('quizQuestionsTbody').innerHTML = (q.questions || []).map(function (qq, idx) {
			return '' +
				'<tr>' +
					'<td class="text-muted small">' + (idx + 1) + '</td>' +
					'<td class="fw-semibold">' + escapeHtml(qq.text) + '</td>' +
					'<td>' + escapeHtml((qq.options || []).join(', ')) + '</td>' +
					'<td><span class="badge bg-success-subtle text-success border border-success-subtle">' + escapeHtml(qq.answer) + '</span></td>' +
				'</tr>';
		}).join('');
		showModal('modalQuizQuestions');
	}

	el('btnAddQuiz').addEventListener('click', function () { openQuizModal('add'); });
	el('quizSearch').addEventListener('input', function () {
		searchQuery = el('quizSearch').value || '';
		render();
	});

	document.getElementById('aoustQuiz').addEventListener('click', function (e) {
		var btn = e.target.closest('button[data-action]');
		if (!btn) return;
		var action = btn.getAttribute('data-action');
		var id = btn.getAttribute('data-id');
		if (action === 'questions') return openQuestions(id);
		if (action === 'edit') return openQuizModal('edit', id);
		if (action === 'delete') {
			var q = quizzes.find(function (x) { return x.id === id; });
			if (confirm('Delete quiz "' + q.title + '"?')) {
				quizzes = quizzes.filter(function (x) { return x.id !== id; });
				render();
			}
		}
	});

	el('formQuiz').addEventListener('submit', function (e) {
		e.preventDefault();
		var id = el('quiz_id').value.trim();
		var qtype = el('quiz_type').value === 'family_host' ? 'family_host' : 'au_pair';
		var title = el('quiz_title').value.trim();
		var desc = el('quiz_desc').value.trim();
		if (!id) quizzes.unshift({ id: nextId('q', quizzes), type: qtype, title: title, description: desc, questions: [] });
		else quizzes = quizzes.map(function (q) { return q.id === id ? { id: q.id, type: qtype, title: title, description: desc, questions: q.questions || [] } : q; });
		bootstrap.Modal.getInstance(document.getElementById('modalQuiz')).hide();
		render();
	});

	render();
})();
</script>

