<script>
    function bindSpareSearch(searchInput, resultContainer) {
        searchInput.addEventListener("input", function() {
            let query = searchInput.value.trim();
            if (query.length > 0) {
                fetch(`./php/fetchSpareParts.php?query=${query}`)
                    .then(response => response.json())
                    .then(data => {
                        resultContainer.innerHTML = "";
                        resultContainer.style.display = "block";

                        if (data.length === 0) {
                            resultContainer.innerHTML = "<div>No matching records found</div>";
                        }

                        data.forEach(spare => {
                            let div = document.createElement("div");
                            div.textContent = spare.spareType;
                            div.dataset.spareID = spare.spareID;
                            div.dataset.spareCharge = spare.spareCharge;

                            div.addEventListener("click", function() {
                                searchInput.value = spare.spareType;
                                resultContainer.style.display = "none";

                                let row = searchInput.closest(".row");
                                let quantityField = row.querySelector(".spareQuantity");
                                let totalPriceField = row.querySelector(".spareTotal");
                                let netAmountField = row.querySelector(".spareNetAmount");
                                let discountField = row.querySelector(".spareDiscount");

                                quantityField.value = 1;
                                totalPriceField.value = parseFloat(spare.spareCharge).toFixed(2);

                                function updateNetAmount() {
                                    let quantity = parseFloat(quantityField.value) || 1;
                                    let unitPrice = parseFloat(spare.spareCharge) || 0;
                                    let discount = parseFloat(discountField.value) || 0;

                                    let totalBeforeDiscount = quantity * unitPrice;
                                    let netAmount = totalBeforeDiscount - (totalBeforeDiscount * discount / 100);

                                    netAmountField.value = netAmount.toFixed(2);
                                    updateTotalSpareAjaxNetAmount();
                                }

                                quantityField.addEventListener("input", updateNetAmount);
                                discountField.addEventListener("input", updateNetAmount);

                                updateNetAmount();
                            });

                            resultContainer.appendChild(div);
                        });
                    })
                    .catch(error => console.error("Error fetching spare details:", error));
            } else {
                resultContainer.style.display = "none";
            }
        });

        // Hide result box on outside click
        document.addEventListener("click", function(e) {
            if (!searchInput.contains(e.target) && !resultContainer.contains(e.target)) {
                resultContainer.style.display = "none";
            }
        });
    }

    // Initial binding on existing spare parts rows
    document.addEventListener("DOMContentLoaded", function() {
        document.querySelectorAll(".mainSparePartsRow").forEach(row => {
            const searchInput = row.querySelector(".sparePartsSearch");
            const resultContainer = row.querySelector(".spareSearchResults");
            if (searchInput && resultContainer) {
                bindSpareSearch(searchInput, resultContainer);
            }
        });
    });

    // Total Spare Net Amount Calculation
    function updateTotalSpareAjaxNetAmount() {
        let total = 0;
        document.querySelectorAll(".spareNetAmount").forEach(input => {
            total += parseFloat(input.value) || 0;
        });
        document.getElementById("totalSpareAjax").value = total.toFixed(2);

        if (typeof updateFinalBillTotal === "function") {
            updateFinalBillTotal();
        }
    }
</script>