document.addEventListener("DOMContentLoaded", () => {

  document.getElementById("category").addEventListener("change", loadCourses);
  document.getElementById("course").addEventListener("change", loadSubjects);
  document.getElementById("subject").addEventListener("change", loadLessons);
});

// Load all categories
async function loadCategories() {
  const res = await fetch("Backend/Process/LoadCategories.php");
  const data = await res.json();
  fillDropdown("category", data.data, "Select Category...");
}

// Load courses by category
async function loadCourses() {
  const id = document.getElementById("category").value;
  const res = await fetch("Backend/Process/LoadCourses.php?category_id=" + id);
  const data = await res.json();
  fillDropdown("course", data.data, "Select Course...");
  fillDropdown("subject", [], "Select Subject...");
  fillDropdown("lesson", [], "Select Lesson...");
}

// Load subjects by course
async function loadSubjects() {
  const id = document.getElementById("course").value;
  const res = await fetch("Backend/Process/LoadSubjects.php?course_id=" + id);
  const data = await res.json();
  fillDropdown("subject", data.data, "Select Subject...");
  fillDropdown("lesson", [], "Select Lesson...");
}

// Load lessons by subject
async function loadLessons() {
  const id = document.getElementById("subject").value;
  const res = await fetch("Backend/Process/LoadLessons.php?subject_id=" + id);
  const data = await res.json();
  fillDropdown("lesson", data.data, "Select Lesson...");
  // Reset quiz count when lesson changes
  updateQuizCount(0);
  
  // Add event listener to lesson dropdown to update count when lesson is selected
  const lessonSelect = document.getElementById("lesson");
  if (lessonSelect) {
    // Remove old listener if exists and add new one
    const newLessonSelect = lessonSelect.cloneNode(true);
    lessonSelect.parentNode.replaceChild(newLessonSelect, lessonSelect);
    newLessonSelect.addEventListener("change", () => {
      const selectedLesson = newLessonSelect.value;
      if (selectedLesson && selectedLesson !== "0") {
        updateQuizCountForSelectedLesson(selectedLesson);
      } else {
        updateQuizCount(0);
      }
    });
  }
}

// Reusable dropdown filler
function fillDropdown(id, items, defaultText) {
  const select = document.getElementById(id);
  select.innerHTML = `<option value="">${defaultText}</option>`;
  items.forEach(item => {
    select.innerHTML += `<option value="${item.id}">${item.title}</option>`;
  });
}


async function add() {
  const lesson = document.getElementById("lesson").value;
  const question = document.getElementById("question").value;
  const option_A = document.getElementById("option_A").value;
  const option_B = document.getElementById("option_B").value;
  const option_C = document.getElementById("option_C").value;
  const option_D = document.getElementById("option_D").value;
  const medium = document.getElementById("medium").value;
  const answer = document.getElementById("answer").value;

  const quiz_number = document.getElementById("quiz_number").value;

  const updateBtn = document.getElementById("updateBtn");
  const addBtn = document.getElementById("addBtn");

  const quizData = {
    lesson: lesson,
    question: question,
    option_A: option_A,
    option_B: option_B,
    option_C: option_C,
    option_D: option_D,
    medium: medium,
    answer: answer,
    quiz_number: quiz_number
  };

  const quizJSON = JSON.stringify(quizData);

  const response = await fetch(
    "Backend/Process/AddQuizProcess.php", {
    method: "POST",
    body: quizJSON,
    headers: {
      "Content-type": "application/json"
    }
  }
  );

  if (response.ok) {
    const json = await response.json();
    console.log(json);

    if (json.status) {
      alert(json.message);
      clearFields();
      document.getElementById("medium1").selectedIndex = 0;
      document.getElementById("quiz_number").innerHTML = '<option value="0" selected>Select Quiz</option>';
      updateBtn.classList.remove("d-block");
      updateBtn.classList.add("d-none");

      addBtn.classList.remove("d-none");
      addBtn.classList.add("d-block");
      
      // Update quiz count after adding
      updateQuizCountForLesson();

    } else {
      alert(json.message);
    }

  } else {
    alert("something went wrong")
  }

}

