jQuery(document).ready(function ($) {
  // Handle the "Print Marksheet" button click
  $("#printMarksheet").on("click", function () {
    window.print();
  });

  // Handle the "Download Marksheet" button click
  $("#downloadMarksheet").on("click", function () {
    /**
     * A robust function to convert the two-header-row table to a clean CSV string.
     * It replicates the visual structure of the HTML table headers by correctly
     * handling both rowspan and colspan.
     * @param {jQuery} table The jQuery object for the marksheet table.
     * @returns {string} The CSV content.
     */
    function tableToCsv(table) {
      const csvRows = [];

      // --- HEADER PROCESSING ---
      const mainHeaderRowData = [];
      const mainHeaderRow = table.find("thead tr:first-child");
      const subHeaderRow = table.find("thead tr:last-child");

      // Only include visible header cells so hidden subjects stay out of the CSV
      const visibleMainHeaderCells = mainHeaderRow.find("th:visible");

      visibleMainHeaderCells.each(function () {
        const cellText = $(this).text();
        const colspan = parseInt($(this).attr("colspan")) || 1;

        mainHeaderRowData.push(quoteCell(cellText));

        // If a cell has a colspan, add empty "filler" cells to its row
        // in the CSV so the columns align correctly.
        for (let i = 1; i < colspan; i++) {
          mainHeaderRowData.push("");
        }
      });
      csvRows.push(mainHeaderRowData.join(","));

      const simplerSubHeaderRowData = [];
      const visibleSubHeaderCells = subHeaderRow.find("th:visible");
      let subHeaderIndex = 0;

      visibleMainHeaderCells.each(function () {
        const rowspan = parseInt($(this).attr("rowspan")) || 1;
        const colspan = parseInt($(this).attr("colspan")) || 1;

        if (rowspan > 1) {
          // For cells like "Roll No." and "Name"
          simplerSubHeaderRowData.push("");
        } else {
          // For subject headers that have sub-headers
          for (let i = 0; i < colspan; i++) {
            const subHeaderCell = visibleSubHeaderCells.eq(subHeaderIndex);
            simplerSubHeaderRowData.push(
              quoteCell(subHeaderCell.text())
            );
            subHeaderIndex++;
          }
        }
      });

      csvRows.push(simplerSubHeaderRowData.join(","));

      // --- BODY PROCESSING ---
      table.find("tbody tr").each(function () {
        const row = [];
        $(this)
          .find("td:visible")
          .each(function () {
            row.push(quoteCell($(this).text()));
          });
        csvRows.push(row.join(","));
      });

      return csvRows.join("\n");
    }

    /**
     * Helper function to correctly quote cell content for CSV.
     */
    function quoteCell(text) {
      text = text.trim();
      return `"${text.replace(/"/g, '""')}"`;
    }

    // --- Main execution ---
    const table = $(".marksheet-table");
    if (table.length === 0) {
      alert("Error: Could not find the marksheet table to download.");
      return;
    }

    const csvContent = tableToCsv(table);
    const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
    const link = document.createElement("a");

    if (link.download !== undefined) {
      const url = URL.createObjectURL(blob);
      const className =
        $(".marksheet-container h3")
          .text()
          .replace("Marksheet for Class: ", "")
          .trim() || "Class";
      const examName =
        $(".marksheet-container h4").text().replace("Exam: ", "").trim() ||
        "Exam";
      const filename = `Marksheet-${className}-${examName}.csv`;

      link.setAttribute("href", url);
      link.setAttribute("download", filename);
      link.style.visibility = "hidden";

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  });
});
