var table ,   block = $(".content-wrapper").parent();
    
  function type_ahead_list(id){
    typeahead = $.typeahead({
        input: id,
        minLength: 2,
        order: "asc",
        dynamic: true,
        maxItem: 6,
        cancelButton: true,
        delay: 300,
        template: function (query, item) {
            var color = "#777";
            return `<div class="row res_item" onmouseover="">` +
                        `<div class="row item-detail pull-left">
                            <h6 class="no-margin">{{name}} </h6>
                            <span class='label label-primary'>{{email}}</span>
                            <span class='label label-info'>{{phone}}</span>
                            <span class='label label-primary'>{{type}}</span>
                        </div>
                    </div>`;
        },
        emptyTemplate: "No Customer Found for: '{{query}}'",
        source: {
            company: {
                display: ["name","phone","email"],
                ajax: function (query) {
                    return {
                        type: "POST",
                        url: "models/crul_invoice.php",
                        path: "data.company",
                        data: {
                            q: "{{query}}",
                            type:"search"
                        },
                        callback: {
                            done: function (data) {
                              //console.log(data);
                                return data;
                            }
                        }
                    }
                }
            }
        },
        callback: {
            onClick: function (node, a, item, event) {
              console.log(item);
                $("#customer_id").val(item['cid']);
                $("#customer_type").val(item['type']);
                $("#customer_name1").val(item['name']);
                //$("#email_sent_to").val(item['cust_email']);

            },

            onSendRequest: function (node, query) {
                console.log('request is sent')
            },
            onReceiveRequest: function (node, query) {
                console.log('request is received')
            }
        },
        debug: true
    });

  }


  function type_ahead_list_edit(id){
    typeahead = $.typeahead({
        input: id,
        minLength: 2,
        order: "asc",
        dynamic: true,
        maxItem: 6,
        cancelButton: true,
        delay: 300,
        template: function (query, item) {
            var color = "#777";
            return `<div class="row res_item" onmouseover="">` +
                        `<div class="row item-detail pull-left">
                            <h6 class="no-margin">{{name}} </h6>
                            <span class='label label-primary'>{{email}}</span>
                            <span class='label label-info'>{{phone}}</span>
                            <span class='label label-primary'>{{type}}</span>
                        </div>
                    </div>`;
        },
        emptyTemplate: "No Customer Found for: '{{query}}'",
        source: {
            company: {
                display: ["name","phone","email"],
                ajax: function (query) {
                    return {
                        type: "POST",
                        url: "models/crul_invoice.php",
                        path: "data.company",
                        data: {
                            q: "{{query}}",
                            type:"search"
                        },
                        callback: {
                            done: function (data) {
                              //console.log(data);
                                return data;
                            }
                        }
                    }
                }
            }
        },
        callback: {
            onClick: function (node, a, item, event) {
              console.log(item);
                $("#edit_customer_id").val(item['cid']);
                $("#edit_customer_type").val(item['type']);
                $("#edit_customer_name1").val(item['name']);
                //$("#email_sent_to").val(item['cust_email']);

            },

            onSendRequest: function (node, query) {
                console.log('request is sent')
            },
            onReceiveRequest: function (node, query) {
                console.log('request is received')
            }
        },
        debug: true
    });

  }

  type_ahead_list('#customer_name');
  type_ahead_list_edit('#edit_customer_name');

  function edit_items1(itemid,qty,pric,date_,pro){
            console.log(pro);
            get_Products();
            $("#edit_product_id").html($("#product_id").html());
            $("#edit_objid").val(itemid);
            $("#edit_product_id").val(pro);
            //$('#edit_product_id option[value='+pro+']').attr('selected','selected');
            $("#edit_created_at").val(date_);
            $("#edit_quantity").val(qty);
            $("#edit_buy_price").val(pric);

            // because we didnt have it in table so we cant set it in edit_items we will set it from here
            for(var j=0 ; j< products_array_values.length; j++ ){
             if(pro == products_array_values[j]['id']){

                var sellPrice    = products_array_values[j]['sell_price'];
                var sellPricePer = products_array_values[j]['sell_price_percentage'];
                var avgPrice     = products_array_values[j]['average_price'];
                var oldtotalQty  = products_array_values[j]['remained_quantity'];

                $("#edit_average_price_old").val(avgPrice);
                $("#edit_total_quantity_old").val(oldtotalQty);
                $("#edit_sell_price").val(sellPrice);
                $("#edit_sell_price_percentage").val(sellPricePer);
                $("#edit_quantity_save").val(oldtotalQty-qty); // prevoius remainded quantity before add the current editing quantity of this purchase
                // returning the previous values of average price before adding this editing quantity
                var totalPrice_before_edit = oldtotalQty * avgPrice - qty * pric;
                var avgPrice_before_edit   = totalPrice_before_edit /(oldtotalQty - qty);
                if(isNaN(avgPrice_before_edit)){avgPrice_before_edit = avgPrice}
                $("#edit_average_price_old_prev").val(avgPrice_before_edit)
              }
            }


            $('#edit_form_cont').modal('toggle');
            calc_sell_price_edit();
  }

  var old_products_array_values =[] ;

  function edit_items(itm,inv_no,cust_name,total_price,net_balance,total_paid,total_remained,created,is_paid,pay_term,email,mobile,invoice_return_date,usd_rate,currency,total_discount,customer_id){
    old_products_array_values =[] ;
    cust_name = decodeURIComponent(cust_name);
    email = decodeURIComponent(email);
    mobile = decodeURIComponent(mobile);

    $("#edit_itemid_invoice").val(itm); // for payments
    get_Products();
    $.ajax({
                    url : 'models/crul_invoice.php',
                    type : 'POST',
                    data : {type:'get_edit_invoice',id : itm},
                    dataType : 'json',
                    success : function(response) {
                      if(response.is_success==true){

                        // for Payments
                        var attach ='';
                        var total_paid_amount =0;
                        for(var i=0 ; i < response.payments.length;i++){

                          attach = attach + `<div id="edit_payment_row`+(i+1)+`">
                                                  <div class="form-group has-feedback has-feedback-left form-group-material col-sm-5">
                                                       <label class="control-label animate is-visible">Payment Amount</label>
                                                       <input type="text" id="edit_paid_price`+(i+1)+`" name="edit_paid_price`+(i+1)+`" class="form-control" placeholder="Payment Amount" required="required" value="`+currency_format(response.payments[i][3])+`">
                                                       <div class="form-control-feedback"><i class="icon-cash text-muted"></i></div>
                                                       <input type="hidden" id="edit_invoice_id_pay`+(i+1)+`" name="edit_invoice_id_pay`+(i+1)+`" value="`+response.payments[i][7]+`">
                                                       <input type="hidden" id="edit_payment_id`+(i+1)+`" name="edit_payment_id`+(i+1)+`" value="`+response.payments[i][0]+`">
                                                  </div>
                                                  <div class="form-group has-feedback has-feedback-left form-group-material col-sm-5">
                                                       <label class="control-label animate is-visible">Payment Date</label>
                                                       <input type="text" id="edit_payment_date`+(i+1)+`" name="edit_payment_date`+(i+1)+`" class="form-control" placeholder="Payment Date" value="`+response.payments[i][4]+`" readonly>
                                                       <div class="form-control-feedback"><i class="icon-calendar3 text-muted"></i></div>
                                                  </div>
                                                  <div class="form-group has-feedback has-feedback-left form-group-material col-sm-2" >
                                                       <a id="edit_save_payment_btn" class="btn btn-primary" style="margin-top: 25px;" onclick="update_payments(`+(i+1)+`,`+response.payments[i][0]+`,`+response.payments[i][7]+`,'edit_')" data-popup="tooltip" data-original-title="Save Changes">
                                                          <i class="icon-floppy-disk"></i>
                                                       </a>
                                                       <a id="edit_remove_payment_btn" class="btn btn-danger" style="margin-top: 25px;" onclick="remove_payments(`+(i+1)+`,`+response.payments[i][0]+`,`+response.payments[i][7]+`,'edit_')" data-popup="tooltip" data-original-title="Delete Payment">
                                                          <i class="icon-x"></i>
                                                       </a>
                                                    </div>
                                              </div>`;
                           total_paid_amount = +total_paid_amount + +response.payments[i][3];
                        }
                        $("#edit_total_paid").val(currency_format(total_paid_amount));
                        $("#edit_edit_payments_fields").html(attach);

                        // for products

                        var attach_p ='';
                        var cunt = 1;
                        $("#edit_products_array_div").html('');
                        var total_invoice_edit = 0;
                        for(var i=0 ; i < response.sell.length;i++){

                          // to save the old unit price until not change to new values unless he change the product to new one
                          old_products_array_values.push({
                                                        sell_id: response.sell[i][0],
                                                        quantity: response.sell[i][1],
                                                        discount: response.sell[i][2],
                                                        unit_price: response.sell[i][3],
                                                        product_id: response.sell[i][5],
                                                        invoice_id: response.sell[i][6],
                                                        product_name: response.sell[i][7],
                                                        average_price: response.sell[i][8]
                                                    });
                          console.log(old_products_array_values);
                          var eventsAll = ` onchange="calculate_price_edit();"   onkeyup="this.onchange();" onkeypress="this.onchange();"  onpaste="this.onchange();" oninput="this.onchange();" onkeydown="this.onchange();"  `;

                          var newField = `<div class="form-group " id="edit_field_`+cunt+`" >
                                            <div class="form-group form-group-material col-sm-2">
                                                <label class="control-label animate">Product Name</label>
                                                <select name="edit_product_id`+cunt+`" id="edit_product_id`+cunt+`" class="form-control" `+eventsAll+`>
                                                    <option value="" selected="selected">Product Name</option>
                                                </select>
                                            </div>
                                            <div class="form-group form-group-material col-sm-3">
                                                <label class="control-label has-margin is-visible">Quantity
                                                  <label class="badge badge-success position-right" id="edit_qty_store`+cunt+`" style="margin-left: 40px; margin-bottom: auto;">Total Quantity In Store</label>
                                                </label>
                                                <input type="text" id="edit_quantity`+cunt+`" name="edit_quantity`+cunt+`" value="`+response.sell[i][1]+`" class="touchspin-basic" placeholder="Quantity" required="required" `+eventsAll+`>
                                            </div>
                                            <div class="form-group has-feedback has-feedback-left form-group-material col-sm-2">
                                                <label class="control-label is-visible">Unit Price</label>
                                                <input type="text" id="edit_unit_price`+cunt+`" name="edit_unit_price`+cunt+`" value="`+response.sell[i][3]+`" class="form-control" placeholder="Unit Price" readonly>
                                                <div class="form-control-feedback">   <i class=" icon-cash text-muted"></i>  </div>
                                            </div>
                                            <div class="form-group has-feedback has-feedback-left form-group-material col-sm-1">
                                                 <label class="control-label is-visible">Discount</label>
                                                 <input type="text" id="edit_discount`+cunt+`" name="edit_discount`+cunt+`" value="`+response.sell[i][2]+`" class="form-control" placeholder="Discount" `+eventsAll+` >
                                                 <div class="form-control-feedback"> <i class="icon-price-tag text-muted"></i></div>
                                            </div>
                                            <input type="hidden" id="edit_product_avg_price`+cunt+`" name="edit_product_avg_price`+cunt+`" value="`+response.sell[i][8]+`" readonly >
                                            <div class="form-group has-feedback has-feedback-left form-group-material col-sm-2">
                                                 <label class="control-label is-visible">Totals</label>
                                                 <input type="text" id="edit_totals`+cunt+`" name="edit_totals`+cunt+`" class="form-control" placeholder="Totals" readonly >
                                                 <div class="form-control-feedback">  <i class="icon-coins text-muted"></i> </div>
                                            </div>
                                            <div class="form-group has-feedback  col-sm-2" style="font-size: xx-small;">
                                                <!--
                                                <a id="edit_save_product_btn" class="btn btn-primary btn-xs" style="margin-top: 25px; font-size: xx-small;" onclick="update_product(`+(i+1)+`,`+response.sell[i][0]+`,`+response.sell[i][1]+`,`+response.sell[i][2]+`,`+response.sell[i][3]+`,`+response.sell[i][5]+`,`+response.sell[i][6]+`)" data-popup="tooltip" data-original-title="Save Changes">
                                                  <i class="icon-floppy-disk"></i>
                                                </a> -->
                                                <a id="edit_remove_fields_btn" class="btn btn-danger btn-xs" style="margin-top: 25px; font-size: xx-small;" onclick="remove_edit_field(`+cunt+`)">
                                                  <i class="icon-x"></i>
                                                </a>
                                                <span id="edit_add_fields_btn" class="btn btn-info btn-xs" style="margin-top:25px; font-size: xx-small;" onclick="add_fields_btn_edit();">
                                                  <i class="icon-plus22"></i>
                                                </span>
                                            </div>
                                        </div>`;

                          $("#edit_products_array_div").append(newField);
                          $("#edit_product_id"+cunt).html($("#product_id_store").html());
                          $("#edit_product_id"+cunt).val(response.sell[i][5]);
                          $("#edit_product_id"+cunt).selectpicker('refresh');
                          $(".touchspin-basic").TouchSpin({
                               min: 0,
                               max: 100000,
                               step: 1
                          });
                          var total_price_cal = response.sell[i][1] * response.sell[i][3] - response.sell[i][2];
                          $("#edit_totals"+cunt).val(total_price_cal);
                          total_invoice_edit = +total_invoice_edit  + +total_price_cal;

                          cunt = +cunt +1;
                          $("#edit_field_counter").val(cunt);

                          
                        } // for i
                        
                        calculate_price_edit("maxQ");
                        $("#edit_total_invoice").val(currency_format(total_invoice_edit));

                        }else{
                          noty({
                                   width: 200,
                                   text: response.message,
                                   type: 'error',
                                   dismissQueue: true,
                                   timeout: 3000,
                                   layout: 'top',
                             });
                        }
                    },
                    complete: function() {
                           //  me.data('requestRunning', false);
                    }

              }); // submit ajax

    



            

            $("#edit_product_id").html($("#product_id").html());
            $("#edit_objid").val(itm);
            $("#edit_pay_term").val(pay_term);
            $("input[id='edit_pay_term']").TouchSpin({
                initval: pay_term
            });

           
            
            $("#edit_customer_id").val(customer_id);
            $("#edit_customer_name1").val(cust_name);
            $("#edit_customer_name").val(cust_name);

            $("#edit_net_balance").val(currency_format(net_balance));
            
            if(is_paid ==4){ // its offer
              $('#edit_is_offer').prop('checked', true);
            }else{
              $('#edit_is_offer').prop('checked', false);
            }

            // because we didnt have it in table so we cant set it in edit_items we will set it from here
            /*for(var j=0 ; j< products_array_values.length; j++ ){
             if(pro == products_array_values[j]['id']){

                var sellPrice    = products_array_values[j]['sell_price'];
                var sellPricePer = products_array_values[j]['sell_price_percentage'];
                var avgPrice     = products_array_values[j]['average_price'];
                var oldtotalQty  = products_array_values[j]['remained_quantity'];

                $("#edit_average_price_old").val(avgPrice);
                $("#edit_total_quantity_old").val(oldtotalQty);
                $("#edit_sell_price").val(sellPrice);
                $("#edit_sell_price_percentage").val(sellPricePer);
                $("#edit_quantity_save").val(oldtotalQty-qty); // prevoius remainded quantity before add the current editing quantity of this purchase
                // returning the previous values of average price before adding this editing quantity
                var totalPrice_before_edit = oldtotalQty * avgPrice - qty * pric;
                var avgPrice_before_edit   = totalPrice_before_edit /(oldtotalQty - qty);
                if(isNaN(avgPrice_before_edit)){avgPrice_before_edit = avgPrice}
                $("#edit_average_price_old_prev").val(avgPrice_before_edit)
              }
            }*/


            $('#edit_form_cont').modal('toggle');
            calc_sell_price_edit();
  }

  function delete_items(itemid,pid) {
      block = $("#list_of_items_tbl");
      // bootstrap modal confirmation box
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this record!1",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#EF5350",
            confirmButtonText: "Yes, delete it!",
            cancelButtonText: "No, cancel",
            closeOnConfirm: false,
            closeOnCancel: true
        },
        function(isConfirm){
            if (isConfirm) {
              $.ajax({
                url: "models/crul_invoice.php",
                type:"POST",
                data: {"type":"delete","obj_id":itemid} ,
                complete:function(){
                 // hideLoader();
                },
                beforeSend:function(){
                 // showLoader("Deleting Invoice");
            },
                success: function(res) {
                  if(res == 1){
                    get_Products();
                    swal({
                                title: "Deleted!",
                                text: "Invoice has been deleted.",
                                confirmButtonColor: "#66BB6A",
                                type: "success"
                            });
                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                  }else{
                    swal({
                                title: "Cancelled",
                                text: "Your record file is safe, some thing went wrong.",
                                confirmButtonColor: "#2196F3",
                                type: "error"
                            });
                  }
                }
            });
            }
        }); // /confirm
  }

  function Checks(id,types=null,min=null,max=null){
      var name = $("#"+id).val();
     // alert(id + " = " + name)
      if(types == null){  // it mean string

            if(min !=null && max !=null){
                if(name =='' || name.length < min || name.length > max){
                  $("#"+id).closest('.form-group').removeClass('has-success');
                  $("#"+id).closest('.form-group').addClass('has-error');

                  noty({
                          width: 200,
                          text: "Please Enter the Required Field with minimum length of "+ min + " and maximum length " + max,
                          type: 'error',
                          dismissQueue: true,
                          timeout: 3000,
                          layout: 'topRight',
                    });
                  return false;
                }else{
                    $("#"+id).closest('.form-group').removeClass('has-error');
                    $("#"+id).closest('.form-group').addClass('has-success');
                    return true;
                }
            }else if(min !=null && max ==null){
                if(name ==''  || name.length < min ){
                  $("#"+id).closest('.form-group').removeClass('has-success');
                  $("#"+id).closest('.form-group').addClass('has-error');

                  noty({
                          width: 200,
                          text: "Please Enter the Required Field with minimum length of "+ min ,
                          type: 'error',
                          dismissQueue: true,
                          timeout: 3000,
                          layout: 'topRight',
                    });
                  return false;
                }else{
                    $("#"+id).closest('.form-group').removeClass('has-error');
                    $("#"+id).closest('.form-group').addClass('has-success');
                    return true;
                }
            }else if(min ==null && max !=null){
                if(name ==''  ||  name.length > max){
                  $("#"+id).closest('.form-group').removeClass('has-success');
                  $("#"+id).closest('.form-group').addClass('has-error');

                  noty({
                          width: 200,
                          text: "Please Enter the Required Field with  maximum length of " + max,
                          type: 'error',
                          dismissQueue: true,
                          timeout: 3000,
                          layout: 'topRight',
                    });
                  return false;
                }else{
                    $("#"+id).closest('.form-group').removeClass('has-error');
                    $("#"+id).closest('.form-group').addClass('has-success');
                    return true;
                }
            }else{

                if(name ==''){
                  $("#"+id).closest('.form-group').removeClass('has-success');
                  $("#"+id).closest('.form-group').addClass('has-error');

                  noty({
                          width: 200,
                          text: "Field should not be empty",
                          type: 'error',
                          dismissQueue: true,
                          timeout: 3000,
                          layout: 'topRight',
                    });
                  return false;
                }else{
                    $("#"+id).closest('.form-group').removeClass('has-error');
                    $("#"+id).closest('.form-group').addClass('has-success');
                    return true;
                }

            }

      }else if(types == 'No'){  // it mean numbers

            if(min !=null && max !=null){
                if(name !='' && isNaN(name) || name < min || name > max){
                  $("#"+id).closest('.form-group').removeClass('has-success');
                  $("#"+id).closest('.form-group').addClass('has-error');

                  noty({
                          width: 200,
                          text: "Please Enter Numeric Value between "+ min + " and " + max,
                          type: 'error',
                          dismissQueue: true,
                          timeout: 3000,
                          layout: 'topRight',
                    });
                  return false;
                }else{
                    $("#"+id).closest('.form-group').removeClass('has-error');
                    $("#"+id).closest('.form-group').addClass('has-success');
                    return true;
                }
            }else if(min !=null && max ==null){
                if(name !='' && isNaN(name) || name < min ){
                  $("#"+id).closest('.form-group').removeClass('has-success');
                  $("#"+id).closest('.form-group').addClass('has-error');

                  noty({
                          width: 200,
                          text: "Please Enter Numeric Value Greater than "+ min,
                          type: 'error',
                          dismissQueue: true,
                          timeout: 3000,
                          layout: 'topRight',
                    });
                  return false;
                }else{
                    $("#"+id).closest('.form-group').removeClass('has-error');
                    $("#"+id).closest('.form-group').addClass('has-success');
                    return true;
                }
            }else if(min ==null && max !=null){
                if(name !='' && isNaN(name) ||  name > max){
                  $("#"+id).closest('.form-group').removeClass('has-success');
                  $("#"+id).closest('.form-group').addClass('has-error');

                  noty({
                          width: 200,
                          text: "Please Enter Numeric Value Less than " + max,
                          type: 'error',
                          dismissQueue: true,
                          timeout: 3000,
                          layout: 'topRight',
                    });
                  return false;
                }else{
                    $("#"+id).closest('.form-group').removeClass('has-error');
                    $("#"+id).closest('.form-group').addClass('has-success');
                    return true;
                }
            }else{

                if(name !='' && isNaN(name)){
                  $("#"+id).closest('.form-group').removeClass('has-success');
                  $("#"+id).closest('.form-group').addClass('has-error');

                  noty({
                          width: 200,
                          text: "Please Enter Numeric Value",
                          type: 'error',
                          dismissQueue: true,
                          timeout: 3000,
                          layout: 'topRight',
                    });
                  return false;
                }else{
                    $("#"+id).closest('.form-group').removeClass('has-error');
                    $("#"+id).closest('.form-group').addClass('has-success');
                    return true;
                }

            }

      }
  }

  

  function calc_sell_price() {
              var newQty    = $('#quantity').val();
              var newPrice  = $('#buy_price').val();
              var newMul    = newQty * newPrice;
              //console.log("New Price : "+newMul)
              var oldQty    = $("#total_quantity_old").val();
              var oldAvg    = $('#average_price_old').val();
              var oldMul    = oldQty * oldAvg;
              //console.log("Old Price : "+oldMul)
              if(newPrice !='' && newPrice >0 && newPrice !=null && newPrice !=undefined){
              var newAvg    = (+newMul + +oldMul) / (+newQty + +oldQty);
              }else{
                var newAvg    = oldAvg;
              }
              $("#average_price").val(parseFloat(newAvg).toFixed(2));
              var SellPercen = $('#sell_price_percentage').val();

              if(SellPercen !='' && SellPercen >0 && SellPercen !=null && SellPercen !=undefined){
                var Percen    = SellPercen * newAvg /100;
                var sellPrice = +Percen + +newAvg;

                $("#sell_price").val(parseFloat(sellPrice).toFixed(2));
              }

  }


  function calc_sell_price_edit() {

            //var oldQtysave    = $('#edit_quantity_save').val();
            var newQty    = $('#edit_quantity').val();
            var newPrice  = $('#edit_buy_price').val();
            var newMul    = newQty * newPrice;
            //console.log("New Price : "+newMul)
            var oldQty    = $("#edit_quantity_save").val() ;
            var oldAvg    = $('#edit_average_price_old_prev').val();
            var oldMul    = oldQty * oldAvg;
            //console.log("Old Price : "+oldMul)
            if(newPrice !='' && newPrice >0 && newPrice !=null && newPrice !=undefined){
            var newAvg    = (+newMul + +oldMul) / (+newQty + +oldQty);
            }else{
              var newAvg    = oldAvg;
            }
            $("#edit_average_price").val(parseFloat(newAvg).toFixed(2));
            var SellPercen = $('#edit_sell_price_percentage').val();
            if(SellPercen !='' && SellPercen >0 && SellPercen !=null && SellPercen !=undefined){
              var Percen    = SellPercen * newAvg /100;
              var sellPrice = +Percen + +newAvg;

              $("#edit_sell_price").val(parseFloat(sellPrice).toFixed(2));
            }

  }

  

  function calculate_price(){

      

      var cnt = $("#field_counter").val();
      var Bill_total = 0;
      var current_products = []; // store current product in invoice to resolve duplicated product
      
      for(var i =1; i < cnt; i++){

          var productID     = $("#product_id"+i).val();
          var quantityField = $("#quantity"+i).val();
          var discountField = $("#discount"+i).val();
          console.log(productID);
          if(productID != undefined && productID != null){
             if(isNaN(current_products[productID])){ current_products[productID] =0}
              current_products[productID] = current_products[productID] + 1;
              if(current_products[productID] >= 2){
                noty({
                                   width: 200,
                                   text: "Product Already Selected!!",
                                   type: 'error',
                                   dismissQueue: true,
                                   timeout: 3000,
                                   layout: 'top',
                             });
                $("#product_id"+i).val('');
                $("#product_id"+i).selectpicker('refresh');
                return false;
              }

              var sellPrice     = 0;
              // to get sell price for product
              for(var j=0 ; j< products_array_values.length; j++ ){
                 if(productID == products_array_values[j]['id']){
                    sellPrice = products_array_values[j]['sell_price'];
                    var maxQ = products_array_values[j]['remained_quantity'];


                    console.log('Max Qty :' + maxQ)
                    if(maxQ == null || maxQ == 0){
                      $("#unit_price"+i).val('');
                      noty({
                                   width: 200,
                                   text: "You Can't Sell This Product, The Remained Quantity is 0 !",
                                   type: 'error',
                                   dismissQueue: true,
                                   timeout: 3000,
                                   layout: 'topRight',
                             });
                      $("#product_id"+i).val('');
                      $("#product_id"+i).selectpicker('refresh');
                      $("#qty_store"+i).removeClass();
                      $("#qty_store"+i).addClass('badge badge-danger position-right');
                      $("#qty_store"+i).html("Total Quantity In Store : "+maxQ);
                      return false;
                    }else{
                      $("#unit_price"+i).val(currency_format(sellPrice));
                    }

                    $("#product_avg_price"+i).val(products_array_values[j]['average_price']);


                    $( "#quantity"+i).trigger("touchspin.updatesettings", {max: maxQ});

                    var msg = 'badge badge-success position-right';
                    if(maxQ < 100 && maxQ >20){
                      msg = 'badge badge-warning position-right';
                    }else if(maxQ < 20){
                       msg = 'badge badge-danger position-right';
                    }


                   // $( "#quantity"+i).trigger("touchspin.updatesettings", {postfix: maxQ});
                    $( "#qty_store"+i).removeClass();
                    $( "#qty_store"+i).addClass(msg);
                    $( "#qty_store"+i).html("Total Quantity In Store : "+maxQ);
                 }
              }

              // check if discount greater than total price
                if(discountField > (sellPrice * quantityField)){
                  $("#discount"+i).val('');
                  noty({
                                   width: 200,
                                   text: "Discount Can Not Be Greater Than Sell Price!",
                                   type: 'error',
                                   dismissQueue: true,
                                   timeout: 3000,
                                   layout: 'topRight',
                             });
                }
              // end check discount
              var totalproduct = sellPrice * quantityField - discountField;
              $("#totals"+i).val(currency_format(parseFloat(totalproduct).toFixed(2)));

              Bill_total = Bill_total + totalproduct;


          }
      }

      $("#total_invoice").val(currency_format(parseFloat(Bill_total).toFixed(2)));
      $("#net_balance").val(currency_format(parseFloat(Bill_total).toFixed(2)));
  }

  function calculate_price_edit(is_edit=null){


      var cnt = $("#edit_field_counter").val();
      var Bill_total = 0;
      var current_products = []; // store current product in invoice to resolve duplicated product
      

      

      for(var i =1; i < cnt; i++){

          var productID     = $("#edit_product_id"+i).val();
          var quantityField = $("#edit_quantity"+i).val();
          var discountField = $("#edit_discount"+i).val();
          console.log(productID);
          

          if(productID != undefined && productID != null){
            if(isNaN(current_products[productID])){ current_products[productID] =0}
              current_products[productID] = current_products[productID] + 1;
              if(current_products[productID] >= 2){
                noty({
                                   width: 200,
                                   text: "Product Already Selected!!",
                                   type: 'error',
                                   dismissQueue: true,
                                   timeout: 3000,
                                   layout: 'top',
                             });
                $("#edit_product_id"+i).val('');
                $("#edit_product_id"+i).selectpicker('refresh');
                return false;
              }
                    //alert(current_products[productID])

              var sellPrice     = 0;
              var avg_price     = 0;
              // to get sell price for product
              for(var j=0 ; j< products_array_values.length; j++ ){

                 if(productID == products_array_values[j]['id']){
                    
                    sellPrice = products_array_values[j]['sell_price'];
                    avg_price = products_array_values[j]['average_price']; 
                    
                    // Check for old value if product sold we should load the values of selling date not the current date
                    for(var kk=0 ; kk< old_products_array_values.length; kk++ ){
                       if(productID == old_products_array_values[kk]['product_id']){
                        sellPrice = old_products_array_values[kk]['unit_price']; 
                        avg_price = old_products_array_values[kk]['average_price'] 
                       }
                    }

                    

                    // we should add the edit qty with remaind qty just once when call edit_item
                    var current_qty = 0;

                    if(is_edit == "maxQ"){
                      
                      products_array_values[j]['remained_quantity'] = +products_array_values[j]['remained_quantity'] + +$("#edit_quantity"+i).val();
                    }

                    var maxQ  = products_array_values[j]['remained_quantity'];
                    
                    

                    console.log('Max Qty :' + maxQ)
                    if(maxQ == null || maxQ == 0){
                      noty({
                                   width: 200,
                                   text: "You Can't Sell This Product, The Remained Quantity is 0 !",
                                   type: 'error',
                                   dismissQueue: true,
                                   timeout: 3000,
                                   layout: 'topRight',
                             });
                      $("#edit_unit_price"+i).val('');
                      $("#edit_product_id"+i).val('');
                      $("#edit_product_id"+i).selectpicker('refresh');
                      $("#edit_qty_store"+i).removeClass();
                      $("#edit_qty_store"+i).addClass('badge badge-danger position-right');
                      $("#edit_qty_store"+i).html("Total Quantity In Store : "+maxQ);
                      return false;
                      
                    }else{
                      $("#edit_unit_price"+i).val(currency_format(sellPrice));
                      $("#edit_product_avg_price"+i).val(avg_price);
                    }

                    

                    

                    $( "#edit_quantity"+i).trigger("touchspin.updatesettings", {max: +maxQ + +current_qty});

                    var msg = 'badge badge-success position-right';
                    if(maxQ < 100 && maxQ >20){
                      msg = 'badge badge-warning position-right';
                    }else if(maxQ < 20){
                       msg = 'badge badge-danger position-right';
                    }


                   // $( "#quantity"+i).trigger("touchspin.updatesettings", {postfix: maxQ});
                    $( "#edit_qty_store"+i).removeClass();
                    $( "#edit_qty_store"+i).addClass(msg);
                    $( "#edit_qty_store"+i).html("Total Quantity In Store : "+maxQ);

                 } // if productID == products_array_values
              } // for j

              // check if discount greater than total price
                if(discountField > (sellPrice * quantityField)){
                  $("#edit_discount"+i).val('');
                  noty({
                                   width: 200,
                                   text: "Discount Can Not Be Greater Than Sell Price!",
                                   type: 'error',
                                   dismissQueue: true,
                                   timeout: 3000,
                                   layout: 'topRight',
                             });
                }
              // end check discount

              var totalproduct = sellPrice * quantityField - discountField;
              $("#edit_totals"+i).val(currency_format(parseFloat(totalproduct).toFixed(2)));

              Bill_total = Bill_total + totalproduct;


          } // if productID != null
      } // for i

      $("#edit_total_invoice").val(currency_format(parseFloat(Bill_total).toFixed(2)));
      $("#edit_net_balance").val(currency_format(parseFloat(Bill_total).toFixed(2)));
  }

  function get_Category(){

          $.ajax({
                url : 'models/crul_category.php',
                type : 'POST',
                data : {type:'get'},
                dataType : 'json',
                success : function(response) {
                  //console.log(response)
                    var attach ='<option value="" selected="selected">Category Name</option>';
                    var aaa='';
                      for(var i=response.length-1 ; i >= 0;i--){
                        var tp ="Income";
                        if(response[i][2]==1){tp ="Outcome";}
                        attach = attach + '<option data-subtext="'+tp+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                        aaa = aaa + '<option  value="'+response[i][0]+'">'+response[i][1]+'</option>';

                      }
                      $("#category_id").html(attach);
                      $("#edit_category_id").html(attach);
                      $('#category_id').selectpicker('refresh');
                      $("#edit_category_id").selectpicker('refresh');
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                }

          }); // submit ajax

  }

  var products_array_values =[] ;

  function get_Products_Price(){
      // here we will just show the income products
      products_array_values =[] ;
      var comp = false;
      $.ajax({
                url : 'models/crul_product.php',
                type : 'POST',
                data : {type:'get'},
                dataType : 'json',
                success : function(response) {
                       for(var i=response.length-1 ; i >= 0;i--){
                          if(response[i][16]==0){
                                products_array_values.push({
                                                        id: response[i][0],
                                                        product_name: response[i][1],
                                                        sell_price: response[i][4],
                                                        sell_price_percentage: response[i][5],
                                                        average_price: response[i][6],
                                                        category_id_fk: response[i][7],
                                                        category : response[i][15],
                                                        category_type : response[i][16],
                                                        total_quantity : response[i][17],
                                                        sold_quantity : response[i][18],
                                                        remained_quantity: response[i][19]

                                                    });
                          }
                      }
                      
                },
                complete: function() {
                  comp = true;
                }

          }); // submit ajax
        return comp;
      }


  function get_Products(){
      // here we will just show the income products
      products_array_values =[] ;
      $.ajax({
                url : 'models/crul_product.php',
                type : 'POST',
                data : {type:'get'},
                dataType : 'json',
                success : function(response) {
                  console.log(response)
                    var attach ='<option value="" selected="selected">Product Name</option>';
                    var edit_attach ='';
                      for(var i=response.length-1 ; i >= 0;i--){
                          if(response[i][16]==0){
                              var tp ="Income";
                              if(response[i][16]==1){tp ="Outcome";}
                              var cat_nm = response[i][15];
                              attach = attach + '<option data-subtext=" Category : '+cat_nm+" || Type : "+tp+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                              edit_attach = edit_attach +  '<option value="'+response[i][0]+'">'+response[i][1]+'</option>';
                              products_array_values.push({
                                                        id: response[i][0],
                                                        product_name: response[i][1],
                                                        sell_price: response[i][4],
                                                        sell_price_percentage: response[i][5],
                                                        average_price: response[i][6],
                                                        category_id_fk: response[i][7],
                                                        category : response[i][15],
                                                        category_type : response[i][16],
                                                        total_quantity : response[i][17],
                                                        sold_quantity : response[i][18],
                                                        remained_quantity: response[i][19]

                                                    });
                          }
                      }
                      $("#product_id1").html(attach);
                      $("#product_id_store").html(attach);
                      $('#product_id1').selectpicker('refresh');
                      //$("#edit_product_id").html(edit_attach);

                },
                complete: function() {

                }

          }); // submit ajax

      }

  function getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
          return pair[1];
        }
      }
      return 'not';
  }

  function remove_field(id) {
      /*var cunt = $("#field_counter").val();
      cunt = +cunt -1;
      $("#field_counter").val(cunt);*/
      $("#field_"+id).html('');
      $("#field_"+id).remove();
      calculate_price();
  }

  function remove_edit_field(id) {
      /*var cunt = $("#field_counter").val();
      cunt = +cunt -1;
      $("#field_counter").val(cunt);*/
      $("#edit_field_"+id).html('');
      $("#edit_field_"+id).remove();
      calculate_price_edit();
  }

  function show_invoice(itm,inv_no,cust_name,total_price,net_balance,total_paid,total_remained,created,is_paid,pay_term,email,mobile,invoice_return_date,usd_rate,currency,total_discount){

          cust_name = decodeURIComponent(cust_name);
          email = decodeURIComponent(email);
          mobile = decodeURIComponent(mobile);

          $.ajax({
                url : 'models/crul_invoice.php',
                type : 'POST',
                data : {type:'show_invoice', id : itm},
                dataType : 'json',
                success : function(response) {
                    console.log(response)
                    var customer_info ='';
                    var attach = "";
                    var footers="";
                    var Bill_totalPrice = 0;
                    var Bill_discount = 0;
                    var invoice_condition ="Not Paid";
                    if(is_paid ==1){
                      invoice_condition ="Partially Paid";
                    }else if(is_paid ==2){
                      invoice_condition ="Completly Paid";
                    }else if(is_paid ==3){
                      invoice_condition ="Returned";
                    }else if(is_paid ==4){
                      invoice_condition ="Offer";
                    }
                        customer_info =`<table width="100%">
                                                <tr class="text-bold">
                                                    <td width="45%"><span class="text-primary">Invoice No :</span></td>
                                                    <td width="55%"><span class="text-danger" id="invoice_No_pdf">`+inv_no+`</span></td>
                                                </tr>
                                                <tr class="text-bold">
                                                    <td width="45%"><span class="text-primary">Invoice To :</span></td>
                                                    <td width="55%"><span class="text-danger" id="invoice_No_pdf">`+cust_name+`</span></td>
                                                </tr>
                                                <tr class="text-bold">
                                                    <td width="45%"><span class="text-primary">Mobile :</span></td>
                                                    <td width="55%"><span class="text-danger" id="invoice_No_pdf">`+mobile+`</span></td>
                                                </tr>
                                                <tr class="text-bold">
                                                    <td width="45%"><span class="text-primary">Invoice Date :</span></td>
                                                    <td width="55%"><span class="text-danger" id="invoice_No_pdf">`+created+`</span></td>
                                                </tr>
                                                <tr class="text-black">
                                                    <td width="45%"><span class="text-primary">Invoice Status :</span></td>
                                                    <td width="55%"><span class="text-danger" id="invoice_No_pdf">`+invoice_condition+`</span></td>
                                                </tr>
                                        </table>`;

                      $("#invoice_detials").html(customer_info);

                      for(var i=0 ; i < response.length;i++){
                        var total_item_price = response[i][1] * response[i][3] - response[i][2];
                        attach = attach + `<tr>
                                                <td>`+(i+1)+`</td>
                                                <td>`+response[i][4]+`</td>
                                                <td>`+response[i][1]+`</td>
                                                <td>`+currency_format_display(response[i][3])+`</td>
                                                <td>`+currency_format_display(response[i][2])+`</td>
                                                <td class="alpha-orange text-center text-bold">`+currency_format_display(total_item_price)+`</td>
                                            </tr>`;
                        Bill_totalPrice = +Bill_totalPrice + +total_item_price;
                        Bill_discount   = +Bill_discount + +response[i][2];
                        //alert(Bill_discount)
                      }
                      Bill_totalPrice=currency_format_display(Bill_totalPrice);
                      Bill_discount=currency_format_display(Bill_discount);

                      footers =`<div class="text-teal-800 text-bold text-size-large">
                                      <span class="col-md-7">Total Price:</span>
                                      <span class="text-success-800 col-md-5 text-center">`+Bill_totalPrice+`</span>
                                </div>
                                <div class="text-primary text-size-large">
                                      <span class="col-md-7">Net Balance:</span>
                                      <span class="text-primary-800 col-md-5 text-center">`+currency_format_display(net_balance)+`</span>
                                </div>
                                <div class="text-danger text-size-large">
                                      <span class="col-md-7">Total Discount:</span>
                                      <span class="text-danger col-md-5 text-center">`+Bill_discount+`</span>
                                 </div>
                                <div class="text-primary text-size-large">
                                      <span class="col-md-7">Total Paid:</span>
                                      <span class="text-primary-800 col-md-5 text-center">`+currency_format_display(total_paid)+`</span>
                                </div>
                                
                                <hr class="col-md-11 col-md-push-0">
                                <div class="text-warning-800 text-size-large">
                                    <span class="col-md-7"> Remained:</span>
                                    <span class="text-warning-800 col-md-5 text-center">`+currency_format_display(total_remained)+`</span>
                                </div>`;

                      var disc =`<div class="text-danger text-size-large">
                                      <span class="col-md-6">Total Discount:</span>
                                      <span class="text-danger col-md-6">`+Bill_discount+`</span>
                                 </div>`;

                      $("#invoice_body").html(attach);
                      $("#invoice_footer").html(footers);
                     // $("#invoice_logo1").html(disc);
                      $('#edit_form_cont1').modal('toggle');
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                }

          }); // submit ajax


  }


  function show_payments(itm,inv_no,cust_name,total_price,net_balance,total_paid,total_remained,created,is_paid,pay_term,email,mobile,invoice_return_date,usd_rate,currency,total_discount){
              //alert(created);
              cust_name = decodeURIComponent(cust_name);
              email = decodeURIComponent(email);
              mobile = decodeURIComponent(mobile);

              $.ajax({
                    url : 'models/crul_invoice.php',
                    type : 'POST',
                    data : {type:'show_payments',id : itm},
                    dataType : 'json',
                    success : function(response) {
                      if(response!=0){


                        var customer_info ='';
                        var attach = "";
                        var footers="";
                        var Bill_totalPrice = 0;
                        var Bill_discount = 0;
                        var invoice_condition ="Not Paid";
                        if(is_paid ==1){
                          invoice_condition ="Partially Paid";
                        }else if(is_paid ==2){
                          invoice_condition ="Completly Paid";
                        }else if(is_paid ==3){
                          invoice_condition ="Returned";
                        }else if(is_paid ==4){
                          invoice_condition ="Offer";
                        }
                            customer_info =`<table width="100%">
                                                  <tr class="text-bold">
                                                      <td width="45%"><span class="text-primary">Invoice No :</span></td>
                                                      <td width="55%"><span class="text-danger" id="invoice_No_pdf_payment">`+inv_no+`</span></td>
                                                  </tr>
                                                  <tr class="text-bold">
                                                      <td width="45%"><span class="text-primary">Invoice To :</span></td>
                                                      <td width="55%"><span class="text-danger" id="invoice_No_pdf">`+cust_name+`</span></td>
                                                  </tr>
                                                  <tr class="text-bold">
                                                      <td width="45%"><span class="text-primary">Mobile :</span></td>
                                                      <td width="55%"><span class="text-danger" id="invoice_No_pdf">`+mobile+`</span></td>
                                                  </tr>
                                                  <tr class="text-bold">
                                                      <td width="45%"><span class="text-primary">Invoice Date :</span></td>
                                                      <td width="55%"><span class="text-danger" id="invoice_No_pdf">`+created+`</span></td>
                                                  </tr>
                                                  <tr class="text-black">
                                                      <td width="45%"><span class="text-primary">Invoice Status :</span></td>
                                                      <td width="55%"><span class="text-danger" id="invoice_No_pdf">`+invoice_condition+`</span></td>
                                                  </tr>
                                            </table>`;

                        $("#invoice_detials_payment").html(customer_info);
                        var total_paid_price =0;
                        for(var i=0 ; i < response.length;i++){
                          total_paid_price = +total_paid_price + +response[i][3] ;
                          attach = attach + `<tr>
                                                  <td>`+(i+1)+`</td>
                                                  <td>`+currency_format_display(response[i][3])+`</td>
                                                  <td>`+response[i][4]+`</td>
                                            </tr>`;
                        }

                          footers =`<div class="text-teal-800 text-bold text-size-large">
                                        <span class="col-md-7">Total Paid Price:</span>
                                        <span class="text-success-800 col-md-5">`+currency_format_display(total_paid_price)+`</span>
                                    </div>
                                    <div class="text-primary text-size-large">
                                        <span class="col-md-7">Net Balance:</span>
                                        <span class="text-primary-800 col-md-5">`+currency_format_display(net_balance)+`</span>
                                    </div>
                                    <div class="text-warning-800 text-size-large">
                                        <span class="col-md-7"> Remained:</span>
                                        <span class="text-warning-800 col-md-5">`+currency_format_display(total_remained)+`</span>
                                    </div>`;



                          $("#invoice_body_payment").html(attach);
                          $("#invoice_footer_payment").html(footers);
                          $('#show_payments_modal').modal('toggle');
                        }else{
                          noty({
                                   width: 200,
                                   text: 'This Invoice has no Payments yet! or something went wrong',
                                   type: 'error',
                                   dismissQueue: true,
                                   timeout: 3000,
                                   layout: 'top',
                             });
                        }
                    },
                    complete: function() {
                           //  me.data('requestRunning', false);
                    }

              }); // submit ajax


  }

  function add_payments(itemid){
    $("#itemid_payment").val(itemid);
    $('#add_payments_modal').modal('toggle');
  }

 // use in datatable action Edit invoice sub menu
  function edit_payments(itm,inv_no,cust_name,total_price,net_balance,total_paid,total_remained,created,is_paid,pay_term,email,mobile,invoice_return_date,usd_rate,currency,total_discount){
    //first we should get inovice and payment ids so we should call payment show

    cust_name = decodeURIComponent(cust_name);
    email = decodeURIComponent(email);
    mobile = decodeURIComponent(mobile);

    $.ajax({
                    url : 'models/crul_invoice.php',
                    type : 'POST',
                    data : {type:'show_payments',id : itm},
                    dataType : 'json',
                    success : function(response) {
                      if(response!=0){
                        var attach ='';
                        for(var i=0 ; i < response.length;i++){

                          attach = attach + `<div id="payment_row`+(i+1)+`">
                                                  <div class="form-group has-feedback has-feedback-left form-group-material col-sm-5">
                                                       <label class="control-label animate is-visible">Payment Amount</label>
                                                       <input type="text" id="paid_price`+(i+1)+`" name="paid_price`+(i+1)+`" class="form-control" placeholder="Payment Amount" required="required" value="`+currency_format(response[i][3])+`">
                                                       <div class="form-control-feedback"><i class="icon-cash text-muted"></i></div>
                                                       <input type="hidden" id="invoice_id_pay`+(i+1)+`" name="invoice_id_pay`+(i+1)+`" value="`+response[i][5]+`">
                                                       <input type="hidden" id="payment_id`+(i+1)+`" name="payment_id`+(i+1)+`" value="`+response[i][0]+`">
                                                  </div>
                                                  <div class="form-group has-feedback has-feedback-left form-group-material col-sm-5">
                                                       <label class="control-label animate is-visible">Payment Date</label>
                                                       <input type="text" id="payment_date`+(i+1)+`" name="payment_date`+(i+1)+`" class="form-control" placeholder="Payment Date" value="`+response[i][4]+`" readonly>
                                                       <div class="form-control-feedback"><i class="icon-calendar3 text-muted"></i></div>
                                                  </div>
                                                  <div class="form-group has-feedback has-feedback-left form-group-material col-sm-2" >
                                                       <a id="save_payment_btn" class="btn btn-primary" style="margin-top: 25px;" onclick="update_payments(`+(i+1)+`,`+response[i][0]+`,`+response[i][5]+`)" data-popup="tooltip" data-original-title="Save Changes">
                                                          <i class="icon-floppy-disk"></i>
                                                       </a>
                                                       <a id="remove_payment_btn" class="btn btn-danger" style="margin-top: 25px;" onclick="remove_payments(`+(i+1)+`,`+response[i][0]+`,`+response[i][5]+`)" data-popup="tooltip" data-original-title="Delete Payment">
                                                          <i class="icon-x"></i>
                                                       </a>
                                                    </div>
                                              </div>`;
                        }
                        $("#edit_payments_fields").html(attach);
                        }else{
                          noty({
                                   width: 200,
                                   text: response.message,
                                   type: 'error',
                                   dismissQueue: true,
                                   timeout: 3000,
                                   layout: 'top',
                             });
                        }
                    },
                    complete: function() {
                           //  me.data('requestRunning', false);
                    }

              }); // submit ajax

    $("#itemid_invoice").val(itm);

    $('#edit_payments_modal').modal('toggle');

  }

  function remove_payments(itemid,paymentid,invid,control=''){

      swal({
          title: "Are you sure?",
          text: "You will not be able to recover this Payment!",
          type: "warning",
          showCancelButton: true,
          confirmButtonColor: "#EF5350",
          confirmButtonText: "Yes, delete it!",
          cancelButtonText: "No, cancel",
          closeOnConfirm: true,
          closeOnCancel: true
      },
      function(isConfirm){
          if (isConfirm) {

              $.ajax({
                   url : 'models/crul_invoice.php',
                   type : 'POST',
                   data : {type:'delete_payments',id:paymentid,invid:invid},
                   dataType : 'json',
                   success : function(response) {
                     if(response!= 1) {
                       noty({
                             width: 200,
                             text: response.message,
                             type: 'error',
                             dismissQueue: true,
                             timeout: 3000,
                             layout: 'top',
                       });

                     }else{
                       $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                       $("#"+control+"payment_row"+itemid).html('');
                       //$('#edit_payments_modal').modal('toggle');
                       noty({
                             width: 200,
                             text: 'Payment Successfully Deleted',
                             type: 'success',
                             dismissQueue: true,
                             timeout: 3000,
                             layout: 'topRight',
                       });

                     }
                   },
                   complete: function() {
                          //  me.data('requestRunning', false);
                   }

             }); // submit ajax


          }
      }); // /confirm
  }

 /// for Edit all invoice 
  function update_payments(itemid,paymentid,invid,control=''){

        var paid_price = $("#"+control+"paid_price"+itemid).val();
        paid_price = paid_price.replace('$','');
        $.ajax({
              url : 'models/crul_invoice.php',
              type : 'POST',
              data : {type:'update_payments',id:paymentid,invid:invid,paid_price:paid_price},
              dataType : 'json',
              success : function(response) {
                if(response!= 1) {
                  noty({
                        width: 200,
                        text: response.message,
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'top',
                  });

                } else {
                  $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                  if(control !='edit_'){
                    $('#edit_payments_modal').modal('toggle');
                  }else{
                    // we should update total_paid
                    
                    var total_paid_after_update =0;
                    $("input[id^='edit_paid_price']").each(function() {
                         var cur_pay = $(this).val();
                         cur_pay = cur_pay.replace('$','');
                         total_paid_after_update = +total_paid_after_update + +cur_pay;

                      });
                    $('#edit_total_paid').val(currency_format( total_paid_after_update));
                  }
                  
                  noty({
                        width: 200,
                        text: 'Payment Successfully Updated',
                        type: 'success',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'topRight',
                  });

                }
              },
              complete: function() {
                     //  me.data('requestRunning', false);
              }

        }); // submit ajax

  }

  Date.dateDiff = function(datepart, fromdate, todate) {
    datepart = datepart.toLowerCase();
    var diff = todate - fromdate;
    var divideBy = { w:604800000,
                     d:86400000,
                     h:3600000,
                     n:60000,
                     s:1000 };

    return Math.floor( diff/divideBy[datepart]);
  }

  function add_fields_btn_edit() {
          
          var cunt = $("#edit_field_counter").val();

          var eventsAll = ` onchange="calculate_price_edit();"   onkeyup="this.onchange();" onkeypress="this.onchange();"  onpaste="this.onchange();" oninput="this.onchange();" onkeydown="this.onchange();"  `;

          var newField = `<div class="form-group " id="edit_field_`+cunt+`" >
                            <div class="form-group form-group-material col-sm-2">
                                <label class="control-label animate">Product Name</label>
                                <select name="edit_product_id`+cunt+`" id="edit_product_id`+cunt+`" class="form-control" `+eventsAll+`>
                                    <option value="" selected="selected">Product Name</option>
                                </select>
                            </div>
                            <div class="form-group form-group-material col-sm-3">
                                <label class="control-label has-margin is-visible">Quantity
                                  <label class="badge badge-success position-right" id="edit_qty_store`+cunt+`" style="margin-left: 40px; margin-bottom: auto;">Total Quantity In Store</label>
                                </label>
                                <input type="text" id="edit_quantity`+cunt+`" name="edit_quantity`+cunt+`" value="1" class="touchspin-basic" placeholder="Quantity" required="required" `+eventsAll+`>
                            </div>
                            <div class="form-group has-feedback has-feedback-left form-group-material col-sm-2">
                                <label class="control-label is-visible">Unit Price</label>
                                <input type="text" id="edit_unit_price`+cunt+`" name="edit_unit_price`+cunt+`" value="" class="form-control" placeholder="Unit Price" readonly>
                                <div class="form-control-feedback">   <i class=" icon-cash text-muted"></i>  </div>
                            </div>
                            <div class="form-group has-feedback has-feedback-left form-group-material col-sm-1">
                                 <label class="control-label is-visible">Discount</label>
                                 <input type="text" id="edit_discount`+cunt+`" name="edit_discount`+cunt+`" value="" class="form-control" placeholder="Discount" `+eventsAll+` >
                                 <div class="form-control-feedback"> <i class="icon-price-tag text-muted"></i></div>
                            </div>
                            <input type="hidden" id="edit_product_avg_price`+cunt+`" name="edit_product_avg_price`+cunt+`" value="" readonly >
                            <div class="form-group has-feedback has-feedback-left form-group-material col-sm-2">
                                 <label class="control-label is-visible">Totals</label>
                                 <input type="text" id="edit_totals`+cunt+`" name="edit_totals`+cunt+`" class="form-control" placeholder="Totals" readonly >
                                 <div class="form-control-feedback">  <i class="icon-coins text-muted"></i> </div>
                            </div>
                            <div class="form-group has-feedback  col-sm-2" style="font-size: xx-small;">
                                
                                <a id="edit_remove_fields_btn" class="btn btn-danger btn-xs" style="margin-top: 25px; font-size: xx-small;" onclick="remove_edit_field(`+cunt+`)">
                                  <i class="icon-x"></i>
                                </a>
                                <span id="edit_add_fields_btn" class="btn btn-info btn-xs" style="margin-top:25px; font-size: xx-small;" onclick="add_fields_btn_edit();">
                                  <i class="icon-plus22"></i>
                                </span>
                            </div>
                        </div>`;

          

          $("#edit_products_array_div").append(newField);
          $("#edit_product_id"+cunt).html($("#product_id_store").html());
          //$("#edit_product_id"+cunt).val(response.sell[i][5]);
          $("#edit_product_id"+cunt).selectpicker('refresh');
          $(".touchspin-basic").TouchSpin({
               min: 1,
               max: 100000,
               step: 1
          });
          

          cunt = +cunt +1;
          $("#edit_field_counter").val(cunt);


    }

