$(document).ready(function () {
    $("body").off('click').on("click", '.remove', remove);
    $("body").on('change blur keyup focus', '.rate, .qty, .amount, .discperc, .discamt, .cgstperc, .cgstperc, .subtotal, .netamt', mainCal);
    $("body").on("keyup blur focus", ".qty, .rate, .amount, .cdiscperc, .cdiscamt, .total", calDetail);
    $("body").on('change blur click', '.gstperc, .oms', getGst);
    $("body").on('change blur click', '.item', getRate);
    $("body").on('blur', '.remtran', checkRem);
    $("body").on('blur', '.cdiscperc', focusRem);
    $("body").on('click', '.cardchk', payMode);
    $(".cashamt").attr('readonly', true);
    $(".ccamt").attr('readonly', true);

    mainCal();

    function getRate() {
        var tr = $(this).closest("tr"),
                item = tr.find(".item").val();
        $.post('getRate.php', {item: item}, function (data) {
            tr.find('.rate').val(data);
        });
    }
    function focusRem() {
        var tr = $(this).closest("tr"),
                cdiscp = tr.find(".cdiscperc").val();
//                crem = tr.find(".remtran").val();
        if (cdiscp > 0) {
            tr.find(".remtran").focus();
        }
    }
    function checkRem() {
        var tr = $(this).closest("tr"),
                cdiscp = tr.find(".cdiscperc").val(),
                crem = tr.find(".remtran").val();
        if (cdiscp > 0 && crem == '') {
            alert('Remark for Discount Cannot Be Empty');
            tr.find(".cdiscperc").val("0");
            tr.find(".cdiscperc").focus();

        }
    }

    var para = $(".para").val();
    var admin = $(".admin").val();
    if (admin != '1') {
        $("#hdelete").hide();
//        $("#hedit").hide();
    }
    $("#submit").hide();

    if (para == 'P') {
        $("#edit").click();
    }
    $("#edit").click(function () {
        $("#submit").hide();
    });

    $(".paymode").hide();
    payMode();
    function payMode() {
        if ($(".cardchk").prop("checked") == true) {
            $(".paymode").show();
        } else {
            $(".paymode").hide();
        }
    }



    $(".cashchk").click(function () {
        if (($(".cardchk").prop("checked") == true) || ($(".bothchk").prop("checked") == true)) {
            $(".cashchk").prop("checked", false);
            $(".cashamt").val(0);
            alert('Card or Both Check checkbox are already ticked');
        } else {
            var netamt = $(".netamt").val();
            if ($(".cashchk").prop("checked")) {
                $(".cashamt").val(netamt);
            } else {
                $(".cashamt").val(0);
            }
        }
    });

    $(".cardchk").click(function () {
        if (($(".cashchk").prop("checked") == true) || ($(".bothchk").prop("checked") == true)) {
            $(".cardchk").prop("checked", false);
            $(".ccamt").val(0);
            alert('Cash or Both Check checkbox are already ticked');
        } else {
            var netamt = $(".netamt").val();
            if ($(".cardchk").prop("checked")) {
                $(".ccamt").val(netamt);
            } else {
                $(".ccamt").val(0);
            }
        }
    });

    $(".bothchk").click(function () {
        if (($(".cashchk").prop("checked") == true) || ($(".cardchk").prop("checked") == true)) {
            $(".bothchk").prop("checked", false);
            $(".cashamt").attr('readonly', true);
            $(".ccamt").attr('readonly', true);
            alert('Cash or Card checkbox are already ticked');
        } else {
            if ($(".bothchk").prop("checked")) {
                $(".cashamt").removeAttr('readonly', true);
                $(".ccamt").removeAttr('readonly', true);

            } else {
                $(".cashamt").attr('readonly', true);
                $(".ccamt").attr('readonly', true);
            }
        }
    });


    function getGst() {
        var gstperc = $(".gstperc").val();
        if ($(".oms").prop('checked')) {
            var val = gstperc;
            $('.igstperc').val(val);
            $('.cgstperc').val(0);
            $('.sgstperc').val(0);
        } else {
            var val2 = gstperc / 2;
            $('.cgstperc').val(val2);
            $('.sgstperc').val(val2);
            $('.igstperc').val(0);
        }
        mainCal();
    }


    function calDetail() {
        var tr = $(this).closest("tr"),
                qty = tr.find(".qty").val(),
                rate = tr.find(".rate").val(),
                amount = parseFloat(rate) * parseFloat(qty),
                subtotal = 0,
                total = 0,
                cdiscperc = tr.find(".cdiscperc").val(),
                cdiscamt = 0;

        if (!isNaN(amount)) {
            tr.find(".amount").val(amount);
        } else {
            tr.find(".amount").val("0");
        }

        if (!isNaN(cdiscperc)) {
            tr.find(".cdiscperc").val(cdiscperc);
        } else {
            tr.find(".cdiscperc").val("0");
        }

        if (cdiscperc > 0) {
            if (cdiscperc <= parseFloat(100)) {
                cdiscamt = (cdiscperc * amount) / 100;
            } else {
                alert("Discount Cannot Be Greater Than 100");
                tr.find(".cdiscperc").val("0");
            }
        }

        if (!isNaN(cdiscamt)) {
            tr.find(".cdiscamt").val(cdiscamt);
        } else {
            tr.find(".cdiscamt").val("0");
        }

        total = parseFloat(amount) - parseFloat(cdiscamt);

        if (!isNaN(total)) {
            tr.find(".total").val(total);
        } else {
            tr.find(".total").val("0");
        }





        $(".total").each(function () {
            if (!isNaN(this.value) && this.value.lenght != 0) {
                subtotal += parseFloat(this.value);
            }
        });
        $(".subtot").val(subtotal);
        mainCal();
    }

    function mainCal() {
        var subtot = $(".subtot").val(),
                discperc = $(".discperc").val(),
                discamt = $(".discamt").val();
        if (discperc > 0) {
            discamt = (discperc * subtot) / 100;
        }
        $(".discamt").val(discamt);
        var taxable = parseFloat(subtot) - parseFloat(discamt);

        $(".taxable").val(taxable);


        var cgstperc = $(".cgstperc").val(),
                igstperc = $(".igstperc").val(),
                cgstamt = 0, igstamt = 0;
        if (cgstperc > 0) {
            cgstamt = cgstperc * taxable / 100;
        }
        if (igstperc > 0) {
            igstamt = igstperc * taxable / 100;
        }
        var netamt = parseFloat(taxable) + parseFloat(cgstamt) + parseFloat(cgstamt) + parseFloat(igstamt);
        $(".cgstamt").val(cgstamt);
        $(".sgstamt").val(cgstamt);
        $(".igstamt").val(igstamt);
        $(".netamt").val(netamt);


    }

    $("#finishTab").click(function () {
        var cashamt = $(".cashamt").val(),
                ccamt = $(".ccamt").val(),
                discperc = $(".discperc").val(),
                netamt = $(".netamt").val(),
                tableno = $(".tableno").val(),
                staff = $(".staff").val(),
                gstperc = $(".gstperc").val(),
                admin = $(".admin").val(),
                paymode = $(".paytype").val(),
                totamt = parseFloat(cashamt) + parseFloat(ccamt),
                valid = true;

        if ($(".cardchk").prop("checked") == true) {
            if (paymode == '' || paymode == 0) {
                alert('Payment Type Cannot Be Empty');
                return false;
                valid = false;
            }
        }


        if (admin != '1') {
            if (gstperc <= 0) {
                alert('GST Cannot Be Zero');
                return false;
                valid = false;
            }
        }

        if (cashamt > 0 || ccamt > 0) {
            if (totamt != netamt) {
                alert('Cash, Card Amount Not same as Net Amount');
                return false;
                valid = false;
            }
        }

        if (discperc < 100) {
            if (netamt <= 0) {
                alert('Net Amount Cannot Be Zero');
                return false;
                valid = false;
            }
        }
        if (tableno == '') {
            alert('Table Cannot Be Empty');
            return false;
            valid = false;
        }
        if (staff == '') {
            alert('Staff Cannot Be Empty');
            return false;
            valid = false;
        }




        if (valid) {
            var isValid = true;

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

            }
        }
    });


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

    function AddRows() {
        var ctr = $('#items').val();
        var hide_check = "";
        if ($("#del_all").prop("checked")) {
            hide_check = 0;
        } else {
            hide_check = 1;
        }
        var detail = ".fetchpart_" + ctr;
        $.post('bill_add.php', {ctr: ctr, hide: hide_check}, function (data) {
            $(data).appendTo('.matbody');
            ctr++;
            $('#items').val(ctr);
            $(detail).select2();
        });
    }

//search part


    $("body").on("keyup", ".ssearch", getSearchData);
    $("body").on("change", ".soperator", getSearchData);
    $("body").on("click", ".sload", getSearchData);
    $("body").on("click", "#search", getSearchData);

    //////////////////////////////////////////////Search Part - Start//////////////////////////////////////////////

    $(".snoRecord").hide();
    $(".sloader").hide();

    var imrangeFrom = 0,
            imrangeTo = 40;

    $(".ssearch").focus();
//    $(".ssearch").val("");
//    $(".sfield").val("1");
    getSearchData();

    function getSearchData(pagination) {

        $(".sloader").show();

        if (pagination == 'prev') {
            if (imrangeFrom > 0) {
                imrangeFrom = (imrangeFrom - 40);
                imrangeTo = (imrangeTo - 40);
            }
        }
        if (pagination == 'next') {
            imrangeFrom = (imrangeFrom + 40);
            imrangeTo = (imrangeTo + 40);
        }

        var series = $(".series").val(),
                vouchno = $(".vouchno").val(),
                type = $(".type").val(),
                manual = $(".manual").val(),
                ssearch = $(".ssearch").val(),
                sfield = $(".sfield").val(),
                sortBy = $(".sortBy").val(),
                orderAs = $(".orderAs").val(),
                soperator = $(".soperator").val(),
                data = {ssearch: ssearch, sfield: sfield, sortBy: sortBy, orderAs: orderAs, soperator: soperator,
                    series: series, vouchno: vouchno, rangeFrom: imrangeFrom, rangeTo: imrangeTo, type: type, manual: manual},
                values = "";
        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: "bill_search.php",
            data: data,
            success: function (response) {
                if (response == "") {
                    $(".snoRecord").show();
                    $(".snext").hide();
                    $(".ssload").hide();
                } else {
                    $(".snext").show();
                    $(".snoRecord").hide();
                    $(".ssload").show();


                    $.each(response, function () {
                        values +=
                                "<tr class='getdtl' id='getdtl_" + this.value + " ' >" +
                                "<td align='left'>" + this.vouchno + "<input type='hidden' class='vouchno' value='" + this.vouchno + "'</td>" +
                                "<td align='left'>" + this.vouchdt + "</td>" +
                                "<td align='left'>" + this.vouchtime + "</td>" +
                                "<td align='left'>" + this.tablename + "</td>" +
                                "<td align='left'>" + this.user + "</td>" +
                                "<td align='right'>" + this.totitems + "</td>" +
                                "<td align='right'>" + this.totqty + "</td>" +
                                "<td align='left'><a href='" + this.action + "' ><i class='fa fa-pencil'></i></a></td>" +
//                                "<td align='center'><a href='pendkot_print.php?vouchno=" + this.vouchno + "' target='_blank'><i class='fa fa-print' aria-hidden='true'></i></a></td>" +
                                "</tr>" +
                                "<tr class='dtlhide1' id='dtlsale_" + this.value + "' style='font-size:18px;'>" +
                                "</tr>";
                    });
                    $(".sloader").hide();
                    $(".sTbody").empty();
                    $(".sTbody").html(values);
                    if (response) {
                        $(".search-action-bar").show();
                    }
                }
            },
            error: function (request, textStatus, errorThrown) {

            }
        });
    }
    $("#search").click(function () {
        $(".searchModal").on('shown.bs.modal', function () {
            $(".ssearch").focus();
            $(".ssearch").val("");
            $(".sfield").val("1");
            getSearchData();
        });

        getSearchData();
    });
    $(".sprev").click(function () {
        getSearchData('prev');
    });
    $(".snext").click(function () {
        getSearchData('next');
    });


    //////////////////////////////////////////////Search Part - End  //////////////////////////////////////////////
});