<script>
function bindLubricantSearch(searchInput, resultContainer) {
    searchInput.addEventListener("input", function () {
        let query = searchInput.value.trim();
        if (query.length > 0) {
            fetch(`./php/fetchLubricant.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(lubricant => {
                        let div = document.createElement("div");
                        div.textContent = lubricant.lubricantType;
                        div.dataset.lubricantID = lubricant.lubricantID;
                        div.dataset.lubricantCharge = lubricant.lubricantCharge;

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

                            let row = searchInput.closest(".row");
                            let quantityField = row.querySelector(".lubricantQuantity");
                            let totalPriceField = row.querySelector(".lubricantTotal");
                            let netAmountField = row.querySelector(".lubricantNetAmount");
                            let discountField = row.querySelector(".lubricantDiscount");

                            quantityField.value = 1;
                            totalPriceField.value = parseFloat(lubricant.lubricantCharge).toFixed(2);

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

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

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

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

                            updateNetAmount();
                        });

                        resultContainer.appendChild(div);
                    });
                })
                .catch(error => console.error("Error fetching lubricant 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 bindings
document.addEventListener("DOMContentLoaded", function () {
    document.querySelectorAll(".mainlubricantRow").forEach(row => {
        const searchInput = row.querySelector(".lubricantSearch");
        const resultContainer = row.querySelector(".lubricantSearchResults");
        if (searchInput && resultContainer) {
            bindLubricantSearch(searchInput, resultContainer);
        }
    });
});

// Total calculation function remains the same
function updateTotalLubricantAjaxNetAmount() {
	let total = 0;
	document.querySelectorAll(".lubricantNetAmount").forEach(input => {
		total += parseFloat(input.value) || 0;
	});
	document.getElementById("totalLubricantAjax").value = total.toFixed(2);

	// If you have another function to update grand total:
	if (typeof updateFinalLubricantBillTotal === "function") {
		updateFinalLubricantBillTotal();
	}
}
</script>