$(document).ready(function() {
    
    $( "div[id^='products_array_div']" ).on('change',"select[id^='product_id']",function(){
      get_Products_Price();
      //alert("cc")
    });

    $( "div[id^='edit_products_array_div']" ).on('change',"select[id^='edit_product_id']",function(){
     // get_Products_Price();
      //alert("cc")
    });

    get_Products();

    $("#edit_form_cont").on("hidden.bs.modal", function () {
    
      get_Products();
    });

    $("#edit_btn_cancel").on('click',function(){
    
      get_Products();
    });

    $('#add_fields_btn').click(function() {

           var cunt = $("#field_counter").val();

           var eventsAll = ` onchange="calculate_price();" onfocusout="this.onchange();" onblur="this.onchange();" onkeyup="this.onchange();" onkeypress="this.onchange();" onclick="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();" onkeydown="this.onchange();" onmousedown="this.onchange();" onmouseenter="this.onchange();" `;

           var newField = `<div class="form-group " id="field_`+cunt+`" >
                              <div class="form-group form-group-material col-sm-3">
                                  <label class="control-label animate">Product Name</label>
                                  <select name="product_id`+cunt+`" id="product_id`+cunt+`" class="form-control" `+eventsAll+`>
                                      <option value="" selected="selected">Product Name</option>
                                  </select>
                              </div>
                              <div class="form-group form-group-material col-sm-3">
                                  <label class="control-label has-margin is-visible">Quantity
                                    <label class="badge badge-success position-right" id="qty_store`+cunt+`" style="margin-left: 40px; margin-bottom: auto;">Total Quantity In Store</label>
                                  </label>
                                  <input type="text" id="quantity`+cunt+`" name="quantity`+cunt+`" value="1" class="touchspin-basic" placeholder="Quantity" required="required" `+eventsAll+`>
                              </div>
                              <div class="form-group has-feedback has-feedback-left form-group-material col-sm-2">
                                  <label class="control-label is-visible">Unit Price</label>
                                  <input type="text" id="unit_price`+cunt+`" name="unit_price`+cunt+`" class="form-control" placeholder="Unit Price" readonly>
                                  <div class="form-control-feedback">   <i class=" icon-cash text-muted"></i>  </div>
                              </div>
                              <div class="form-group has-feedback has-feedback-left form-group-material col-sm-1">
                                   <label class="control-label">Discount</label>
                                   <input type="text" id="discount`+cunt+`" name="discount`+cunt+`" class="form-control" placeholder="Discount" `+eventsAll+` >
                                   <div class="form-control-feedback"> <i class="icon-price-tag text-muted"></i></div>
                              </div>
                              <input type="hidden" id="product_avg_price`+cunt+`" name="product_avg_price`+cunt+`" readonly >
                              <div class="form-group has-feedback has-feedback-left form-group-material col-sm-2">
                                   <label class="control-label">Totals</label>
                                   <input type="text" id="totals`+cunt+`" name="totals`+cunt+`" class="form-control" placeholder="Totals" readonly >
                                   <div class="form-control-feedback">  <i class="icon-coins text-muted"></i> </div>
                              </div>
                              <div class="form-group has-feedback  col-sm-1">
                                   <a id="remove_fields_btn" class="btn btn-danger" style="margin-top: 25px;" onclick="remove_field(`+cunt+`)">
                                      <i class="icon-x"></i>
                                   </a>
                              </div>
                          </div>`;
           $("#products_array_div").append(newField);
           $("#product_id"+cunt).html($("#product_id_store").html());
           $("#product_id"+cunt).selectpicker('refresh');
           $(".touchspin-basic").TouchSpin({
                 min: 1,
                 max: 100000,
                 step: 1
             });

             cunt = +cunt +1;
             $("#field_counter").val(cunt);

         //  alert(cunt)

    });

    
    

    $('#pdf').click(function() {
         print_invoice('PDF');
    });

    $('#print').click(function() {
         print_invoice('Print');
    });

    $('#pdf_pay').click(function() {
         print_invoice('PDF','pay');
    });

    $('#print_pay').click(function() {
         print_invoice('Print','pay');
    });

    $("#product_id").on('change',function(){
       // alert("CC")
        var productID = $("#product_id").val();

        for(var j=0 ; j< products_array_values.length; j++ ){
         if(productID == products_array_values[j]['id']){

            var sellPrice    = products_array_values[j]['sell_price'];
            var sellPricePer = products_array_values[j]['sell_price_percentage'];
            var avgPrice     = products_array_values[j]['average_price'];
            var oldtotalQty  = products_array_values[j]['remained_quantity'];

            if(sellPrice == null){
              sellPrice = '';
            }

            if(sellPricePer == null){
              sellPricePer = '';
            }

            if(avgPrice == null){
              avgPrice = '';
            }
            if(oldtotalQty == null){
              oldtotalQty = '';
            }



            $("#sell_price").val(sellPrice);
            $("#sell_price_percentage").val(sellPricePer);
            $("#average_price_old").val(avgPrice);
            $("#total_quantity_old").val(oldtotalQty);

            if(products_array_values[j]['category_type']==1){ // outcome
              $("#sell_price").prop('disabled', true);
              $("#sell_price_percentage").prop('disabled', true);
            }else{
              $("#sell_price").prop('disabled', false);
              $("#sell_price_percentage").prop('disabled', false);
            }

         }
      }
    });

    $("#edit_product_id").on('change',function(){

          var productID = $("#edit_product_id").val();

          for(var j=0 ; j< products_array_values.length; j++ ){
             if(productID == products_array_values[j]['id']){

                var sellPrice    = products_array_values[j]['sell_price'];
                var sellPricePer = products_array_values[j]['sell_price_percentage'];
                var avgPrice     = products_array_values[j]['average_price'];
                var oldtotalQty  = products_array_values[j]['remained_quantity'];
                // because we didnt have it in table so we cant set it in edit_items we will set it from here
                $("#edit_average_price_old").val(avgPrice);
                $("#edit_quantity_save").val(oldtotalQty);



                //
                if(sellPrice == null){
                  sellPrice = '';
                }

                if(sellPricePer == null){
                  sellPricePer = '';
                }

                if(avgPrice == null){
                  avgPrice = '';
                }
                if(oldtotalQty == null){
                  oldtotalQty = '';
                }



                $("#edit_sell_price").val(sellPrice);
                $("#edit_sell_price_percentage").val(sellPricePer);
                $("#edit_average_price_old").val(avgPrice);
                $("#edit_total_quantity_old").val(oldtotalQty);
                $('#edit_average_price_old_prev').val(avgPrice);

             }
          }
    });

    $("#edit_form_cancel_btn").click(function(event) {
        $("#edit-form-cont").collapse('hide');
        $("#edit_form")[0].reset();
    });

    $("#conform_panel_cancel_btn").click(function(event) {
        $("#confirm-form-cont").collapse('hide');
        $("#confirm_form")[0].reset();
    });

    $('#add_form').submit(function(event) {
          event.preventDefault();
              // block
              //alert("ooo")
          block = $(this).parent();
              // \block

          var cnt               = $("#field_counter").val();
          var Bill_total        = 0;
          var product_id_array  =[];
          var quantity_array    =[];
          var discount_array    =[];
          var unit_price_array  =[];
          var product_avg_price =[];
          var check_products    =[];
          var check_quantity    =[];
          var k=0;

          for(var i =1; i < cnt; i++){

              var productID     = $("#product_id"+i).val();
              var quantityField = $("#quantity"+i).val();
              var discountField = $("#discount"+i).val();
              var unit_price    = $("#unit_price"+i).val();
              var avge_price    = $("#product_avg_price"+i).val();

              if(productID != undefined && productID != null ){
                check_products[k]   = Checks('product_id'+i,'No',1);
                check_quantity[k]   = Checks('quantity'+i,'No',1);
                //console.log(check_quantity)
                product_id_array[k] = productID;
                quantity_array[k]   = quantityField;
                discount_array[k]   = discountField;
                product_avg_price[k]= avge_price;
                unit_price_array[k] = unit_price.replace('$','');
                k++;
              }
          }
          var customer_name  = $("#customer_name1").val();
          var pay_term       = $("#pay_term").val();
          var customer_type  = $("#customer_type").val();
          var customer_id    = $("#customer_id").val();
          var net_balance    = $("#net_balance").val();
          var total_paid     = $("#total_paid").val();
          var total_invoice  = $("#total_invoice").val();
          var is_offer       = 0;
          if ($('#is_offer').is(":checked")){
              is_offer = 1;
          }

          total_invoice = total_invoice.replace('$','');
          net_balance   = net_balance.replace('$','');
          var Check1    = Checks('customer_name1');
          var Check2    = Checks('pay_term');
          var Check3    = Checks('customer_type');
          var Check4    = Checks('net_balance');
          var CheckPro  = true;
          var checkQty  = true;

          for(m=0;m<check_products.length;m++){

            if(check_products[m]==false){
              CheckPro = false;
            }
            if(check_quantity[m]==false){
              checkQty = false;
            }

          }


          if(Check1 && Check2 && Check3 && Check4 && CheckPro && checkQty){
              $("#submit_add_btn").attr('disabled',true);
              $.ajax({
                  url: "models/crul_invoice.php",
                  type:"POST",

                  data : {product_id:product_id_array,quantity:quantity_array,customer_id:customer_id,pay_term:pay_term,
                          customer_type:customer_type,net_balance:net_balance,total_paid:total_paid,total_invoice:total_invoice,discount:discount_array,
                          is_offer:is_offer,unit_price:unit_price_array,product_avg_price:product_avg_price,type:'create'}
              })
              .done(function(res) {
                  //alert(res);
                  if(res == 0){
                      swal({
                          title:"Error",
                          text: "Please Refresh the page and try again.",
                          confirmButtonColor: "#66BB6A",
                          type: "warning"
                      });
                      $("#add-form-cont").collapse('hide');
                  }
                  else if(res == 1){
                      $("#add_form")[0].reset();
                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                      get_Products();
                      $("#add-form-cont").collapse('hide');
                      noty({
                                      width: 200,
                                      text: 'Invoice Successfully Added',
                                      type: 'success',
                                      dismissQueue: true,
                                      timeout: 3000,
                                      layout: 'topRight',
                                });
                  }else{
                      swal({
                          title: "Error",
                          text: "Detail:"+res,
                          confirmButtonColor: "#66BB6A",
                          type: "error"
                      });
                  }
                  $("#submit_add_btn").attr('disabled',false);
              })
              .fail(function(err) {
                   swal({
                      title: "Error",
                      text: "Detail:"+err,
                      confirmButtonColor: "#66BB6A",
                      type: "error"
                  });
                  $("#submit_add_btn").attr('disabled',false);
              })
              .always(function() {
                  console.log("complete");
              });
          }

    });

    // submit editable Visa Application form
    $('#edit_form').submit(function(event) {
          event.preventDefault();
          // block

          block = $(this).parent();
              // \block
          var obj_id            = $("#edit_objid").val();
          var cnt               = $("#edit_field_counter").val();
          var Bill_total        = 0;
          var product_id_array  =[];
          var quantity_array    =[];
          var discount_array    =[];
          var unit_price_array  =[];
          var product_avg_price =[];
          var check_products    =[];
          var check_quantity    =[];
          var k=0;

          for(var i =1; i < cnt; i++){

              var productID     = $("#edit_product_id"+i).val();
              var quantityField = $("#edit_quantity"+i).val();
              var discountField = $("#edit_discount"+i).val();
              var unit_price    = $("#edit_unit_price"+i).val();
              var avge_price    = $("#edit_product_avg_price"+i).val();

              if(productID != undefined && productID != null ){
                check_products[k]   = Checks('edit_product_id'+i,'No',1);
                check_quantity[k]   = Checks('edit_quantity'+i,'No',1);
                //console.log(check_quantity)
                product_id_array[k] = productID;
                quantity_array[k]   = quantityField;
                discount_array[k]   = discountField;
                product_avg_price[k]= avge_price;
                unit_price_array[k] = unit_price.replace('$','');
                k++;
              }
          }
          var customer_name  = $("#edit_customer_name1").val();
          var pay_term       = $("#edit_pay_term").val();
          var customer_type  = $("#edit_customer_type").val();
          var customer_id    = $("#edit_customer_id").val();
          var net_balance    = $("#edit_net_balance").val();
          var total_paid     = $("#edit_total_paid").val();
          var total_invoice  = $("#edit_total_invoice").val();
          var is_offer       = 0;
          if ($('#edit_is_offer').is(":checked")){
              is_offer = 1;
          }

          total_invoice = total_invoice.replace('$','');
          net_balance   = net_balance.replace('$','');
          total_paid    = total_paid.replace('$','');
          var Check1    = Checks('edit_customer_name1');
          var Check2    = Checks('edit_pay_term');
          var Check3    = Checks('edit_customer_type');
          var Check4    = Checks('edit_net_balance');
          var CheckPro  = true;
          var checkQty  = true;

          for(m=0;m<check_products.length;m++){

            if(check_products[m]==false){
              CheckPro = false;
            }
            if(check_quantity[m]==false){
              checkQty = false;
            }

          }


          if(Check1 && Check2 && Check3 && Check4 && CheckPro && checkQty){
              $.ajax({
                  url: "models/crul_invoice.php",
                  type:"POST",
                  data : {obj_id:obj_id,product_id:product_id_array,quantity:quantity_array,customer_id:customer_id,pay_term:pay_term,
                          customer_type:customer_type,net_balance:net_balance,total_paid:total_paid,total_invoice:total_invoice,discount:discount_array,
                          is_offer:is_offer,unit_price:unit_price_array,product_avg_price:product_avg_price,type:'update'}
              })
              .done(function(res) {
                  //alert(res);
                  if(res == 0){
                      swal({
                          title:"Error",
                          text: "Please Refresh the page and try again.",
                          confirmButtonColor: "#66BB6A",
                          type: "warning"
                      });
                      $('#edit_form_cont').modal('toggle');
                  }
                  else if(res == 1){
                      $("#edit_form")[0].reset();
                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                      get_Products();
                      $('#edit_form_cont').modal('toggle');
                      noty({
                                      width: 200,
                                      text: 'Invoice Successfully Updated',
                                      type: 'success',
                                      dismissQueue: true,
                                      timeout: 3000,
                                      layout: 'topRight',
                                });
                  }else{
                      swal({
                          title: "Error",
                          text: "Detail:"+res,
                          confirmButtonColor: "#66BB6A",
                          type: "error"
                      });
                  }
              })
              .fail(function(err) {
                   swal({
                      title: "Error",
                      text: "Detail:"+err,
                      confirmButtonColor: "#66BB6A",
                      type: "error"
                  });
              })
              .always(function() {
                  console.log("complete");
              });
          }


    });

    $('#invoice_form').on('submit', function(e){
      e.preventDefault();
    });

    $('#show_payments_form').on('submit', function(e){
      e.preventDefault();
    });


    $('#add_payments_form').on('submit', function(e){
          e.preventDefault();

          var catId          = $("#itemid_payment").val();
          var paid_price  = $("#paid_price").val();

          var Check1   = Checks('paid_price','No');



          if(Check1 ){
            $("#submit_add_pay_btn").attr('disabled',true);
            $.ajax({
                  url : 'models/crul_invoice.php',
                  type : 'POST',
                  data : {type:'add_payments',id : catId,paid_price:paid_price}
                })
                .done(function(res) {
                    //alert(res);
                    if(res == 1){
                      $("#add_payments_form")[0].reset();
                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                      get_Products();
                      $('#add_payments_modal').modal('toggle');
                      noty({
                                        width: 200,
                                        text: 'Payment Successfully Added',
                                        type: 'success',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'topRight',
                                  });
                    }else{
                        swal({
                            title: "Error",
                            text: "Detail:"+res,
                            confirmButtonColor: "#66BB6A",
                            type: "error"
                        });
                    }
                    $("#submit_add_pay_btn").attr('disabled',false);
                }); // submit ajax
          }else{
                noty({
                          width: 200,
                          text: 'Enter Required Feilds!!',
                          type: 'error',
                          dismissQueue: true,
                          timeout: 3000,
                          layout: 'top',
                    });
          }

    });

    function PrintDiv(path) {
            printJS(path);
    }



    function print_invoice(typ,payment=null){


          var INV_NO           = $("#invoice_No_pdf").html();
          var HTML             = $("#invoce_html").html();
          if(payment !=null){ // to print invoice payments
            INV_NO           = $("#invoice_No_pdf_payment").html();
            HTML             = $("#invoce_html_pay").html();
          }

          HTML                 = HTML.replace('image/sys','../image/sys');
          INV_NO               = INV_NO.trim();
          HTML = `<!DOCTYPE html>
                            <html lang="en">
                                  <head>
                                       <meta charset="utf-8">
                                       <meta http-equiv="X-UA-Compatible" content="IE=edge">
                                       <meta name="viewport" content="width=device-width, initial-scale=1">
                                       <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,100,500,700,900" rel="stylesheet" type="text/css">
                                       <link href="../assets/css/icons/icomoon/styles.css" rel="stylesheet" type="text/css">
                                       <link href="../assets/css/bootstrap.css" rel="stylesheet" type="text/css">
                                       <link href="../assets/css/core.css" rel="stylesheet" type="text/css">
                                       <link href="../assets/css/components.css" rel="stylesheet" type="text/css">
                                       <link href="../assets/css/colors.css" rel="stylesheet" type="text/css">
                                       <script type="text/javascript" src="../assets/js/plugins/loaders/pace.min.js"></script>
                                       <script type="text/javascript" src="../assets/js/core/libraries/jquery.min.js"></script>
                                       <script type="text/javascript" src="../assets/js/core/libraries/bootstrap.min.js"></script>
                                       <script type="text/javascript" src="../assets/js/plugins/loaders/blockui.min.js"></script>
                                       <script type="text/javascript" src="../assets/js/plugins/ui/nicescroll.min.js"></script>
                                       <script type="text/javascript" src="../assets/js/plugins/ui/drilldown.js"></script>
                                       <script type="text/javascript" src="../assets/js/core/app.js"></script>
                                       <script type="text/javascript" src="../assets/js/pages/components_popups.js"></script>
                                       <script type="text/javascript" src="../assets/js/plugins/ui/ripple.min.js"></script>
                                  </head>
                                  <body>
                                        <div class="page-container">
                                            <div class="page-content">
                                                <div class="content-wrapper">
                                                    <style>
                                                        body {background-color: #fff !important;}
                                                        thead  tr {background-color: darkgrey !important;}
                                                        .table > thead > tr > th {line-height: 2.538462 !important;}
                                                        .inv_body_hdr th{background: #444 !important;}
                                                        .inv_body_hdr th{ color: #fff;  padding: 10px 10px;  }
                                                        #invoice_body tr td{ padding: 20px 10px !important;}
                                                        #invoice_footer div span{ padding: 10px 10px;}
                                                    </style>` + HTML + `
                                                </div>
                                           </div>
                                        </div>
                                    </body>
                            </html>`;


                console.log(HTML);
                $("#pdf").attr('disabled',true);
                $("#pdf_pay").attr('disabled',true);
                $("#print").attr('disabled',true);
                $("#print_pay").attr('disabled',true);
                $.ajax({
                      url : 'models/crul_invoice.php',

                      type : 'POST',
                      data : {type:typ,html:HTML,inv_no:INV_NO,pay:payment},
                      dataType : 'json',
                      success : function(response) {
                            console.log(response)
                            if(response.is_success == true) {

                                  if(typ=='Print'){
                                    PrintDiv(response.data);
                                  }else{
                                    noty({
                                        width: 200,
                                        text: 'PDF Generated Successfully',
                                        type: 'success',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'top',
                                    });
                                    var LINKS = '<a class="btn btn-labeled btn-labeled-left heading-btn btn-info" href="'+response.data+'" style="float: left;"> Download <b><i class="icon-file-download"></i></b> </a>';
                                    if(payment !=null){
                                      $("#link_pdf_pay").append(LINKS);
                                    }else{
                                      $("#link_pdf").append(LINKS);
                                    }

                                  }
                                  $("#pdf").attr('disabled',false);
                                  $("#pdf_pay").attr('disabled',false);
                                  $("#print").attr('disabled',false);
                                  $("#print_pay").attr('disabled',false);
                            } else {

                               noty({
                                     width: 200,
                                     text: response.message,
                                     type: 'error',
                                     dismissQueue: true,
                                     timeout: 3000,
                                     layout: 'top',
                               });

                                  $("#pdf").attr('disabled',false);
                                  $("#pdf_pay").attr('disabled',false);
                                  $("#print").attr('disabled',false);
                                  $("#print_pay").attr('disabled',false);
                            }
                      },
                      complete: function() {
                            //   me.data('requestRunning', false);
                      }

                }); // submit ajax


    }



});





