document.addEventListener("DOMContentLoaded", function () {
  const yearDropdown = document.getElementById("year");
  const errorDiv = document.getElementById("yearError");

  // Get the form dynamically
  const form = document.querySelector("form"); // get from id as table name

  // Dynamic table name = form id
  const tableName = form.id.toLowerCase();

  const currentYear = new Date().getFullYear();
  const startYear = 1990;

  // Fill Year dropdown
  for (let y = currentYear; y >= startYear; y--) {
    let nextYear = y + 1;

    let option = document.createElement("option");
    option.value = y;
    option.textContent = `AY ${y}-${nextYear}`;

    yearDropdown.appendChild(option);
  }

  // Validate selected year
  yearDropdown.addEventListener("change", function () {
    let selectedYear = parseInt(this.value);

    fetch("/check_year", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        table: tableName,  // dynamic table name
        year: selectedYear
      })
    })
      .then(res => res.json())
      .then(data => {
        if (data.exists) {
          errorDiv.style.display = "block";
          errorDiv.innerText = `Year ${selectedYear}-${selectedYear + 1} already exists!`;

          // Block submission
          form.onsubmit = function () { return false; };
        } else {
          errorDiv.style.display = "none";
          form.onsubmit = null; // Allow submit
        }
      });
  });
});

