$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
    $(".tbody").on("keyup change blur focus", ".qty, .rate, .totqty", calDetail);
    $("body").on("blur ", ".itemname", CreateProd);
    $("body").on("blur ", ".itemname", getMsp);
    $("body").on("blur", ".mprodname", checkmprodname);

    var currentRow = null;
    // when opening modal
    $("body").on("click", ".itemname", function () {
        currentRow = $(this).closest("tr");
    });

    $("body").on("click", ".saveent", saveProduct);

    function saveProduct() {
        // Show loading animation
        var tr = $(this).closest("tr");

        $("#loadingIndicator").show();

        var mprodname = $(".mprodname").val(),
            mcost = $(".mcost").val(),
            mrate = $(".mrate").val(),
            mloosepairs = $(".mloosepairs").is(":checked") ? 1 : 0;

        if (mprodname == "") {
            alert("Product Cannot Be Empty");
            $("#loadingIndicator").hide();
            return;
        }

        $.post("saveProduct.php", {
            mprodname: mprodname,
            mcost: mcost,
            mrate: mrate,
            mloosepairs: mloosepairs
        }, function (data) {
            // Hide loading animation
            $("#loadingIndicator").hide();

            if (data != "") {
                alert("Product Created.");

                // fill values
                currentRow.find(".itemname").val(data);

                $(".PurchCreateModal").modal("hide");

                // trigger your existing barcode fetch logic
                setTimeout(function () {
                    currentRow.find(".itemname").focus();
                }, 300);

                // clear modal fields
                $(".mprodname").val('');
                $(".mcost").val('');
                $(".mrate").val('');
                $(".mloosepairs").prop("checked", false);
            } else {
                alert("Failed to Create Product.");
            }
        }).fail(function () {
            $("#loadingIndicator").hide();
            alert("Error occurred during saving.");
        });
    }

    function checkmprodname() {
        var prodname = $('.mprodname').val();
        if (prodname) {
            $.get('check_prodModal.php', { prodname: prodname }, function (data) {
                if (parseFloat(data) > 0) {
                    $('.mprodname').val("");
                    $('.mprodname').focus();
                    alert("Product Name Already Exist");
                }
            });
        }
    }

    function CreateProd() {
        var tr = $(this).closest("tr"),
            item = tr.find(".itemname").val().toUpperCase(); // convert to uppercase

        if (item === 'NEW') { // match uppercase 'NEW'
            $(".PurchCreateModal").modal("show");
            $('.PurchCreateModal').on('shown.bs.modal', function () {
                $('.mprodname').focus(); // replace with your class or ID
            });

        }
    }


    function getMsp() {
        var tr = $(this).closest("tr"),
            itemname = tr.find(".itemname").val(),
            data = { itemname: itemname };

        if (itemname != '') {

            $.ajax({
                type: 'GET',
                dataType: 'json',
                url: "getItemMspName.php?m=a",
                data: data,
                success: function (response) {
                    var m = response;

                    tr.find(".rate").val(m.rate);
                    tr.find(".cartqty").val(m.cartqty);
                    tr.find(".cost").val(m.cost);
                    tr.find(".loosepairs").val(m.loosepairs);

                }
            });
        } else {
            tr.find(".rate").val("0");
            tr.find(".cartqty").val("0");
            tr.find(".amount").val("0");
            tr.find(".cost").val("0");
        }
    }

    $("body").on("blur", ".totqty", function () {
        let $row = $(this).closest("tr");
        let $tbody = $row.closest("tbody");

        // Check if current row is last row
        let isLastRow = $row[0] === $tbody.find("tr:last")[0];

        // Check if qty has value (avoid empty row triggering)
        let hasValue = $.trim($(this).val()) !== "0";

        // Prevent duplicate: check if row already processed
        let alreadyAdded = $row.data("row-added") === true;

        if (isLastRow && hasValue && !alreadyAdded) {
            AddRows();

            // mark this row so it won't trigger again
            $row.data("row-added", true);
        }
    });

    function calDetail() {
        var tr = $(this).closest("tr"),
            cartqty = parseFloat(tr.find(".cartqty").val()) || 0,
            loosepairs = tr.find(".loosepairs").val(),
            qty = parseFloat(tr.find(".qty").val()) || 0,
            totqtyField = tr.find(".totqty");

        if (loosepairs != 1) {
            var totqty = cartqty * qty;

            totqtyField
                .val(totqty)
                .prop("readonly", true)
                .attr("tabindex", "-1");
        } else {
            totqtyField
                .prop("readonly", false)
                .removeAttr("tabindex");
        }

        var totalqty = 0;
        $(".totqty").each(function () {
            if (!isNaN(this.value) && this.value.length !== 0) {
                totalqty += parseFloat(this.value);
            }
        });

        $(".totalqty").val(totalqty);
    }

    $('#addnew').click(function () {
        AddRows();
        //        caltran();
    });
    function remove() {
        $(this).closest("tr").remove();
        //        caltran();
    }


    function AddRows() {
        var ctr = $('#items').val();
        var prodtype = $('.prodtype').val();
        var hide_check = "";
        if ($("#del_all").prop("checked")) {
            hide_check = 0;
        } else {
            hide_check = 1;
        }
        //        var detail = ".fetchpart_" + ctr;
        var focusFld = ".focusFld_" + ctr;
        ctr++;
        $('#items').val(ctr);
        $.post('inward_add.php', { ctr: ctr, hide: hide_check, prodtype: prodtype }, function (data) {
            $(data).appendTo('.tbody');

            //            $(detail).select2();
            $(focusFld).focus();
            //            caltran();
        });
    }




});