$(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("keydown", 'td', updown);


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


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

    // Open modal
    $('#createTransporterBtn').click(function () {
        $('#transporter_name').val('');
        $('#transporterModal').modal('show');
    });

    // Save transporter
    $('#saveTransporter').click(function () {

        var tname = $('#transporter_name').val().trim();
        var tmobile = $('.tmobile').val();

        if (tname === '') {
            alert('Enter transporter name');
            $("#transporter_name").focus();

            return;
        }

        $.ajax({
            url: "createtransporter.php",
            type: "POST",
            dataType: "json",
            data: { name: tname, mobile: tmobile },
            success: function (res) {
                // 🔴 Transporter already exists
                if (res.status === "exists") {
                    alert("Transporter With Same Name Already Exists! In Customer Or Supplier Master");
                    $("#transporterModal").modal("hide");

                    setTimeout(function () {
                        // open select2
                        $(".transporter").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 transporter created
                var option = new Option(res.name, res.code, true, true);
                $(".transporter").append(option).val(res.code).trigger("change");
                $("#transporterModal").modal("hide");
            },

        });
    });


    $("#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 },
            success: function (res) {
                // 🔴 Party already exists
                if (res.status === "exists") {
                    alert("Party With Same Name Already Exists! In Customer Or Supplier 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);
        });
    }

    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(),
            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();

            }
        }
    });



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

    }


    //    $("#hdelete").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();
    }




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

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

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



});