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

    $("body").on("change", ".type", showbank);

    $(".showcashbank").hide();

    showbank();

    function showbank() {
        var type = $(".type").val();

        if (type == "U") {
            $(".showcashbank").show();
            $(".bankname").prop("required", true);
        } else {
            $(".showcashbank").hide();
            $(".bankname").prop("required", false).val("").trigger("change");

        }

    }

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

        if (itemname != '') {

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

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

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

    $("body").on("blur", ".rate", 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,
            rate = parseFloat(tr.find(".rate").val()) || 0,
            totqtyField = tr.find(".totqty");

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

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

        var amount = (parseFloat(totqtyField.val()) || 0) * rate;
        tr.find(".amount").val(amount);

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

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

        $(".subtotal").val(subtotal);

        var addpack = parseFloat($(".addpack").val()) || 0;
        var netamt = subtotal + addpack;

        $(".netamt").val(netamt);

    }

    $('#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('salenew_add.php', { ctr: ctr, hide: hide_check, prodtype: prodtype }, function (data) {
            $(data).appendTo('.tbody');

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

});