// Examination.js
// Requires Swal (sweetalert) loaded

const userAnswers = {}; // question_id -> 'A'|'B'|...
let questionCache = []; // array of question objects returned from server
let currentIndex = 0;
let totalQuestions = 0;
let timerInterval = null;

function formatTime(seconds) {
    const h = String(Math.floor(seconds / 3600)).padStart(2,'0');
    const m = String(Math.floor((seconds % 3600)/60)).padStart(2,'0');
    const s = String(seconds % 60).padStart(2,'0');
    return `${h}:${m}:${s}`;
}

async function postJSON(url, payload) {
    const res = await fetch(url, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
    });
    const text = await res.text();
    try { return JSON.parse(text); }
    catch (e) {
        console.error("Invalid JSON response:", text);
        Swal.fire("Server Error","Invalid response from server","error");
        return { status:false, message: "Invalid server response" };
    }
}

document.addEventListener("DOMContentLoaded", async () => {
    const questionText = document.querySelector(".question-card p");
    const optionsContainer = document.querySelector(".question-options");
    const nextBtn = document.querySelector(".next-btn");
    const prevBtn = document.querySelector(".prev-btn");
    const navContainer = document.querySelector(".question-nav");
    const timerElement = document.querySelector(".timer");

    const urlParams = new URLSearchParams(window.location.search);
    const lesson_id = urlParams.get("lesson_id");
    const subject_id = urlParams.get("subject_id");
    const language = urlParams.get("language");

    async function loadQuestions() {
        const r = await postJSON("Backend/Process/load_exam_questions.php", { lesson_id, language });
        if (!r.status) {
            Swal.fire("Error", r.message || "Failed to load questions", "error"); 
            return;
        }

        questionCache = r.data;
        totalQuestions = questionCache.length;
        currentIndex = 0;
        renderNavButtons();
        renderQuestion(currentIndex);

        // Start timer from displayed value
        const initialTimeText = timerElement.textContent.trim();
        const [h, m, s] = initialTimeText.split(':').map(Number);
        const remainingSeconds = h * 3600 + m * 60 + s;
        startTimer(remainingSeconds, timerElement);
    }

    function renderNavButtons() {
        if (!navContainer) return;
        navContainer.innerHTML = "";
        for (let i=0;i<totalQuestions;i++){
            const btn = document.createElement("button");
            btn.type = "button";
            btn.textContent = i+1;
            btn.className = i===currentIndex ? "active" : "";
            btn.addEventListener("click", ()=> gotoIndex(i));
            navContainer.appendChild(btn);
        }
    }

    function updateNav() {
        if (!navContainer) return;
        const btns = navContainer.querySelectorAll("button");
        btns.forEach((b,i)=> b.classList.toggle("active", i===currentIndex));
    }

    function renderQuestion(index) {
        const q = questionCache[index];
        if (!q) return;
        questionText.textContent = q.question;
        optionsContainer.innerHTML = `
            <label><input type="radio" name="option" value="A"> A. ${q.option_a}</label>
            <label><input type="radio" name="option" value="B"> B. ${q.option_b}</label>
            <label><input type="radio" name="option" value="C"> C. ${q.option_c}</label>
            <label><input type="radio" name="option" value="D"> D. ${q.option_d}</label>
        `;
        if (userAnswers[q.id]) {
            const sel = optionsContainer.querySelector(`input[value="${userAnswers[q.id]}"]`);
            if (sel) sel.checked = true;
        }
        optionsContainer.querySelectorAll("input[name='option']").forEach(r=> {
            r.addEventListener("change", e => {
                userAnswers[q.id] = e.target.value;
            });
        });
        updateNav();
    }

    async function gotoIndex(index) {
        if (index < 0 || index >= totalQuestions) return;
        currentIndex = index;
        renderQuestion(currentIndex);
    }

    nextBtn.addEventListener("click", async () => {
        if (currentIndex === totalQuestions - 1) {
            await submitExamAndRedirect();
        } else {
            gotoIndex(currentIndex + 1);
        }
    });

    if (prevBtn) prevBtn.addEventListener("click", ()=> gotoIndex(currentIndex - 1));

    async function submitExamAndRedirect() {
        const answers = questionCache.map(q => ({
            question_id: q.id,
            selected_option: userAnswers[q.id] || null
        }));

        const res = await postJSON("Backend/Process/submit_exam.php", {
            lesson_id,
            subject_id,
            answers
        });
        if (res.status) {
            window.location.href = "FinalResults.php";
        } else {
            Swal.fire("Error", res.message || "Failed to submit exam", "error");
        }
    }

    await loadQuestions();
});

// TIMER function
function startTimer(seconds, timerElement) {
    let totalSeconds = Number(seconds) || 0;
    if (!timerElement) return;
    timerElement.textContent = formatTime(totalSeconds);

    timerInterval = setInterval(() => {
        totalSeconds--;
        timerElement.textContent = formatTime(totalSeconds);

        if (totalSeconds <= 0) {
            clearInterval(timerInterval);

            document.querySelectorAll("input, button, select, textarea").forEach(el=>{
                el.disabled = true;
            });

            // Wait for user click OK
            Swal.fire({
                title: "⏰ Time’s Up!",
                text: "Your exam time is over. Click OK to submit your answers.",
                icon: "info",
                allowOutsideClick: false,
                confirmButtonText: "OK"
            }).then(async () => {
                const safeAnswers = questionCache.map(q => ({
                    question_id: q.id,
                    selected_option: userAnswers[q.id] || null
                }));

                try {
                    const res = await postJSON("Backend/Process/submit_exam.php", {
                        answers: safeAnswers
                    });
                    if (res.status) {
                        window.location.href = "FinalResults.php";
                    } else {
                        Swal.fire("Error", res.message || "Failed to submit exam", "error");
                    }
                } catch (e) {
                    Swal.fire("Error", "Unexpected error submitting exam", "error");
                }
            });
        }
    }, 1000);
}
