/* =====================================================
   GLOBAL STATE
===================================================== */
let addedYears = [];

/* =====================================================
   INITIALIZE YEARS FROM DATABASE HEADERS
===================================================== */
document.addEventListener("DOMContentLoaded", () => {
    const headers = document.querySelectorAll("#tableHeader th");

    headers.forEach(th => {
        if (th.innerText.startsWith("Utilized")) {
            const year = th.innerText.replace("Utilized", "").trim();
            if (!addedYears.includes(year)) {
                addedYears.push(year);
            }
        }
    });
});

/* =====================================================
   ADD YEAR COLUMN (DYNAMIC)
===================================================== */
function addYearColumn() {
    const yearSelect = document.getElementById("yearSelect");
    const year = yearSelect.value;

    if (!year) {
        alert("Please select AY");
        return;
    }

    if (addedYears.includes(year)) {
        alert("This AY is already added");
        return;
    }

    addedYears.push(year);

    // Add header column
    const headerRow = document.getElementById("tableHeader");
    const th = document.createElement("th");
    th.innerText = "Utilized " + year;

    // Insert before Balance column
    headerRow.insertBefore(th, headerRow.children[headerRow.children.length - 2]);

    // Add input cells to all existing rows
    document.querySelectorAll("#matTable tbody tr").forEach(tr => {
        const td = document.createElement("td");
        td.innerHTML = `<input type="number">`;
        tr.insertBefore(td, tr.children[tr.children.length - 2]);
    });
}

/* =====================================================
   ADD NEW ROW
===================================================== */
function addRow() {
    const tbody = document.querySelector("#matTable tbody");
    const tr = document.createElement("tr");

    let utilizedCols = "";
    addedYears.forEach(() => {
        utilizedCols += `<td><input type="number"></td>`;
    });

    tr.innerHTML = `
        <td contenteditable="true"></td>
        <td><input></td>
        ${utilizedCols}
        <td><input></td>
        <td>
            <button onclick="saveRow(this)">Save</button>
        </td>
    `;

    tbody.appendChild(tr);
}

/* =====================================================
   SAVE SINGLE ROW
===================================================== */
function saveRow(btn) {
    const tr = btn.closest("tr");
    const inputs = tr.querySelectorAll("input");

    const financialYear = tr.children[0].innerText.trim();

    if (!financialYear) {
        alert("AY is required");
        return;
    }

    let payload = {
        financial_year: financialYear,
        mat_credit: inputs[0].value || 0,
        balance: inputs[inputs.length - 1].value || 0,
        utilization: []
    };

    addedYears.forEach((year, i) => {
        const value = inputs[i + 1].value;
        if (value) {
            payload.utilization.push({
                year: year,
                amount: value
            });
        }
    });

    fetch("/save_mat_row", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
    })
        .then(res => res.json().then(j => ({ ok: res.ok, data: j })))
        .then(res => {
            if (res.ok) {
                alert("✅ " + res.data.message);
            } else {
                alert("⚠️ " + res.data.error);
            }
        })
        .catch(() => {
            alert("Server error");
        });
}

/* =====================================================
   SAVE ALL ROWS
===================================================== */
function saveAll() {
    let rows = [];

    document.querySelectorAll("#matTable tbody tr").forEach(tr => {
        const inputs = tr.querySelectorAll("input");
        const financialYear = tr.children[0].innerText.trim();

        if (!financialYear) return;

        let row = {
            financial_year: financialYear,
            mat_credit: inputs[0].value || 0,
            balance: inputs[inputs.length - 1].value || 0,
            utilization: []
        };

        addedYears.forEach((year, i) => {
            const value = inputs[i + 1].value;
            if (value) {
                row.utilization.push({
                    year: year,
                    amount: value
                });
            }
        });

        rows.push(row);
    });

    if (!rows.length) {
        alert("No data to save");
        return;
    }

    fetch("/save_mat_all", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(rows)
    })
        .then(res => res.json())
        .then(res => {
            let msg = "✅ " + res.message;
            if (res.skipped && res.skipped.length) {
                msg += "\n\nSkipped AY:\n" + res.skipped.join(", ");
            }
            alert(msg);
        })
        .catch(() => {
            alert("Server error");
        });
}
