<script>
    let mainDentPaintRowCount = 1;

    function updateTotalDentAjaxNetAmount() {
        let total = 0;
        document.querySelectorAll(".dentNetAmount").forEach(input => {
            total += parseFloat(input.value) || 0;
        });
        const totalField = document.getElementById("totalDentAjax");
        if (totalField) {
            totalField.value = total.toFixed(2);
        }
        if (typeof updateFinalDentBillTotal === "function") {
            updateFinalDentBillTotal();
        }
    }

    function addListenersToDentPaintRow(row) {
        // Delete button logic
        row.querySelector(".deleteMainDentPaintRow").addEventListener("click", function() {
            if (document.querySelectorAll(".mainDentPaintRow").length > 1) {
                row.remove();
                mainDentPaintRowCount--;
                updateTotalDentAjaxNetAmount();
            } else {
                alert("At least one row is required!");
            }
        });

        // Bind AJAX search for this row
        const searchInput = row.querySelector(".dentTypeSearch");
        const resultContainer = row.querySelector(".dentSearchResults");
        if (searchInput && resultContainer) {
            bindDentSearch(searchInput, resultContainer);
        }
    }

    document.addEventListener("DOMContentLoaded", function() {
        const container = document.getElementById("mainDentPaintContainer");
        const addBtn = document.getElementById("addMainDentPaintRow");

        if (!window.mainDentPaintHandlerAttached) {
            window.mainDentPaintHandlerAttached = true;

            const initialRow = container.querySelector(".mainDentPaintRow");
            if (initialRow) {
                addListenersToDentPaintRow(initialRow);
            }

            addBtn.addEventListener("click", function() {
                if (mainDentPaintRowCount < 100) {
                    const firstRow = container.querySelector(".mainDentPaintRow");
                    const newRow = firstRow.cloneNode(true);

                    // Reset inputs
                    newRow.querySelectorAll("input").forEach(input => {
                        input.value = input.type === "text" ? "" : "0";
                    });

                    // Clear search results box on new row
                    const resultBox = newRow.querySelector(".dentSearchResults");
                    if (resultBox) {
                        resultBox.innerHTML = "";
                        resultBox.style.display = "none";
                    }

                    container.appendChild(newRow);
                    addListenersToDentPaintRow(newRow);
                    mainDentPaintRowCount++;
                } else {
                    alert("Maximum of 100 rows allowed.");
                }
            });
        }
    });
</script>