$(function() {
//var singleSelect = $('.datatable-column-search-inputs').DataTable();
  /*$("#spinner-currency").spinner({
        start: 1000,
        numberFormat: "C",

    });
  $("#spinner-currency").spinner("option", "culture", 'en-US');*/

  $(".touchspin-basic").TouchSpin({
        min: 1,
        max: 100000,
        step: 1,
        //postfix: '<i class="icon-paragraph-justify2"></i>'
    });

  $('.daterange-single').daterangepicker({ 
        singleDatePicker: true,
        locale: {
            format: 'YYYY-MM-DD'
        }
    });


   // Setting datatable defaults
    $.extend( $.fn.dataTable.defaults, {
        autoWidth: false,
        columnDefs: [{ 
            orderable: false,
            width: '100px',
            targets: [ 9 ]
        }],
        dom: '<"datatable-header"fBl><"datatable-scroll"t><"datatable-footer"ip>',
        language: {
            search: '<span>Filter:</span> _INPUT_',
            searchPlaceholder: 'Type to filter...',
            lengthMenu: '<span>Show:</span> _MENU_',
            paginate: { 'first': 'First', 'last': 'Last', 'next': '&rarr;', 'previous': '&larr;' }
        },
        drawCallback: function () {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
        },
        preDrawCallback: function() {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
        }
    });


    

    // Individual column searching with text inputs
    $('.datatable-column-search-inputs tfoot td').not(':last-child').each(function () {
        var title = $('.datatable-column-search-inputs thead th').eq($(this).index()).text();
        $(this).html('<input type="text" class="form-control input-sm" placeholder="Search '+title+'" />');
    });
    
    

   var query_id = getQueryVariable("id");
   var query_ip = getQueryVariable("ip");
   var query_pt = getQueryVariable("pt");

   var table = $('.datatable-column-search-inputs').DataTable({
         

        "processing": true,
        "serverSide": true,
        "ajax": {
        "url" : "models/crul_invoice.php",
        "data": function(d){
          d.type = "load";
          if(query_id !='not'){
            d.id =query_id ;
          }else if(query_ip !='not' && query_pt !='not'){
            d.ip =query_ip ; // is paid
            d.pt =query_pt ; // pay term
          }else if(query_ip !='not'){
            d.ip =query_ip ; // is paid
          }
        }
        },
        drawCallback: function() {
                  $('[data-popup=tooltip]').tooltip();
                  $('[data-popup=popover-custom]').popover({
                    template: '<div class="popover  border-teal-400"><div class="arrow"></div><h3 class="popover-title bg-teal-400"></h3><div class="popover-content"></div></div>'
                  });

            },
        "columnDefs": [
          {
              "targets": 9,
              "data": null,
              "render": function (data,type,row) {

                            return  `<ul class='icons-list pull-right'>
                                          <li class='text-primary-600'>
                                              <a href='#' class='text-success-400' onclick="show_invoice(`+row[0]+`,'`+row[1]+`','`+escape(row[2])+`','`+row[3]+`','`+row[4]+`','`+row[5]+`','`+row[6]+`','`+row[7]+`','`+row[8]+`','`+row[9]+`','`+escape(row[10])+`','`+escape(row[11])+`','`+row[14]+`','`+row[15]+`','`+row[16]+`','`+row[17]+`')" data-popup='tooltip' data-original-title='Show Invoice Details'>
                                                  <i class='icon-calculator'></i>
                                              </a>
                                          </li>

                                          <li class='text-primary-600'>
                                              <a href='#' class='text-primary-400' onclick="edit_items(`+row[0]+`,'`+row[1]+`','`+escape(row[2])+`','`+row[3]+`','`+row[4]+`','`+row[5]+`','`+row[6]+`','`+row[7]+`','`+row[8]+`','`+row[9]+`','`+escape(row[10])+`','`+escape(row[11])+`','`+row[14]+`','`+row[15]+`','`+row[16]+`','`+row[17]+`','`+row[12]+`')" data-popup='tooltip' data-original-title='Edit'>
                                                  <i class='icon-pencil7'></i>
                                              </a>
                                          </li>
                                          <li class='text-danger-600'>
                                              <a href='#' class='text-danger-400' onclick="delete_items(`+row[0]+`,'`+row[1]+`')" data-popup='tooltip' data-original-title='Remove'>
                                                  <i class='icon-trash'></i>
                                              </a>
                                          </li>

                                          <li class="dropdown">
                                              <a href="#" class="dropdown-toggle" data-toggle="dropdown" data-popup='tooltip' data-original-title=' Invoice Payments Details'>
                                                <i class="icon-menu9"></i>
                                              </a>

                                              <ul class="dropdown-menu dropdown-menu-right">
                                                <li>
                                                  <a href='#' onclick="show_payments(`+row[0]+`,'`+row[1]+`','`+escape(row[2])+`','`+row[3]+`','`+row[4]+`','`+row[5]+`','`+row[6]+`','`+row[7]+`','`+row[8]+`','`+row[9]+`','`+escape(row[10])+`','`+escape(row[11])+`','`+row[14]+`','`+row[15]+`','`+row[16]+`','`+row[17]+`')" data-popup='tooltip' data-original-title='Show Invoice Payments'>
                                                    <i class='icon-coins text-info-400'></i> Payments Details
                                                  </a>
                                                </li>
                                                <li>
                                                  <a href='#' onclick="add_payments(`+row[0]+`,`+row[4]+`,`+row[6]+`,'`+row[7]+`','`+escape(row[11])+`','`+row[12]+`')" data-popup='tooltip' data-original-title='Add New Payments to this Invoice'>
                                                    <i class='icon-cash text-primary-600'></i> Add New Payment
                                                  </a>
                                                </li>
                                                <li>
                                                  <a href='#' onclick="edit_payments(`+row[0]+`,'`+row[1]+`','`+escape(row[2])+`','`+row[3]+`','`+row[4]+`','`+row[5]+`','`+row[6]+`','`+row[7]+`','`+row[8]+`','`+row[9]+`','`+escape(row[10])+`','`+escape(row[11])+`','`+row[14]+`','`+row[15]+`','`+row[16]+`','`+row[17]+`','`+row[12]+`')" data-popup='tooltip' data-original-title='Edit or Remove Invoice Payments'>
                                                    <i class='icon-pencil5 text-teal-600'></i> Edit Payments
                                                  </a>
                                                </li>

                                              </ul>
                                            </li>
                                      </ul>`;
                        }
          },
          {
             "render": function(data, type, row){


                      return  `<a href='#' onclick="show_invoice(`+row[0]+`,'`+row[1]+`','`+escape(row[2])+`','`+row[3]+`','`+row[4]+`','`+row[5]+`','`+row[6]+`','`+row[7]+`','`+row[8]+`','`+row[9]+`','`+escape(row[10])+`','`+escape(row[11])+`','`+row[14]+`','`+row[15]+`','`+row[16]+`','`+row[17]+`')"  data-popup='tooltip' data-original-title='Invoice Number'>`+data+`</a>`;


             },
             "targets": 1
          },
          {
             "render": function(data, type, row){


                      return  `<a href='index.php?p=invoice&id=`+row[12]+`'  data-popup='tooltip' data-original-title='Show All Invoices For This Customer'>`+data+`</a>`;


             },
             "targets": 2
          },

          {
              "render": function(data, type, row){

                  return currency_format_display(data);
              },
              "targets": 3
          },
          {
              "render": function(data, type, row){

                  return currency_format_display(data);
              },
              "targets": 4
          },
          {
              "render": function(data, type, row){

                  return currency_format_display(data);
              },
              "targets": 5
          },
          {
              "render": function(data, type, row){

                  return currency_format_display(data);
              },
              "targets": 6
          },
          // {
          //     "render": function(data, type, row){
          //         var status ='';
          //
          //         if(data ==0){
          //             status = '<span class="label label-danger btn-block "> Not Paid </span>';
          //         }else if(data ==1){
          //             status = '<span class="label label-info btn-block "> partially Paid </span>';
          //         }else if(data ==2){
          //            status = '<span class="label label-success btn-block "> Paid </span>';
          //        }else if(data ==3){
          //            status = '<span class="label label-primary btn-block "> Returned </span>';
          //        }else{
          //          status ="";
          //        }
          //         return status;
          //     },
          //     "targets": 8
          // },


            {
                "render": function(data, type, row){
                   if(row[8] ==2 && row[9] ==0){
                     status=  `<span class="label label-success btn-block ">Paid</span>`;
                   }else if(row[8] ==3){
                     status = '<span class="label bg-purple  btn-block "> Returned </span>';
                   }else if(row[8] ==4){
                     status = '<span class="label bg-violet  btn-block "> Offer </span>';
                   }else{

                        // datepart: 'y', 'm', 'w', 'd', 'h', 'n', 's'

                        //Set the two dates
                        var y2k  = new Date(row[7]);
                        var today= new Date();
                        var days = Date.dateDiff('d', y2k, today); //displays 625
                        //alert(days)
                         if(days >= row[9]){
                             var afterTermDays = days - row[9];
                             if(row[8]==1){
                               status = '<span class="label bg-orange  btn-block btn-xs"> Partially Paid ('+afterTermDays+' DAYS OUT)</span>';
                             }else{
                               status = '<span class="label label-danger btn-block btn-xs"> Not Payed ('+afterTermDays+' DAYS OUT)</span>';
                             }

                         }else{
                             var remainedDays = row[9]-days;
                             if(row[8]==1){
                               status = '<span class="label label-info  btn-block btn-xs"> Partially Paid ('+remainedDays+' DAYS REM)</span>';
                             }else{
                               status = '<span class="label label-primary btn-block btn-xs"> Not Payed ('+remainedDays+' DAYS REM)</span>';
                             }

                         }
                   }
                   return  status;
                },
                "targets": 8
            }
        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {


            if(   aData[8] == 0 ){ // outcome type
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('alpha-orange');
                });
            }
        },
        "order": [[0,'desc']],
        "displayLength": 25,

        buttons: {            
            buttons: [
                {
                    extend: 'copyHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: [ 0, ':visible' ]
                    }
                },
                {
                    extend: 'excelHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'pdfHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'print',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'colvis',
                    text: '<i class="icon-three-bars"></i> <span class="caret"></span>',
                    className: 'btn bg-blue btn-icon'
                }
                
            ]
        },
        lengthMenu: [
            [  10, 25, 50, 100 ],
            [  '10', '25', '50', '100' ]
        ],
        
        initComplete: function () {
         
        
         $("div.datatable-header").append(`<a data-toggle="collapse"
                                      style="margin-left:10px;"
                                      data-target="#add-form-cont"
                                      href="javascript:;"
                                      aria-controls="add-form-cont"
                                      aria-expanded="false"
                                      class="btn btn-primary"
                                      id="add_Item_Btn">
                                        <i class="`+CURRENT_BTN_ICON+`"></i> `+CURRENT_BTN+`
                                    </a>`);
        $("div.datatable-header").append(`&nbsp;<div class="btn-group">
                          <button type="button" 
                          class="btn bg-teal-400 btn-labeled dropdown-toggle" 
                          data-toggle="dropdown"><b><i class="icon-filter4">
                          </i></b> Invoice Filter <span class="caret"></span></button>
                          <ul class="dropdown-menu dropdown-menu-right">
                  <li><a href="index.php?p=invoice&ip=2"><i class="icon-coins text-success"></i> Paid</a></li>
                  <li class="divider"></li>
                  <li><a href="index.php?p=invoice&ip=1&pt=0"><i class="icon-bell-check text-info"></i> Partially Paid (In term)</a></li>
                  <li><a href="index.php?p=invoice&ip=1&pt=1"><i class="icon-bell-cross text-orange"></i> Partially Paid (out term)</a></li>
                  <li class="divider"></li>
                  <li><a href="index.php?p=invoice&ip=0&pt=0"><i class="icon-alarm-check text-primary"></i> Not Paid (In term)</a></li>
                  <li><a href="index.php?p=invoice&ip=0&pt=1"><i class="icon-alarm-cancel text-danger"></i> Not Paid (out term)</a></li>
                  <li class="divider"></li>
                  <li><a href="index.php?p=invoice&ip=4"><i class=" icon-task text-violet"></i> Offered</a></li>
                  <li><a href="index.php?p=invoice&ip=3"><i class="icon-loop text-purple"></i> Returned</a></li>
                  
                  
                </ul>
              </div>`);
        

            this.api().columns().every( function() {
                var column = this;
                

            });
        }
    });

    
    table.columns().every( function () {
        var that = this;
        $('input', this.footer()).on('keyup change', function () {
            that.search(this.value).draw();
        });
    });


    // Single row selection
    
    $('.datatable-column-search-inputs tbody').on('click', 'tr', function() {
        if ($(this).hasClass('success')) {
            $(this).removeClass('success');
        }
        else {
            table.$('tr.success').removeClass('success');
            $(this).addClass('success');
        }
    });


         // change filter to top
    $('.datatable-column-search-inputs tfoot tr').insertAfter($('.datatable-column-search-inputs thead tr'))


    $('.dataTables_length select').select2({
        minimumResultsForSearch: Infinity,
        width: 'auto'
    });


});



