let selectedLessonId = null;
let selectedSubjectId = null;
const languageModal = new bootstrap.Modal(document.getElementById('languageModal'));

document.addEventListener('click', (e) => {
    if (e.target.classList.contains('submit-btn')) {
        e.preventDefault();

        selectedSubjectId = e.target.getAttribute('data-subject-id');
        selectedLessonId = e.target.getAttribute('data-lesson-id');

        languageModal.show();
    }
});

// --- When Language Selected ---
document.querySelectorAll('.lang-btn').forEach(langBtn => {
    langBtn.addEventListener('click', async () => {
        const language = langBtn.getAttribute('data-lang');

        if (!selectedSubjectId || !selectedLessonId) {
            Swal.fire("Error", "Missing Subject or Lesson ID!", "error");
            return;
        }

        console.log(selectedSubjectId);
        console.log(selectedLessonId);
        console.log(language);

        try {
            const response = await fetch("Backend/Process/load_exam_questions.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    subject_id: selectedSubjectId,
                    lesson_id: selectedLessonId,
                    language: language
                })
            });

            const result = await response.json();

            if (result.status) {
                console.log(result);
                Swal.fire({
                    title: "Exam Loaded!",
                    text: "Redirecting to your examination...",
                    icon: "success",
                    timer: 1500,
                    showConfirmButton: false
                });
                setTimeout(() => {
                     window.location.href = `Examination.php?lesson_id=${selectedLessonId}&language=${language}&subject_id=${selectedSubjectId}`;
                }, 1500);
            } else {
                Swal.fire("Error", result.message, "error");
            }

        } catch (error) {
            console.error("Error:", error);
            Swal.fire("Error", "Something went wrong!", "error");
        }
    });
});