function clearFields() {
  document.getElementById("question").value = "";
  document.getElementById("option_A").value = "";
  document.getElementById("option_B").value = "";
  document.getElementById("option_C").value = "";
  document.getElementById("option_D").value = "";
  document.getElementById("medium").value = 0;
  document.getElementById("answer").value = 0;
  document.getElementById("medium1").selectedIndex = 0;
  document.getElementById("quiz_number").innerHTML = '<option value="0" selected>Select Quiz</option>';
}

// Clear all quiz registration fields including dropdowns
function clearQuizFields() {
  // Clear dropdowns
  document.getElementById("category").selectedIndex = 0;
  fillDropdown("course", [], "Select Course...");
  fillDropdown("subject", [], "Select Subject...");
  fillDropdown("lesson", [], "Select Lesson...");
  
  // Clear quiz form fields
  clearFields();
  
  // Reset buttons
  const updateBtn = document.getElementById("updateBtn");
  const addBtn = document.getElementById("addBtn");
  if (updateBtn && addBtn) {
    updateBtn.classList.remove("d-block");
    updateBtn.classList.add("d-none");
    addBtn.classList.remove("d-none");
    addBtn.classList.add("d-block");
  }
  
  // Reset quiz count
  updateQuizCount(0);
}

document.addEventListener("DOMContentLoaded", () => {

  // For quiz loading section - update count when medium changes
  const medium1Select = document.getElementById("medium1");
  if (medium1Select) {
    medium1Select.addEventListener("change", () => {
      loadQuizNUmbers();
      updateQuizCountForLesson();
    });
  }
  
  // Use event delegation for lesson dropdown in quiz loading section
  document.addEventListener("change", (e) => {
    if (e.target && e.target.id === "lesson") {
      // Check if medium1 is selected - if yes, use filtered count, else use total count
      const medium1 = document.getElementById("medium1")?.value;
      if (medium1 && medium1 !== "0") {
        updateQuizCountForLesson();
      } else {
        const lessonId = e.target.value;
        if (lessonId && lessonId !== "0") {
          updateQuizCountForSelectedLesson(lessonId);
        } else {
          updateQuizCount(0);
        }
      }
    }
  });

});

async function loadQuizNUmbers() {
  const lesson = document.getElementById("lesson").value;
  const medium1 = document.getElementById("medium1").value;

  const filterData = {
    lesson: lesson,
    medium1: medium1
  };

  const filterJSON = JSON.stringify(filterData);

  const response = await fetch(
    "Backend/Process/filterQuiz.php", {
    method: "POST",
    body: filterJSON,
    headers: {
      "Content-type": "application/json"
    }
  }
  );

  if (response.ok) {
    const json = await response.json();
    console.log(json);

    if (json.status) {
      fillDropdown1("quiz_number", json.data, "Select Quiz");
      // Update quiz count
      updateQuizCount(json.data ? json.data.length : 0);
    } else {
      alert(json.message);
      updateQuizCount(0);
    }

  } else {
    alert("something went wrong");
    updateQuizCount(0);
  }

}

// Update quiz count badge
function updateQuizCount(count) {
  const badge = document.getElementById("quizCountBadge");
  if (badge) {
    badge.textContent = count || 0;
  }
}

// Load and update quiz count for selected lesson and medium (for quiz loading section)
async function updateQuizCountForLesson() {
  const lesson = document.getElementById("lesson").value;
  const medium1 = document.getElementById("medium1").value;

  if (!lesson || lesson === "0" || !medium1 || medium1 === "0") {
    updateQuizCount(0);
    return;
  }

  const filterData = {
    lesson: lesson,
    medium1: medium1
  };

  const filterJSON = JSON.stringify(filterData);

  try {
    const response = await fetch(
      "Backend/Process/filterQuiz.php", {
      method: "POST",
      body: filterJSON,
      headers: {
        "Content-type": "application/json"
      }
    }
    );

    if (response.ok) {
      const json = await response.json();
      if (json.status && json.data) {
        updateQuizCount(json.data.length);
      } else {
        updateQuizCount(0);
      }
    } else {
      updateQuizCount(0);
    }
  } catch (err) {
    console.error("Error loading quiz count:", err);
    updateQuizCount(0);
  }
}

