<script>
    function bindLabourSearch(searchInput, resultContainer) {
        searchInput.addEventListener("input", function() {
            let query = searchInput.value.trim();
            if (query.length > 0) {
                fetch(`./php/fetchLabour.php?query=${encodeURIComponent(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>";
                            return;
                        }

                        data.forEach(labour => {
                            let div = document.createElement("div");
                            div.textContent = labour.labourCode;
                            div.dataset.labourID = labour.labourID;
                            div.dataset.labourCharge = labour.labourCharge;

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

                                const row = searchInput.closest(".row");
                                const quantityField = row.querySelector(".labourQuantity");
                                const totalPriceField = row.querySelector(".labourTotal");
                                const netAmountField = row.querySelector(".labourNetAmount");
                                const discountField = row.querySelector(".labourDiscount");

                                quantityField.value = 1;
                                totalPriceField.value = parseFloat(labour.labourCharge).toFixed(2);

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

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

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

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

                                updateNetAmount();
                            });

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

    // Add global click handler once to hide labour search results on outside click
    if (!window.labourSearchGlobalClickAdded) {
        window.labourSearchGlobalClickAdded = true;
        document.addEventListener("click", function(e) {
            document.querySelectorAll(".labourSearchResults").forEach(resultContainer => {
                const input = resultContainer.previousElementSibling;
                if (!resultContainer.contains(e.target) && !input.contains(e.target)) {
                    resultContainer.style.display = "none";
                }
            });
        });
    }

    function updateTotalLabourAjaxNetAmount() {
        let total = 0;
        document.querySelectorAll(".labourNetAmount").forEach(input => {
            total += parseFloat(input.value) || 0;
        });
        document.getElementById("totalLabourAjax").value = total.toFixed(2);

        // Call final update here
        updateFinalLabourBillTotal();
    }
</script>