$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
    $("body").on("blur focus keyup click", '.qty, .rate, .amount, .remove', caltran);
    $("body").on("blur focus keyup click", '.subtotal, .netamt, .cgstperc, .sgstperc, .igstperc, .remove,.party', mainCal);
    $("body").on("blur", '.rate', autoAddRows);
    $("body").on("change", ".mstate", getStateCode);
    $("body").on("change", '.party', getTransporter);
    $("body").on("click", '#saveTransporter', saveTransporter);
    $("body").on("click", '#saveParty', saveParty);


    $("#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 () {
    function saveTransporter() {

        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 () {
    function saveParty() {

        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 getTransporter() {
        var party = $(".party").val();
        if (party) {
            $.ajax({
                type: 'GET',
                dataType: 'json',
                url: "getTransporter.php",
                data: {party: party},
                success: function (response) {
                    var m = response;

                    $(".transporter").val(m.transporter).trigger("change");
                    $(".mobileno").val(m.mobile);

                }
            });
        }
    }



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

    function caltran() {
        var tr = $(this).closest("tr");
        var amt = 0,
                qty = tr.find(".qty").val() || 0,
                rate = tr.find(".rate").val() || 0,
                amt = parseFloat(rate) * parseFloat(qty);
        tr.find('.amount').val(amt);

        var totqty = 0,
                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));

        $('#saledtltab').find('tr').each(function () {
            var row = $(this),
                    qty = row.find(".qty").val() || 0,
                    rate = row.find(".rate").val() || 0,
                    amount = (parseFloat(qty) * parseFloat(rate)).toFixed(2);
            row.find(".amount").val(amount);
        });
        mainCal();
    }

    $("#submit").hide();

    $("#finishTab").click(function () {
        var ccamt = $('.ccamt').val() || 0,
                cashamt = $('.cashamt').val() || 0,
                bankname = $('#bankname').val(),
                credamt = $('.credamt').val() || 0,
                subtotal = $('.subtotal').val() || 0,
                netamt = $('.netamt').val() || 0,
                party = $('.party').val(),
                totcamt = parseFloat(ccamt) + parseFloat(cashamt) + parseFloat(credamt),
                valid = true;

        if (netamt <= 0) {
            alert('Amount Cannot Be Zero');
            return false;
            valid = false;
        }

        if (party == '') {
            alert('Party Cannot Be Empty');
            return false;
            valid = false;
        }

        if (valid) {
            var isValid = true;

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

            }
        }
    });


    // function noZeroAcptQty() {
    //     var $row = $(this).closest("tr"),
    //         mqty = $row.find(".qty").val();
    //     if (mqty != "") {
    //         if (mqty > 0) {
    //         } else {
    //             $row.find(".qty").val("");
    //             alert('Qty Cannot be Zero');
    //             $row.find(".qty").focus();
    //         }
    //     }
    // }

    // function noZeroAcptRate() {
    //     var $row = $(this).closest("tr"),
    //         mrate = $row.find(".rate").val();

    //     if (mrate > 0) {
    //     } else {
    //         alert('Rate Cannot be Zero');
    //         $row.find(".mrp").focus();
    //     }
    // }

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

    ///////////////////////////////////////////////////CALCULATION - START//////////////////////////////////////////////////

    function mainCal() {
        var subtotal = $(".subtotal").val() || 0;

        var oms = Number($(".oms").val());
        var cgstperc = $(".cgstperc").val() || 0;
        var sgstperc = $(".sgstperc").val() || 0;
        var igstperc = $(".igstperc").val() || 0;

        var gstamt = 0;

        if (oms === 1) {
            // IGST
            gstamt = (igstperc / 100) * subtotal;
            $(".igstamt").val(gstamt.toFixed(2));
            $(".cgstamt, .sgstamt").val(0);
        } else {
            // CGST + SGST
            var gstamt1 = (cgstperc / 100) * subtotal;
            var gstamt2 = (sgstperc / 100) * subtotal;

            gstamt = gstamt1 + gstamt2;

            $(".cgstamt").val(gstamt1.toFixed(2));
            $(".sgstamt").val(gstamt2.toFixed(2));
            $(".igstamt").val(0);
        }

        var final = parseFloat(subtotal) + parseFloat(gstamt);
        $(".netamt").val(final);
    }


    ///////////////////////////////////////////////////CALCULATION - END  //////////////////////////////////////////////////


    $('#addnew').click(function () {
        AddRows();
    });

    function remove() {
        $(this).closest("tr").remove();
    }

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

});