$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
    $("body").on("keyup change blur focus", ".qty, .rate, .amount,.discperc,.discamt,.vatperc,.roundoff", calDetail);
    //    $("body").on("keyup change blur focus", ".ldiscperc, .tvatperc, .totdisc, .totadv,.addpack,.addgst", mainCal);
    //    $("body").on("focus blur change", ".vouchdt", getvoucher);
    //    $("body").on("change blur", ".cmbparty", getgst);
    $("body").on("blur", '.cost', autoaddrow);
    $("body").on("change", '.paidby', chgType);
    //    $("body").on("keydown", 'td', updown);

    $("body").on("change blur", ".party", chkOms);
    $("body").on("change blur", ".party, .invno", chkInv);
    $("body").on("change blur", '.item', getMsp);
    $("body").on("blur ", ".item", CreateProd);
    $("body").on("blur", ".mprodname", checkmprodname);

    $("body").on("change", ".mstate", getStateCode);


    $("#partyModal").on("shown.bs.modal", function () {
        $("#party_name").focus();
    });

    // Open modal
    $('#createPartyBtn').click(function () {
        $('#party_name').val('');
        $('#partyModal').modal('show');
    });

    // Save party
    $('#saveParty').click(function () {

        var pname = $('#party_name').val().trim();
        var mstate = $('.mstate').val();
        var mstatecode = $('.mstatecode').val();
        var party_gstno = $('.party_gstno').val();
        var mmobile = $('.mmobile').val();

        if (pname === '') {
            alert('Enter party name');
            $("#party_name").focus();

            return;
        }

        $.ajax({
            url: "createparty.php",
            type: "POST",
            dataType: "json",
            data: { name: pname, state: mstate, statecode: mstatecode, mobile: mmobile, gstno: party_gstno, group: '009' },
            success: function (res) {
                // 🔴 Party already exists
                if (res.status === "exists") {
                    alert("Party With Same Name Already Exists! In Supplier Or Customer Master");
                    $("#partyModal").modal("hide");

                    setTimeout(function () {
                        // open select2
                        $(".party").select2("open");

                        // wait till dropdown opens, then fill search
                        setTimeout(function () {
                            var searchInput = document.querySelector(
                                ".select2-container--open .select2-search__field",
                            );

                            if (searchInput) {
                                searchInput.value = res.name;
                                searchInput.dispatchEvent(
                                    new Event("input", { bubbles: true }),
                                );
                                searchInput.dispatchEvent(
                                    new KeyboardEvent("keydown", {
                                        key: "ArrowDown",
                                    }),
                                );

                            }
                        }, 50);
                    }, 300);

                    return;
                }

                // 🟢 New party created
                var option = new Option(res.name, res.accode, true, true);
                $(".party").append(option).val(res.accode).trigger("change");
                $("#partyModal").modal("hide");
            },

        });
    });

    function getStateCode() {
        var state = $(".mstate").val();
        $.get('get_stcode.php', { state: state }, function (data) {
            $(".mstatecode").val(data);
        });
    }

    var currentRow = null;
    // when opening modal
    $("body").on("click", ".item", 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(),
            mhsncode = $(".mhsncode").val(),
            mcost = $(".mcost").val(),
            mrate = $(".mrate").val(),
            mgstperc = $(".mgstperc").val();

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

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

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

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

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

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

                // clear modal fields
                $(".mbarcode").val('');
                $(".mprodname").val('');
                $(".PurchCreateModal .cost").val('');
            } 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(".item").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 chkInv() {
        var invno = $(".invno").val(),
            file = $(".file").val(),
            party = $(".party").val();
        $.post('chk_pur_invno.php', { invno: invno, party: party, file: file }, function (data) {
            if (data.s == 1) {
                alert('These Invoice Already Exist For Voucher  ' + data.vouchno);
                $(".invno").val('');
                $(".invno").focus();

            }
        }, 'json');
    }

    function chkOms() {
        var party = $(".party").val();
        $.post("chkoms.php", { party: party }, function (data) {
            $(".oms").val(data);
            if (data == 1) {
                $(".ofs").text("Out of State");
            } else {
                $(".ofs").text("In State");
            }
            getMsp();
        });
    }

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

        if (itemname != '') {

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

                    tr.find(".barcode").val(m.barcode);
                    tr.find(".mrp").val(m.mrp);
                    tr.find(".hsncode").val(m.hsncode);
                    //                    tr.find(".stkqty").val(m.stkqty);
                    if (addflg != 1) {
                        if (rate > 0) {
                            tr.find(".rate").val(rate);
                        } else {
                            tr.find(".rate").val(m.rate);
                            tr.find(".ratebfdisc").val(m.rate);
                        }
                    } else {
                        tr.find(".ratebfdisc").val(m.rate);
                    }
                    tr.find(".qty").val("0");
                    tr.find(".cost").val(m.cost);
                    if ($(".importent").prop("checked")) {
                        tr.find(".cgstrate").val("0");
                        tr.find(".sgstrate").val("0");
                        tr.find(".igstrate").val("0");
                    } else {

                        tr.find(".cgstrate").val(m.cgst);
                        tr.find(".sgstrate").val(m.sgst);
                        tr.find(".igstrate").val(m.igst);
                    }
                }
            });
        } else {
            tr.find(".rate").val("0");
            tr.find(".qty").val("0");
            tr.find(".amount").val("0");
            tr.find(".cost").val("0");
            tr.find(".cgstrate").val("0");
            tr.find(".sgstrate").val("0");
            tr.find(".igstrate").val("0");
        }
    }

    chgType();
    function chgType() {
        var paidby = $(".paidby").val();
        if (paidby == "C") {
            $(".totadv").attr("readonly", true);
            $(".totadv").val("0");
            //            mainCal();
        } else {
            $(".totadv").removeAttr("readonly", true);

        }
    }
  

    $("#submit").click(function () {
        $("#submit").hide();
    });

    $("form").submit(function () {

        var party = $('.party').val(),
            totbillamt = $('.totbillamt').val(),
            valid = true;


        if (party == '') {
            var message = "Party Cannot Be Empty";
            alert(message);
            $("#submit").show();

            return false;
            valid = false;
        }

        if (parseFloat(totbillamt) <= 0 || totbillamt == '') {
            var message = "Netamt Cannot zero";
            alert(message);
            $("#submit").show();

            return false;
            valid = false;
        }

        if (valid) {
            var isValid = true;

            if (isValid) {
                $("#submit").hide();
                $("#cancel").hide();

            }
        }
    });



    var canc_flag = $(".canc_flag").val();
    if (canc_flag != '') {
        $("#scancbill").hide();
        $("#hedit").hide();

    }


    //    $("#hdelete").hide();


    $("#cancbill").click(function () {
        $("#cancmodel").modal('show');
    });


    var lrno = $('.lrno').val();
    if (lrno != '') {
        $(".lrdetail").show();
    } else {
        $(".lrdetail").hide();
    }




    $(".lrtab").click(function () {
        $(".lrdetail").animate({
            height: 'toggle'
        });
    });

    function calDetail() {
        var tr = $(this).closest("tr"),
            qty = tr.find(".qty").val(),
            rate = tr.find(".cost").val(),
            discperc = tr.find(".discperc").val(),
            discamt = 0,
            subtot = 0,
            total = 0,
            vat = 0,
            cgst5 = 0,
            cgst12 = 0,
            cgst18 = 0,
            cgst28 = 0,
            igst5 = 0,
            igst12 = 0,
            igst18 = 0,
            igst28 = 0,
            cgst5a = 0,
            cgst12a = 0,
            cgst18a = 0,
            cgst28a = 0,
            igst5a = 0,
            igst12a = 0,
            igst18a = 0,
            igst28a = 0,
            totgst5 = 0,
            totgst12 = 0,
            totgst18 = 0,
            totgst28 = 0,
            totalgst = 0,
            totbillamt = 0,
            amount = (rate * qty).toFixed(2);

        if (discperc > 0) {
            discamt = ((discperc * amount) / 100).toFixed(2);
        } else {
            discamt = tr.find(".discamt").val();
        }
        subtot = amount - discamt;

        var taxval = subtot.toFixed(2);
        tr.find(".subtot").val(taxval);

        var cgstrate = tr.find('.cgstrate').val(),
            sgstrate = tr.find('.sgstrate').val(),
            igstrate = tr.find('.igstrate').val(),
            cgstamnt = parseFloat(taxval) * parseFloat(cgstrate) / 100,
            sgstamnt = parseFloat(taxval) * parseFloat(sgstrate) / 100,
            igstamnt = parseFloat(taxval) * parseFloat(igstrate) / 100,
            total = parseFloat(cgstamnt) + parseFloat(sgstamnt) + parseFloat(igstamnt) + parseFloat(taxval);
        //                rtotal = Math.round((total * 100) / 100);
        tr.find('.cgstamt').val(cgstamnt.toFixed(2));
        tr.find('.sgstamt').val(sgstamnt.toFixed(2));
        tr.find('.igstamt').val(igstamnt.toFixed(2));
        tr.find('.total').val(total.toFixed(2));


        tr.find(".amount").val(amount);
        tr.find(".discamt").val(discamt);
        tr.find(".vat").val(vat);
        $('.tbody').find('tr').each(function () {
            var row = $(this),
                amt = 0,
                qty = row.find('.qty').val(),
                rate = row.find('.cost').val(),
                discperc = row.find('.discperc').val();

            amt = rate * qty,
                row.find(".amount").val(amt);
            if (discperc > 0) {
                var actdisc = (discperc * amt) / 100,
                    rdisc2 = Math.round(actdisc * 100) / 100;
            } else {
                rdisc2 = row.find('.discamt').val();

            }
            row.find('.discamt').val(rdisc2);

            var taxval = parseFloat(amt) - parseFloat(rdisc2),
                rtaxval = Math.round(taxval * 100) / 100;
            row.find('.subtot').val(rtaxval);

            var cgstrate = row.find('.cgstrate').val(),
                sgstrate = row.find('.sgstrate').val(),
                igstrate = row.find('.igstrate').val(),
                cgstamnt = parseFloat(taxval) * parseFloat(cgstrate) / 100,
                sgstamnt = parseFloat(taxval) * parseFloat(sgstrate) / 100,
                igstamnt = parseFloat(taxval) * parseFloat(igstrate) / 100,
                total = parseFloat(cgstamnt) + parseFloat(sgstamnt) + parseFloat(igstamnt) + parseFloat(taxval),
                rtotal = Math.round((total * 100) / 100);
            row.find('.cgstamt').val(cgstamnt.toFixed(2));
            row.find('.sgstamt').val(sgstamnt.toFixed(2));
            row.find('.igstamt').val(igstamnt.toFixed(2));
            row.find('.total').val(rtotal);
            var crate = row.find('.cgstrate').val(),
                camt = row.find('.cgstamt').val(),
                irate = row.find('.igstrate').val(),
                iamt = row.find('.igstamt').val(),
                amount = (parseFloat(qty) * parseFloat(rate)).toFixed(2);

            row.find(".amount").val(amount);


            if (crate < 3) {
                cgst5a = parseFloat(camt);
                cgst5 += parseFloat(cgst5a);
                igst5a = 0;
            } else if (crate < 7) {
                cgst12a = parseFloat(camt);
                cgst12 += parseFloat(cgst12a);
                igst12a = 0;
            } else if (crate < 10) {
                cgst18a = parseFloat(camt);
                cgst18 += parseFloat(cgst18a);
                igst18a = 0;
            } else if (crate < 15) {
                cgst28a = parseFloat(camt);
                cgst28 += parseFloat(cgst28a);
                igst28a = 0;
            }

            if (irate < 7) {
                igst5a = parseFloat(iamt);
                igst5 += parseFloat(igst5a);
                cgst5a = 0;
            } else if (irate < 13) {
                igst12a = parseFloat(iamt);
                igst12 += parseFloat(igst12a);
                cgst12a = 0;
            } else if (irate < 19) {
                igst18a = parseFloat(iamt);
                igst18 += parseFloat(igst18a);
                cgst12a = 0;
            } else if (irate < 29) {
                igst28a = parseFloat(iamt);
                igst28 += parseFloat(igst28a);
                cgst28a = 0;
            }
            //            postperc = parseFloat(ipost) + parseFloat(opost);
            //
            //            $('.postperc').val(postperc);
        });

        var grosstot = 0,
            discamt = 0,
            totqty = 0,
            subtot = 0;



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

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

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

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

        var val2 = 0;
        $(".discamt").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                val2 += parseFloat(this.value);
            }
        });
        Math.round($(".litemdisc").val(val2));

        var val4 = 0;
        $(".subtot").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                val4 += parseFloat(this.value);
            }
        });
        Math.round($(".taxamt").val(val4));

        var vald = 0;
        $(".discount2").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                vald += parseFloat(this.value);
            }
        });
        Math.round($(".lesother").val(vald));


        var val5 = 0;
        $(".total").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                val5 += parseFloat(this.value);
            }
        });
        var roundoff = $(".roundoff").val(),
            finamt = parseFloat(val5) + parseFloat(roundoff);

        $(".netamt").val(finamt.toFixed(2));
        $(".totalamount").val(finamt.toFixed(2));

        totgst5 = parseFloat(cgst5) + parseFloat(cgst5) + parseFloat(igst5);
        totgst12 = parseFloat(cgst12) + parseFloat(cgst12) + parseFloat(igst12);
        totgst18 = parseFloat(cgst18) + parseFloat(cgst18) + parseFloat(igst18);
        totgst28 = parseFloat(cgst28) + parseFloat(cgst28) + parseFloat(igst28);
        totalgst = parseFloat(totgst5) + parseFloat(totgst12) + parseFloat(totgst18) + parseFloat(totgst28);
        $('.cgst5').val(cgst5.toFixed(2));
        $('.sgst5').val(cgst5.toFixed(2));
        $('.igst5').val(igst5.toFixed(2));

        $('.cgst12').val(cgst12.toFixed(2));
        $('.sgst12').val(cgst12.toFixed(2));
        $('.igst12').val(igst12.toFixed(2));



        $('.cgst18').val(cgst18.toFixed(2));
        $('.sgst18').val(cgst18.toFixed(2));
        $('.igst18').val(igst18.toFixed(2));

        $('.cgst28').val(cgst28.toFixed(2));
        $('.sgst28').val(cgst28.toFixed(2));
        $('.igst28').val(igst28.toFixed(2));

        $('.totgst5').val(totgst5.toFixed(2));
        $('.totgst12').val(totgst12.toFixed(2));
        $('.totgst18').val(totgst18.toFixed(2));
        $('.totgst28').val(totgst28.toFixed(2));

        $('.totalgst').val(totalgst.toFixed(2));
        getMsp();
        //        $(".tottotal").val(tottotal);
        //        mainCal();
    }


    function autoaddrow() {
        var ctr = $('#items').val();
        var tr = $(this).closest("tr");
        var srno = tr.find(".srno").val();
        if (srno == ctr) {
            AddRows();
        }
    }


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

    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 focusFld = ".focusFld_" + ctr;
        var detail = ".fetchpart_" + ctr;

        ctr++;
        $('#items').val(ctr);
        $.post('purchgstmulti_add.php', { ctr: ctr, hide: hide_check }, function (data) {
            $(data).appendTo('.tbody');
            $(detail).select2();

            $(focusFld).focus();
        });
    }



});