// Update quiz count for selected lesson only (for lesson selection section)
async function updateQuizCountForSelectedLesson(lessonId) {
  if (!lessonId || lessonId === "0") {
    updateQuizCount(0);
    return;
  }

  try {
    // Count all quizzes for this lesson (across all mediums)
    const response = await fetch(
      "Backend/Process/GetQuizCountByLesson.php", {
      method: "POST",
      body: JSON.stringify({ lesson_id: lessonId }),
      headers: {
        "Content-type": "application/json"
      }
    }
    );

    if (response.ok) {
      const json = await response.json();
      if (json.status) {
        updateQuizCount(json.count || 0);
      } else {
        updateQuizCount(0);
      }
    } else {
      updateQuizCount(0);
    }
  } catch (err) {
    console.error("Error loading quiz count for lesson:", err);
    updateQuizCount(0);
  }
}

function fillDropdown1(id, items, defaultText) {
  const select = document.getElementById(id);
  let options = `<option value="">${defaultText}</option>`;
  items.forEach(item => {
    options += `<option value="${item.question_number}">${item.question_number}</option>`;
  });
  select.innerHTML = options;
}

document.addEventListener("DOMContentLoaded", () => {

  document.getElementById("quiz_number").addEventListener("change", loadMcq);

});

async function loadMcq() {
  const lesson = document.getElementById("lesson").value;
  const medium1 = document.getElementById("medium1").value;
  const quiz_number = document.getElementById("quiz_number").value;

  const question = document.getElementById("question");
  const option_A = document.getElementById("option_A");
  const option_B = document.getElementById("option_B");
  const option_C = document.getElementById("option_C");
  const option_D = document.getElementById("option_D");
  const medium = document.getElementById("medium");
  const answer = document.getElementById("answer");

  const updateBtn = document.getElementById("updateBtn");
  const addBtn = document.getElementById("addBtn");


  console.log(lesson);
  console.log(medium1);
  console.log(quiz_number);

  const mcqData = {
    lesson: lesson,
    medium1: medium1,
    quiz_number: quiz_number
  };

  const mcqJSON = JSON.stringify(mcqData);

  const response = await fetch(
    "Backend/Process/LoadMcqProcess.php", {
    method: "POST",
    body: mcqJSON,
    headers: {
      "Content-type": "application/json"
    }
  }
  );

  if (response.ok) {
    const json = await response.json();
    console.log(json);

    if (json.status) {
      question.value = json.data.question;
      option_A.value = json.data.option_a;
      option_B.value = json.data.option_b;
      option_C.value = json.data.option_c;
      option_D.value = json.data.option_d;
      medium.value = json.data.medium_id;
      answer.value = json.data.correct_option ?? "";

      updateBtn.classList.remove("d-none");
      updateBtn.classList.add("d-block");

      addBtn.classList.remove("d-block");
      addBtn.classList.add("d-none");

    } else {
      alert(json.message);
    }

  } else {
    alert("something went wrong")
  }

}

async function deleteQuiz() {
  const lesson = document.getElementById("lesson").value;
  const medium1 = document.getElementById("medium1").value;
  const quiz_number = document.getElementById("quiz_number").value;

  console.log(lesson);
  console.log(medium1);

  const deleteData = {
    lesson: lesson,
    medium1: medium1,
    quiz_number: quiz_number
  };

  const deleteJSON = JSON.stringify(deleteData);

  const response = await fetch(
    "Backend/Process/DeleteQuizProcess.php", {
    method: "POST",
    body: deleteJSON,
    headers: {
      "Content-type": "application/json"
    }
  }
  );

  if (response.ok) {
    const json = await response.json();
    console.log(json);

    if (json.status) {
      alert(json.message);
      clearFields();
      loadQuizNUmbers();

      document.getElementById("medium1").selectedIndex = 0;

      const updateBtn = document.getElementById("updateBtn");
      const addBtn = document.getElementById("addBtn");
      if (updateBtn && addBtn) {
        updateBtn.classList.remove("d-block");
        updateBtn.classList.add("d-none");

        addBtn.classList.remove("d-none");
        addBtn.classList.add("d-block");
      }
      
      // Update quiz count after deleting
      updateQuizCountForLesson();

    } else {
      alert(json.message);
    }

  } else {
    alert("something went wrong")
  }

}