$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
    $("body").on("keyup change blur focus", ".qty, .rate, .amount,.discperc,.discamt,.vatperc", 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("blur", ".invno", chkinvno);

    $("body").on("blur ", ".barcode", CreateProd);
    $("body").on("blur", ".mbarcode", checkmbarcode);
    $("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", ".barcode", function () {
        currentRow = $(this).closest("tr");
    });

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

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

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

        var mbarcode = $(".mbarcode").val(),
                mprodname = $(".mprodname").val(),
                mcost = $(".mcost").val();

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

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

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

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

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

                // trigger your existing barcode fetch logic
                setTimeout(function () {

                    currentRow.find(".itemname").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 checkmbarcode() {
        var barcode = $('.mbarcode').val();
        if (barcode) {
            $.get('check_prodModal.php', {barcode: barcode}, function (data) {
                if (parseFloat(data) > 0) {
                    $('.mbarcode').val("");
                    $('.mbarcode').focus();
                    alert("Barcode Already Exist");
                }
            });
        }
    }

    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"),
                barcode = tr.find(".barcode").val().toUpperCase(), // convert to uppercase
                itemname = tr.find(".itemname").val();

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

        }
    }

    function chkinvno() {
        var vouchno = $('.vouchno').val();
        var invno = $('.invno').val();
        var party = $(".party").val();
        if (invno.length > 0) {
            $.post('chk_pur_invno.php', {invno: invno, party: party, vouchno: vouchno}, function (data) {
                if (data > 0) {
                    alert('This Bill No. For This Party Already Exist on Voucher No. ' + data);
                    $('.invno').val('');
                    $('.invno').focus();
                }
            });
        }
    }

    $("body").on("keydown", 'td', updown);
    chgType();
    function chgType() {
        var paidby = $(".paidby").val();
        if (paidby == "C") {
            $(".totadv").attr("readonly", true);
            $(".totadv").val("0");
            mainCal();
        } else {
            $(".totadv").removeAttr("readonly", true);

        }
    }
    function updown() {
        var tr = $(this).closest('tr'),
                newsrno = tr.find(".srno").val(),
                srno = parseFloat(newsrno) - 2,
                curcls = $(this).attr('class');

        $(document).keydown(function (event) {
            if (event.keyCode == 40) { // Down key maps to keycode `40`
                if (curcls == 'p2') {
                    $('#rate_' + newsrno).focus();
                    $('#rate_' + newsrno).select();
                } else if (curcls == 'p1') {
                    $('#qty_' + newsrno).focus();
                    $('#qty_' + newsrno).select();
                }
            }
        });


        $(document).keydown(function (event) {
            if (event.keyCode == 38) { // Up key maps to keycode `38`
                if (curcls == 'p2') {
                    $('#rate_' + srno).focus();
                    $('#rate_' + srno).select();
                } else if (curcls == 'p1') {
                    $('#qty_' + srno).focus();
                    $('#qty_' + srno).select();
                }
            }
        });
    }

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

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

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


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

            return false;
            valid = false;
        }
        if (godown == '') {
            var message = "Godown 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();

            }
        }
    });


    //    $("body").on("change blur", ".vouchdt", chkSaleDt);
    //    $("body").on("click", "#submit ,#cancel", hide_but);

    //    function chkSaleDt() {
    //        var vouchdt = $(".vouchdt").val();
    //        $.post('chkSaleLock.php', {vouchdt: vouchdt}, function (data) {
    //            if (data > 0) {
    //                $("#submit").hide();
    //                $('form').on('keyup keypress', function (e) {
    //                    var keyCode = e.keyCode || e.which;
    //                    if (keyCode === 13) {
    //                        e.preventDefault();
    //                        return false;
    //                    }
    //                });
    //            } else {
    //                $("#submit").show();
    //
    //            }
    //
    //        });
    //    }


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

    }


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


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

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

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

    //    function getvoucher() {
    //        var date = new Date($(".vouchdt").val()),
    //                month = (date.getMonth() + 1).toString(),
    //                vouchno = $('.vouchno').val(),
    //                voucher = '0' + month + vouchno;
    //        $('.monno').val(month);
    //        $('.voucher').val(voucher);
    //    }


    $(".lrtab").click(function () {
        $(".lrdetail").animate({
            height: 'toggle'
        });
    });
    //    $('#hedit').click(function () {
    //        var addflag = $('.addflag').val();
    //        if (addflag != 1) {
    //            $('.oms').prop("disabled", true);
    //        } else {
    //            $('.oms').prop("disabled", false);
    //        }
    //    });
    //    function getgst() {
    //        var party = $('.cmbparty').val();
    //        $.post('getcustgst.php', {party: party}, function (data) {
    ////            if (data.gstno != 0) {
    //            $('.gstno').val(data.gstno);
    ////            }
    ////            $('.mobile').val(data.mobile);
    //            $('.transporter').val(data.transporter).trigger('change');
    //        }, 'json');
    //    }


    function calDetail() {
        var tr = $(this).closest("tr"),
                cartqty = tr.find(".cartqty").val(),
                qty = tr.find(".qty").val(),
                totqty = cartqty * qty,
                rate = tr.find(".rate").val(),
                amount = (rate * qty).toFixed(2),
                discperc = tr.find(".discperc").val(),
                discamt = 0,
                vatperc = tr.find(".vatperc").val(),
                subtot = 0,
                total = 0,
                vat = 0;

        if (discperc > 0) {
            discamt = ((discperc * amount) / 100).toFixed(2);
        } else {
            discamt = tr.find(".discamt").val();
        }
        subtot = amount - discamt;
        if (vatperc > 0) {
            vat = ((vatperc * subtot) / 100).toFixed(2);
        } else {
            vat = 0;
        }
        total = (parseFloat(subtot) + parseFloat(vat)).toFixed(2);
        tr.find(".totqty").val(totqty);
        tr.find(".amount").val(amount);
        tr.find(".discamt").val(discamt);
        tr.find(".vat").val(vat);
        tr.find(".total").val(total);
        var totamt = 0,
                totdisc = 0,
                totvat = 0,
                tottotal = 0,
                totbal = 0,
                totalqty = 0,
                totadv = 0;
        $(".qty").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) {
                totamt += parseFloat(this.value);
            }
        });
        //        $(".discamt").each(function () {
        //            if (!isNaN(this.value) && this.value.lenght != 0) {
        //                totdisc += parseFloat(this.value);
        //            }
        //        });
        //        $(".vat").each(function () {
        //            if (!isNaN(this.value) && this.value.lenght != 0) {
        //                totvat += parseFloat(this.value);
        //            }
        //        });
        $(".amount").each(function () {
            if (!isNaN(this.value) && this.value.lenght != 0) {
                tottotal += parseFloat(this.value);
            }
        });
        $(".totamt").val(totamt);

        //        $(".tottotal").val(tottotal);
        mainCal();
    }
    function mainCal() {
        var tdiscperc = $(".ldiscperc").val(),
                vatperc = $(".tvatperc").val(),
                amount = $(".totamt").val(),
                addpack = $(".addpack").val(),
                addgst = $(".addgst").val(),
                totadv = $(".totadv").val(),
                discamt = 0, vat = 0,
                totbal = 0;
        if (tdiscperc > 0) {
            discamt = ((tdiscperc * amount) / 100).toFixed(2);
        } else {
            discamt = $(".totdisc").val();
        }
        var subtot = amount - discamt;
        if (vatperc > 0) {
            vat = ((vatperc * subtot) / 100).toFixed(2);
        } else {
            vat = 0;
        }
        var finamt = parseFloat(subtot) + parseFloat(vat) + parseFloat(addpack) + parseFloat(addgst),
                totbal = parseFloat(finamt);
        $(".totdisc").val(discamt);
        $(".totvat").val(vat);
        $(".tottotal").val(finamt);
        $(".totbal").val(totbal);

    }


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

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



});