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

<style>
	.aoust-muted { color: rgba(33, 37, 41, 0.7); }
	.btn-ca-success { color: #fff !important; }
	.btn-ca-success:hover, .btn-ca-success:focus { color: #fff !important; }
	.aoust-q-card { border: 1px solid rgba(0,0,0,0.08); border-radius: 16px; }
	.aoust-opt-input { font-family: inherit; }
</style>

<?php
	$q = isset($quiz) && is_array($quiz) ? $quiz : array();
	$mode = isset($mode) ? $mode : 'create';
	$is_edit = ($mode === 'edit');
	$id = isset($q['id']) ? $q['id'] : '';
	$action = $is_edit ? base_url('aoust_quiz/update/' . rawurlencode($id)) : base_url('aoust_quiz/store');
	$questions = isset($q['questions']) && is_array($q['questions']) ? $q['questions'] : array();
	$quizType = isset($q['type']) ? (string) $q['type'] : 'au_pair';
	if ($quizType !== 'au_pair' && $quizType !== 'family_host') {
		$quizType = 'au_pair';
	}
?>

<div class="care-admin" id="aoustQuizForm">
	<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) : ($is_edit ? 'Edit quiz' : 'Add quiz'); ?></h1>
				<p class="ca-sub mb-0">MCQ questions: each question can have 3–6 options; select the correct answer.</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('aoust_quiz'); ?>">Back to list</a>
				</div>
			</div>
		</div>
	</div>

	<div class="row g-3">
		<div class="col-lg-8">
			<div class="ca-card mb-4">
				<div class="ca-card-header">
					<h5 class="ca-card-title mb-1"><i class="fa-solid fa-pen-to-square me-2 text-success"></i><?php echo $is_edit ? 'Edit quiz' : 'Add quiz'; ?></h5>
					<p class="mb-0">Saved to Firestore collection <strong>Quaiz</strong>.</p>
				</div>
				<div class="ca-card-body">
					<form method="post" action="<?php echo $action; ?>" id="quizForm">
						<input type="hidden" name="questions_json" id="questions_json">

						<div class="mb-3">
							<label class="form-label">Type</label>
							<select class="form-select" name="type" required>
								<option value="au_pair" <?php echo $quizType === 'au_pair' ? ' selected' : ''; ?>>Au pair</option>
								<option value="family_host" <?php echo $quizType === 'family_host' ? ' selected' : ''; ?>>Family host</option>
							</select>
						</div>

						<div class="mb-3">
							<label class="form-label">Title</label>
							<input class="form-control" name="title" required value="<?php echo htmlspecialchars(isset($q['title']) ? $q['title'] : ''); ?>">
						</div>

						<div class="mb-3">
							<label class="form-label">Description</label>
							<textarea class="form-control" name="description" rows="3"><?php echo htmlspecialchars(isset($q['description']) ? $q['description'] : ''); ?></textarea>
						</div>

						<div class="mb-4">
							<label class="form-label">User ID</label>
							<input class="form-control" name="userId" value="<?php echo htmlspecialchars(isset($q['userId']) ? $q['userId'] : ''); ?>">
							<div class="form-text aoust-muted">Optional. If blank, controller will use session userId.</div>
						</div>

						<div class="d-flex align-items-center justify-content-between mb-2">
							<h6 class="mb-0 fw-bold">Questions</h6>
							<button type="button" class="btn btn-ca-success" id="btnAddQuestion"><i class="fa-solid fa-plus me-2"></i>Add question</button>
						</div>

						<div id="questionsWrap"></div>

						<div class="d-flex gap-2 mt-4">
							<a class="btn btn-light border" href="<?php echo base_url('aoust_quiz'); ?>">Cancel</a>
							<button class="btn btn-primary" type="submit"><?php echo $is_edit ? 'Save changes' : 'Create quiz'; ?></button>
							<?php if ($is_edit): ?>
								<a class="btn btn-outline-danger ms-auto" href="<?php echo base_url('aoust_quiz/delete/' . rawurlencode($id)); ?>" onclick="return confirm('Delete this quiz?');">Delete</a>
							<?php endif; ?>
						</div>
					</form>
				</div>
			</div>
		</div>

		<div class="col-lg-4">
			<div class="ca-card mb-4">
				<div class="ca-card-header">
					<h5 class="ca-card-title mb-1"><i class="fa-solid fa-circle-info me-2 text-success"></i>Rules</h5>
					<p class="mb-0">Validation rules.</p>
				</div>
				<div class="ca-card-body">
					<ul class="mb-0">
						<li>Type: Au pair or Family host</li>
						<li>At least 1 question</li>
						<li>Each question: 3–6 options</li>
						<li>Select 1 correct option</li>
					</ul>
					<?php if ($is_edit): ?>
						<hr>
						<div class="aoust-muted small">Document ID</div>
						<div class="fw-semibold"><?php echo htmlspecialchars($id); ?></div>
					<?php endif; ?>
				</div>
			</div>
		</div>
	</div>
</div>

<script>
(function () {
	var initial = <?php echo json_encode($questions); ?>;
	var wrap = document.getElementById('questionsWrap');
	var btnAdd = document.getElementById('btnAddQuestion');
	var hidden = document.getElementById('questions_json');
	var form = document.getElementById('quizForm');

	function escapeHtml(str) {
		return String(str)
			.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
			.replaceAll('"', '&quot;').replaceAll("'", '&#039;');
	}

	function normalizeQuestion(q) {
		return {
			text: (q && q.text) ? String(q.text) : '',
			options: Array.isArray(q && q.options) ? q.options.map(function (o) { return String(o); }) : [],
			correctIndex: (q && typeof q.correctIndex !== 'undefined') ? Number(q.correctIndex) : -1
		};
	}

	function cardTemplate(qIndex, q) {
		var opts = q.options || [];
		var rows = opts.map(function (opt, i) {
			return optionRowTemplate(qIndex, i, opt, q.correctIndex === i);
		}).join('');
		return '' +
			'<div class="p-3 mb-3 aoust-q-card" data-q="' + qIndex + '">' +
				'<div class="d-flex align-items-center justify-content-between mb-2">' +
					'<div class="fw-bold">Question ' + (qIndex + 1) + '</div>' +
					'<button type="button" class="btn btn-sm btn-outline-danger" data-action="removeQuestion">Remove</button>' +
				'</div>' +
				'<div class="mb-3">' +
					'<label class="form-label">Question text</label>' +
					'<input class="form-control" data-field="qText" value="' + escapeHtml(q.text) + '" placeholder="Enter question...">' +
				'</div>' +
				'<div class="d-flex align-items-center justify-content-between mb-2">' +
					'<div class="fw-semibold">Options <span class="text-muted small">(3–6)</span></div>' +
					'<div class="d-flex gap-2">' +
						'<button type="button" class="btn btn-sm btn-light border" data-action="addOption">Add option</button>' +
						'<button type="button" class="btn btn-sm btn-light border" data-action="removeOption">Remove last</button>' +
					'</div>' +
				'</div>' +
				'<div class="vstack gap-2" data-role="options">' + rows + '</div>' +
				'<div class="form-text aoust-muted mt-2">Select the radio button to set the correct answer.</div>' +
			'</div>';
	}

	function optionRowTemplate(qIndex, optIndex, value, checked) {
		return '' +
			'<div class="d-flex align-items-center gap-2" data-opt="' + optIndex + '">' +
				'<input class="form-check-input m-0" type="radio" name="correct_' + qIndex + '" ' + (checked ? 'checked' : '') + ' data-field="correctRadio">' +
				'<input class="form-control aoust-opt-input" data-field="optText" value="' + escapeHtml(value || '') + '" placeholder="Option ' + (optIndex + 1) + '">' +
			'</div>';
	}

	function getState() {
		var cards = wrap.querySelectorAll('[data-q]');
		var out = [];
		cards.forEach(function (card, qIndex) {
			var text = card.querySelector('[data-field="qText"]').value || '';
			var optWrap = card.querySelector('[data-role="options"]');
			var optRows = optWrap.querySelectorAll('[data-opt]');
			var options = [];
			var correctIndex = -1;
			optRows.forEach(function (row, i) {
				var optText = row.querySelector('[data-field="optText"]').value || '';
				options.push(optText);
				var checked = row.querySelector('[data-field="correctRadio"]').checked;
				if (checked) correctIndex = i;
			});

			// Also store correctAnswer for convenience
			var correctAnswer = (correctIndex >= 0 && correctIndex < options.length) ? options[correctIndex] : '';

			out.push({
				text: text,
				options: options,
				correctIndex: correctIndex,
				correctAnswer: correctAnswer
			});
		});
		return out;
	}

	function render(questions) {
		var normalized = questions.map(normalizeQuestion);
		normalized.forEach(function (q) {
			// Ensure 3 options minimum on UI
			while (q.options.length < 3) q.options.push('');
			if (q.options.length > 6) q.options = q.options.slice(0, 6);
		});
		wrap.innerHTML = normalized.map(function (q, idx) { return cardTemplate(idx, q); }).join('');
	}

	btnAdd.addEventListener('click', function () {
		var current = getState();
		current.push({ text: '', options: ['', '', ''], correctIndex: 0 });
		render(current);
	});

	wrap.addEventListener('click', function (e) {
		var card = e.target.closest('[data-q]');
		if (!card) return;
		var action = e.target.getAttribute('data-action');
		if (!action) return;

		var qIndex = Number(card.getAttribute('data-q'));
		var current = getState();
		var q = current[qIndex];

		if (action === 'removeQuestion') {
			current.splice(qIndex, 1);
			render(current);
			return;
		}
		if (action === 'addOption') {
			if (q.options.length >= 6) return;
			q.options.push('');
			current[qIndex] = q;
			render(current);
			return;
		}
		if (action === 'removeOption') {
			if (q.options.length <= 3) return;
			q.options.pop();
			if (q.correctIndex >= q.options.length) q.correctIndex = q.options.length - 1;
			current[qIndex] = q;
			render(current);
			return;
		}
	});

	form.addEventListener('submit', function (e) {
		var state = getState();
		hidden.value = JSON.stringify(state);
	});

	// initial
	if (!Array.isArray(initial) || initial.length === 0) {
		render([{ text: '', options: ['', '', ''], correctIndex: 0 }]);
	} else {
		render(initial);
	}
})();
</script>

