<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-card { border: 1px solid rgba(0,0,0,0.08); border-radius: 16px; }
	.aoust-preview {
		width: 100%;
		max-width: 520px;
		border-radius: 14px;
		border: 1px solid rgba(0,0,0,0.08);
		background: #f8f9fa;
	}
	.aoust-mini {
		border: 1px solid rgba(0,0,0,0.08);
		border-radius: 14px;
		padding: 12px;
	}
</style>

<?php
	$c = isset($course) && is_array($course) ? $course : array();
	$mode = isset($mode) ? $mode : 'create';
	$is_edit = ($mode === 'edit');
	$id = isset($c['id']) ? $c['id'] : '';
	$action = $is_edit ? base_url('aoust_courses/update/' . rawurlencode($id)) : base_url('aoust_courses/store');
	$mcqs = isset($c['mcqs']) && is_array($c['mcqs']) ? $c['mcqs'] : array();
?>

<div class="care-admin" id="aoustCourseForm">
	<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 course' : 'Add course'); ?></h1>
				<p class="ca-sub mb-0">Course fields + course MCQs + quizzes inside this course (each quiz has MCQs).</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_courses'); ?>">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 course' : 'Add course'; ?></h5>
					<p class="mb-0">Saved to Firestore collection <strong>Courses</strong>.</p>
				</div>
				<div class="ca-card-body">
					<form method="post" action="<?php echo $action; ?>" enctype="multipart/form-data" id="courseForm">
						<input type="hidden" name="mcqs_json" id="mcqs_json">

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

						<div class="mb-3">
							<label class="form-label">Category</label>
							<input class="form-control" name="category" placeholder="e.g. Language, Culture, Orientation" value="<?php echo htmlspecialchars(isset($c['category']) ? $c['category'] : ''); ?>">
							<div class="form-text aoust-muted">Stored on the course document as <strong>category</strong> (plain text tag).</div>
						</div>

						<div class="row g-3">
							<div class="col-md-6">
								<label class="form-label">Duration</label>
								<input class="form-control" name="duration" placeholder="e.g. 4 weeks / 10 lessons" value="<?php echo htmlspecialchars(isset($c['duration']) ? $c['duration'] : ''); ?>">
							</div>
							<div class="col-md-6">
								<label class="form-label">Course video</label>
								<input class="form-control" type="file" name="video" accept="video/*,.mp4,.webm,.mov,.mkv">
								<div class="form-text aoust-muted">Uploaded to Firebase Storage; URL saved as <strong>video</strong>.</div>
							</div>
						</div>

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

						<div class="row g-3 mt-0">
							<div class="col-md-12">
								<label class="form-label">Course image</label>
								<input class="form-control" type="file" name="image" accept="image/*">
								<div class="form-text aoust-muted">Uploaded to Firebase Storage and saved as a URL. <strong>User ID</strong> is taken from your logged-in session automatically.</div>
							</div>
						</div>

						<hr class="my-4">

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

						<div class="d-flex gap-2 mt-4">
							<a class="btn btn-light border" href="<?php echo base_url('aoust_courses'); ?>">Cancel</a>
							<button class="btn btn-primary" type="submit"><?php echo $is_edit ? 'Save changes' : 'Create course'; ?></button>
							<?php if ($is_edit): ?>
								<a class="btn btn-outline-danger ms-auto" href="<?php echo base_url('aoust_courses/delete/' . rawurlencode($id)); ?>" onclick="return confirm('Delete this course?');">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-regular fa-image me-2 text-success"></i>Preview</h5>
					<p class="mb-0">Existing image (if saved).</p>
				</div>
				<div class="ca-card-body">
					<?php if (!empty($c['image'])): ?>
						<img class="aoust-preview" src="<?php echo htmlspecialchars($c['image']); ?>" alt="">
					<?php else: ?>
						<div class="aoust-muted small">No image yet.</div>
					<?php endif; ?>
					<?php
						$vid = isset($c['video']) ? trim((string) $c['video']) : '';
					?>
					<?php if ($vid !== ''): ?>
						<hr class="my-3">
						<div class="aoust-muted small mb-1">Current video</div>
						<video class="aoust-preview mt-1" src="<?php echo htmlspecialchars($vid); ?>" controls playsinline preload="metadata"></video>
						<div class="small mt-2"><a href="<?php echo htmlspecialchars($vid); ?>" target="_blank" rel="noopener">Open URL</a></div>
					<?php elseif ($is_edit): ?>
						<hr class="my-3">
						<div class="aoust-muted small">No video uploaded yet.</div>
					<?php endif; ?>
				</div>
			</div>

			<div class="ca-card">
				<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>Optional category label for filtering/display</li>
						<li>At least 1 course MCQ</li>
						<li>Each question: 3–6 options + correct answer</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 initialMcqs = <?php echo json_encode($mcqs); ?>;

	var mcqsWrap = document.getElementById('courseMcqsWrap');
	var btnAddMcq = document.getElementById('btnAddCourseMcq');
	var hidMcqs = document.getElementById('mcqs_json');
	var form = document.getElementById('courseForm');

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

	function normalizeQ(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 mcqCard(qIndex, q, namePrefix) {
		var opts = q.options || [];
		while (opts.length < 3) opts.push('');
		if (opts.length > 6) opts = opts.slice(0, 6);

		var rows = opts.map(function (opt, i) {
			return '' +
				'<div class="d-flex align-items-center gap-2" data-opt="' + i + '">' +
					'<input class="form-check-input m-0" type="radio" name="correct_' + namePrefix + '_' + qIndex + '" ' + (q.correctIndex === i ? 'checked' : '') + ' data-field="correctRadio">' +
					'<input class="form-control" data-field="optText" value="' + escapeHtml(opt || '') + '" placeholder="Option ' + (i + 1) + '">' +
				'</div>';
		}).join('');

		return '' +
			'<div class="aoust-mini mb-3" data-mcq="' + qIndex + '">' +
				'<div class="d-flex align-items-center justify-content-between mb-2">' +
					'<div class="fw-bold">MCQ ' + (qIndex + 1) + '</div>' +
					'<button type="button" class="btn btn-sm btn-outline-danger" data-action="removeMcq">Remove</button>' +
				'</div>' +
				'<div class="mb-3">' +
					'<label class="form-label">Question</label>' +
					'<input class="form-control" data-field="qText" value="' + escapeHtml(q.text) + '">' +
				'</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 getMcqsState(container) {
		var cards = container.querySelectorAll('[data-mcq]');
		var out = [];
		cards.forEach(function (card) {
			var text = card.querySelector('[data-field="qText"]').value || '';
			var rows = card.querySelectorAll('[data-role="options"] [data-opt]');
			var options = [];
			var correctIndex = -1;
			rows.forEach(function (row, i) {
				options.push(row.querySelector('[data-field="optText"]').value || '');
				if (row.querySelector('[data-field="correctRadio"]').checked) correctIndex = i;
			});
			var correctAnswer = (correctIndex >= 0 && correctIndex < options.length) ? options[correctIndex] : '';
			out.push({ text: text, options: options, correctIndex: correctIndex, correctAnswer: correctAnswer });
		});
		return out;
	}

	function renderCourseMcqs(mcqs) {
		var normalized = (mcqs || []).map(normalizeQ);
		if (normalized.length === 0) normalized = [{ text: '', options: ['', '', ''], correctIndex: 0 }];
		mcqsWrap.innerHTML = normalized.map(function (q, idx) { return mcqCard(idx, q, 'course'); }).join('');
	}

	btnAddMcq.addEventListener('click', function () {
		var curr = getMcqsState(mcqsWrap);
		curr.push({ text: '', options: ['', '', ''], correctIndex: 0 });
		renderCourseMcqs(curr);
	});

	// Delegated handlers for MCQ cards (course)
	mcqsWrap.addEventListener('click', function (e) {
		var card = e.target.closest('[data-mcq]');
		if (!card) return;
		var action = e.target.getAttribute('data-action');
		if (!action) return;
		var idx = Number(card.getAttribute('data-mcq'));
		var curr = getMcqsState(mcqsWrap);
		var q = curr[idx];
		if (action === 'removeMcq') {
			curr.splice(idx, 1);
			renderCourseMcqs(curr);
			return;
		}
		if (action === 'addOption') {
			if (q.options.length >= 6) return;
			q.options.push('');
			curr[idx] = q;
			renderCourseMcqs(curr);
			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;
			curr[idx] = q;
			renderCourseMcqs(curr);
			return;
		}
	});

	form.addEventListener('submit', function () {
		hidMcqs.value = JSON.stringify(getMcqsState(mcqsWrap));
	});

	// Initial render
	renderCourseMcqs(Array.isArray(initialMcqs) ? initialMcqs : []);
})();
</script>

