var table ,  block = $(".content-wrapper").parent();
    

    var HTML_VIEW_PAY = '';
    var print_page =  `
                        <script>
                            setTimeout(function() {
                              window.print()
                            }, 2000)
                        </script>
                        `;
    var HTML_Table = `
                      <!DOCTYPE html>
                      <html lang="ar" dir="rtl">
                      <head>
                        <meta charset="utf-8">
                        <meta http-equiv="X-UA-Compatible" content="IE=edge">
                        <style>

                          .print {  
                            -webkit-print-color-adjust: exact;
                          }
                          
                          .table0_td {
                            
                            border:none;
                            padding:0in 0pt 0in 0pt;
                            height:9.95pt
                            
                          }
                          
                          .table0_td1 {
                            
                            border:none;
                            border-bottom:solid #984806 1.0pt;
                            padding:0in 0pt 0in 0pt;
                            height:9.95pt
                            
                          }
                          
                          
                          
                          .table1_td {
                            
                            border:solid #984806 1.0pt;
                            border-left-color: white;
                            background:#984806;
                            padding:0pt 0pt 0pt 0pt;
                            height:.1in
                            
                          }
                          
                          .last_td {
                            border-left-color: #984806 !important;
                          }
                          
                          .table1_td1 {
                            
                            border:solid #984806 1.0pt;
                            border-top:none;
                            background:white;
                            padding:0pt 0pt 0pt 0pt;
                            height:.1in
                            
                          }
                          
                          .table2_td {
                            
                            border:solid #984806 1.0pt;
                            border-left-color: white;
                            background:#984806;
                            padding:0pt 0pt 0pt 0pt;
                            height:.1in;
                            
                          }
                          
                          .td_head {
                            text-align: center;
                            
                            color : white;
                            height: .3in;
                          }
                          
                          .td_body {
                            text-align: center;
                            
                            color : black;
                            height: .2in;
                            border:solid #984806 1.0pt;
                          }
                          
                          #inv_table tr:nth-child(odd) {
                            background-color: #FDE9D9;
                          }
                          
                          @font-face {
                            font-family: "Noto Kufi Arabic";
                            src: url(assets/custom_font/NotoKufiArabic-Regular.ttf) format("truetype");
                            }
                          
                          .badge {
                            display: inline-block;
                            min-width: 10px;
                            padding: 3px 7px;
                            font-size: 12px;
                            font-weight: 500;
                            color: #fff;
                            line-height: 1.5384616;
                            vertical-align: middle;
                            white-space: nowrap;
                            text-align: center;
                            background-color: #999999;
                            border-radius: 10px;
                          } 

                          .label {
                              display: inline-block;
                              font-weight: 500;
                              padding: 2px 5px 1px 5px;
                              line-height: 1.5384616;
                              border: 1px solid transparent;
                              text-transform: uppercase;
                              text-align: center;

                              font-size: 10px;
                              letter-spacing: 0.1px;
                              border-radius: 2px;
                          }
                          
                          .badge {
                            padding: 1px 1px 1px 1px;
                            font-size: 10px;
                            letter-spacing: 0px;
                            vertical-align: baseline;
                            
                            
                            
                          }
                          
                          .bg-orange-400 {
                            background-color: #FFA726;
                            border-color: #FFA726;
                            color: #fff;
                          }

                          .bg-success-400 {
                            background-color: #4CAF50;
                            border-color: #4CAF50;
                            color: #fff;
                          }

                          

                        </style>

                      </head>

                      <body class="print" style=" font-family: 'Noto Kufi Arabic', Times, serif;">
                        <div align=center>
                      `;


    function show_bills(itemid,cust_name,no_,amount,date_,trans_,notes, cust_id){
          
          notes       = decodeURIComponent_back(notes);
          // staff_anme  = decodeURIComponent_back(staff_anme);
          cust_name   = decodeURIComponent_back(cust_name);

          var headers           ='';
          var attach            = "";
          var attach_other      = "";
          var footers           ="";
          var customer_details  = "";
          var print_attach      = "";
          var total_pay         = "";

          var bill_title        = "وصل قبض";
          
          var bill_paragraph    = Translation('استلم من السيد')+` : (<span style='font-weight:bold;'>` + cust_name + `) </span>`+Translation('مبلغا قدره')+` : (`+currency_format_display(amount)+`) `+Translation('وذلك كدفعه عن حسابه');

          if(trans_ == 'Discount'){
            bill_title        = "وصل خصم من الحساب";
            bill_paragraph    = Translation('تم خصم من حساب السيد')+` : (<span style='font-weight:bold;'>` + cust_name + `) </span>`+Translation('مبلغا قدره')+` : (`+currency_format_display(amount)+`) `+Translation('وذلك عن')+` ................................................................................................................`;

          }else if(trans_ =="Return"){
            bill_title        = "وصل استرجاع مبلغ";
            bill_paragraph    = Translation('تم تسليم السيد')+` : (<span style='font-weight:bold;'>` + cust_name + `) </span>`+Translation('مبلغ مسترجع من حسابة المدفوع قدره')+` : (`+currency_format_display(amount)+`) `+Translation('وذلك عن')+` ................................................................................................................`;
          }


          headers =`
                      <table  dir=rtl border=1 cellspacing=0 cellpadding=0 style='background:white;border-collapse:collapse;border:none; font-weight:bold;'>
                       
                       <tr style='height:9.95pt'>
                        <td width=295 colspan=3 style='width:221.4pt;' class="table0_td">
                        `+Translation('رقم الوصل')+`  :
                        <span id="inv_num" style="color:red;">`+no_+`</span>
                        <br>
                        `+Translation('التــــــــــــاريخ')+`  :  
                        <span id="inv_date">`+date_+`</span>

                        </td>
                        <td width=295 align="center" colspan=2 rowspan=3 style='width:221.4pt;' class="table0_td">
                        <span id="inv_logo"> 
                        <img src="`+COMPANY_LOGO+`" height="150px" align="left">
                         </span>
                        </td>
                       </tr>
                       
                       <tr style='height:9.95pt'>
                        <td width=295 colspan=4 style='width:221.4pt;' class="table0_td">
                       `+Translation('موبايل')+`  : <span dir="ltr" id="inv_phone"> `+COMPANY_PHONE+` </span>
                        <br>
                       `+Translation('البريد الالكتروني')+`  : <span dir="ltr" id="inv_email"> `+COMPANY_EMAIL+` </span>
                        </td>
                       </tr>
                       
                       <tr style='height:9.95pt'>
                        <td colspan=6 width=118 style='width:88.55pt;' class="table0_td1">
                            <span id="inv_address"> `+Translation(COMPANY_ADDRESS)+` </span>
                          
                        </td>
                       </tr>
                       
                       
                      </table>


                      
                        
                            `;

          customer_details = `

                                      <table  dir=rtl border=1 cellspacing=0 cellpadding=0
                                       style='background:white;border-collapse:collapse;border:none; font-weight:bold;'>
                                       
                                       <tr>
                                        <td width=590 colspan=6 style='width:6.15in; text-align:center; border:none;padding:0in 5.4pt 0in 5.4pt'>       
                                          <span style="float: center;  font-size: 18px;" id="inv_slogan">`

                                          +Translation(bill_title)+` </span>
                                        </td>
                                       </tr>

                                       <tr>
                                        <td width=590 colspan=6 style='width:6.15in;border:none;padding:0in 5.4pt 0in 5.4pt'>       
                                          <span style="float: center; font-size: 16px;" id="inv_slogan">
                                          `+bill_paragraph+`
                                          </span>
                                        </td>
                                       </tr>
                                       
                                      
                                       
                                      </table>
                                     
                                            `;
         

          attach =  `
                                  <table id="inv_table"  dir=rtl border=1 cellspacing=0 cellpadding=0 width=591 style='width:443.5pt;border-collapse:collapse;border:#000000; '>
                                   <tr style='page-break-inside:avoid;' class="td_head">
                                    <td width=23 style='width:14.4pt;' class="table2_td">
                                   `+Translation('ت')+` 
                                    </td>
                                    <td width=68 style='width:50.7pt; text-align:center;' class="table2_td">
                                   `+Translation('المبلغ')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt; text-align:center;' class="table2_td">
                                   `+Translation('التاريخ')+` 
                                    </td>
                                    
                                    <td width=74 style='width:110pt; text-align:center;' class="table2_td last_td">
                                   `+Translation('الملاحظات')+` 
                                    </td>
                                   </tr>

                                   <tr style='page-break-inside:avoid;' >
                                    <td width=23 style='width:14.4pt; text-align:center;' >
                                    1 
                                    </td>
                                    <td width=68 style='width:50.7pt; text-align:center;' >
                                   `+currency_format_display(amount)+` 
                                    </td>
                                    <td width=64 style='width:48.3pt; text-align:center;' >
                                   `+date_+` 
                                    </td>
                                    
                                    <td width=74 style='width:55.5pt; text-align:center;' class=" last_td">
                                   `+notes+` 
                                    </td>
                                   </tr>
                                   `;

         




          var total_invoice_price   = 0;
          var total_discount_price  = 0;
          var total_paid_price      = 0;
          var total_remaind_price   = 0;


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

                    total_invoice_price   = currency_format_display(response.invoice[0].total_invoice_price);
                    total_discount_price  = currency_format_display(response.invoice[0].total_payment_discount);
                    total_paid_price      = currency_format_display(response.invoice[0].total_Paid);
                    total_remaind_price   = currency_format_display(response.invoice[0].total_remained);
                    
                     footers =`
                                 
                     <!--<tr style='page-break-inside:avoid;height:.3in'>
                     
                      <td width=517 colspan=4  style='width:388.0pt;border:none;background:white;
                        padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                        <span id="inv_note"> `+Translation('ملاحظة')+` :  </span>
                      </td>
                     </tr>-->


                     <tr style='page-break-inside:avoid;height:.3in'>
                      <td width=517 colspan=2  style='width:388.0pt;border:none;background:white;
                        padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in; text-size:14px;color:purple; font-weight:bold;'>
                        `+Translation('حساب الزبون الكلي')+`
                      </td>
                      <td width=517 colspan=2  style='width:388.0pt;border:none;background:white;
                        padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in; text-size:14px;color:purple; font-weight:bold;'>
                        `+total_invoice_price+`
                      </td>
                     </tr>

                     <tr style='page-break-inside:avoid;height:.3in'>
                      <td width=517 colspan=2  style='width:388.0pt;border:none;background:white;
                        padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in; text-size:14px;color:green; font-weight:bold;'>
                        `+Translation('الدفوعات الكلية')+`
                      </td>
                      <td width=517 colspan=2  style='width:388.0pt;border:none;background:white;
                        padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in; text-size:14px;color:green; font-weight:bold;'>
                        `+total_paid_price+`
                      </td>
                     </tr>

                     <tr style='page-break-inside:avoid;height:.3in'>
                      <td width=517 colspan=2  style='width:388.0pt;border:none;background:white;
                        padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in; text-size:14px;color:#bb7900; font-weight:bold;'>
                        `+Translation('خصومات الحساب الكلية')+`
                      </td>
                      <td width=517 colspan=2  style='width:388.0pt;border:none;background:white;
                        padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in; text-size:14px;color:#bb7900; font-weight:bold;'>
                        `+total_discount_price+`
                      </td>
                     </tr>

                     <tr style='page-break-inside:avoid;height:.3in'>
                      <td width=517 colspan=2  style='width:388.0pt;border:none;background:white;
                        padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in; text-size:14px;color:red; font-weight:bold;'>
                        `+Translation('المبلغ الكلي المتبقي')+`
                      </td>
                      <td width=517 colspan=2  style='width:388.0pt;border:none;background:white;
                        padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in; text-size:14px;color:red; font-weight:bold;'>
                        `+total_remaind_price+`
                      </td>
                     </tr>

                     
                     <tr style='page-break-inside:avoid;height:.1in; background-color: white'>
                      <td width=258 colspan=2  style='width:194.0pt;border:none;
                      padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                      `+Translation('توقيع المُسلم')+`
                      </td>
                      <td width=258 colspan=2 style='text-align:left;width:194.5pt;border:none;padding:2.15pt .15in 2.15pt .15in;
                      height:.1in'>
                     `+Translation('توقيع المستلم')+` 
                      </td>
                     </tr>
                    </table>

                    </div>




                    </body>

                    `+print_attach+`

                    </html>`;

                  }else{
                    swal({
                                title: Translation("خطأ"),
                                text: Translation(res.data),
                                confirmButtonColor: "#2196F3",
                                type: "error"
                            });
                  }

                    
              },
              complete: function() {
                HTML_VIEW_PAY = HTML_Table + headers + customer_details + attach + attach_other + footers;
                       
                $("#bills_show").html(HTML_VIEW_PAY);
                $("#bill_id").val(itemid);

                $('#show_bills_modal').modal('toggle');
              }

        }); // submit ajax


         
         

         
                  


    }



    function edit_items(itemid,amount,date_,notes,cust_id,tans_,inv_typ, itm_id){
      
      notes = decodeURIComponent_back(notes);
      
      
      $("#edit_objid").val(itemid);
      $("#edit_payment_gived_to_id_fk").val(cust_id);
      $("#edit_payment_gived_to_id_fk").val(cust_id).selectpicker('refresh');
      
      $("#edit_payment_withdraw_amount").val(amount);
      $("#edit_payment_withdraw_amount").attr('data-value',amount);

      
      $("#edit_payment_withdraw_date").val(date_);
      $("#edit_payment_withdraw_note").val(notes);
      

      $("#edit_item_type_id_fk").attr('disabled','disabled');

      $("#edit_pay_type").attr('disabled','disabled');


      $("#edit_item_type_id_fk").val(itm_id).selectpicker('refresh');
      $("#edit_pay_type").val(inv_typ);


      $("#transaction_").val(tans_);

      $("#transaction_type").text(tans_);




      if(tans_ == 'Payment'){
        $("#transaction_type_alert").removeClass('alert-primary');
        $("#transaction_type_alert").removeClass('alert-danger');
        $("#transaction_type_alert").removeClass('alert-warning');
        $("#transaction_type_alert").addClass('alert-success');
        $("#edit_item_type_id_fk").removeAttr('disabled');
        $("#edit_pay_type").removeAttr('disabled');
        $("#edit_item_type_id_fk").val(itm_id).selectpicker('refresh');
        $("#edit_pay_type").val(inv_typ);

      }else if(tans_=="Discount"){
        $("#transaction_type_alert").removeClass('alert-primary');
        $("#transaction_type_alert").removeClass('alert-danger');
        $("#transaction_type_alert").removeClass('alert-success');
        $("#transaction_type_alert").addClass('alert-warning');
      }else if(tans_ =="Return"){

        $("#transaction_type_alert").removeClass('alert-primary');
        $("#transaction_type_alert").removeClass('alert-success');
        $("#transaction_type_alert").removeClass('alert-warning');
        $("#transaction_type_alert").addClass('alert-danger');

      }else{
        $("#transaction_type_alert").removeClass('alert-danger');
        $("#transaction_type_alert").removeClass('alert-success');
        $("#transaction_type_alert").removeClass('alert-warning');
        $("#transaction_type_alert").addClass('alert-primary');
      }
      
       load_customer_account_details(cust_id);
      $('#edit_form_cont').modal('toggle');

    }

  



    function delete_items(itemid) {
     
        swal({
            title: Translation("هل انت متأكد؟!"),
            text: Translation("سوف لن تستطيع استرجاع المعلومات المرتبطة بهذا السجل في حالة المسح"),
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#EF5350",
            confirmButtonText: Translation("موافق: امسح!"),
            cancelButtonText: Translation("الغاء الامر"),
            closeOnConfirm: false,
            closeOnCancel: true
        },
        function(isConfirm){
            if (isConfirm) {
              $.ajax({
                url: "models/crul_payment.php",
                type:"POST",
                dataType : "JSON",
                data: {"type":"delete","obj_id":itemid} ,
                complete:function(){
                  //hideLoader();
                },
                beforeSend:function(){
                  //showLoader("Deleting Product");
            },
                success: function(res) {
                  if(res.is_success == true){
                    swal({
                                title: Translation("تم الحذف!"),
                                text: Translation(res.data),
                                confirmButtonColor: "#66BB6A",
                                type: "success"
                            });
                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                  }else{
                    swal({
                                title: Translation("خطأ"),
                                text: Translation(res.data),
                                confirmButtonColor: "#2196F3",
                                type: "error"
                            });
                  }
                }
            });
            }
        }); // /confirm
    }



    function Checks(id,types=null,min=null,max=null){
        var name = $("#"+id).val();
        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 get_Staff(){

      $.ajax({
                      url : 'models/crul_capital.php',
                      type : 'POST',
                      data : {type:'get_Staff'},
                      dataType : 'json',
                      success : function(res) {
                          
                          if(res.is_success == true){
                            
                            var attach ='<option value="" selected="selected">'+Translation('اسم المالك')+'</option>';
                          
                            for(var i=res.data.length-1 ; i >= 0;i--){
                              
                              attach = attach + '<option value="'+res.data[i].staff_id+'">'+res.data[i].full_name+'</option>';
                             

                            }
                            $("#withdraw_by").html(attach);
                            $("#edit_withdraw_by").html(attach);
                            $('#withdraw_by').selectpicker('refresh');
                            $("#edit_withdraw_by").selectpicker('refresh');

                          }else{
                            swal({
                                        title: Translation("خطأ"),
                                        text: Translation(res.data),
                                        confirmButtonColor: "#2196F3",
                                        type: "error"
                                    });
                          }

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

                }); // submit ajax

    }

    function get_Customer(){

                var c_typeo = '0';
                if($("#c_typeo").length >0 ){
                  c_typeo = $("#c_typeo").val();

                }

                $.ajax({
                      url : 'models/crul_customer.php',
                      type : 'POST',
                      data : {type:'get_customer_new',typ:c_typeo},
                      dataType : 'json',
                      success : function(res) {
                          
                          if(res != 0){
                            
                            var attach ='<option value="" selected="selected">'+Translation('اسم الزبون')+'</option>';
                          
                            for(var i=res.length-1 ; i >= 0;i--){
                              
                              attach = attach + '<option value="'+res[i][0]+'">'+res[i][1]+'</option>';
                             

                            }
                            $('select[id$="payment_gived_to_id_fk"]').html(attach);
                            // $('select[id$="payment_gived_to_id_fk"]').html(attach);
                            $('select[id$="payment_gived_to_id_fk"]').selectpicker('refresh');
                            // $('select[id$="payment_gived_to_id_fk"]').selectpicker('refresh');

                          }else{
                            swal({
                                        title: Translation("خطأ"),
                                        text: Translation(res.data),
                                        confirmButtonColor: "#2196F3",
                                        type: "error"
                                    });
                          }

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

                }); // submit ajax

    }

    function print_invoice(typ,payment=null){
      if(typ=='Print'){
        var lines = `<hr style="border:1px dashed #aaa; margin:10px 0;">`;
        window.open().document.write(HTML_VIEW_PAY+lines+HTML_VIEW_PAY+print_page);
      }else if(typ=='PDF'){
        var nn = $("#inv_numb").val();
        pdf_generator(HTML_VIEW_PAY,nn,'pay')
      }else{
        window.open().document.write(HTML_VIEW_PAY);
      }
    }

    function pdf_generator(HTML,INV_NO,payment){

                $.ajax({
                      url : 'models/crul_invoice.php',

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

                                    noty({
                                        width: 200,
                                        text: Translation('تم توليد ملف الـ PDF بنجاح'),
                                        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+'" target="_blank" style="float: right;"> '+Translation('تحميل')+' <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: Translation(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 compute_remain_price(val,idd){

        // var val = $("#payment_withdraw_amount").val();

        if(val !="" &&  !isNaN(val) && val !=null && val !=undefined ){
          val = val;
        }else{
          val = 0;
        }
        // var real_price = $("#product_row_total_"+row_num).attr('data-actual-row-price'); 
        var old_remain   = $("#total_customer_remaind").attr('data-original-amount');
        // var old_remain   = $("#"+idd).attr('data-original-amount');
        
          // alert("old_remain="+old_remain)

        // if(real_price == null || real_price == undefined || isNaN(real_price)){real_price=0;}
        if(old_remain   == null || old_remain   == undefined || old_remain   == '' || isNaN(old_remain)){old_remain=0; }
       
        var new_remaind = old_remain - val;
          // alert("new_remaind="+new_remaind)

       
        if(new_remaind < 0){

           noty({
                  width: 200,
                  text: Translation("الرجاء التأكد من القيمة المدخلة لان المدفوعات اصبحت اكبر من السعر الكلي المتبقي"),
                  type: 'error',
                  dismissQueue: true,
                  timeout: 4000,
                  layout: 'topRight',
                });

          
          // $("#payment_withdraw_amount").val('');
          $("#"+idd).val('');
          
        }


    }


    function compute_return_price(val,idd){

        // var val = $("#payment_withdraw_amount").val();

        if(val !="" &&  !isNaN(val) && val !=null && val !=undefined ){
          val = val;
        }else{
          val = 0;
        }
        // var real_price = $("#product_row_total_"+row_num).attr('data-actual-row-price'); 
        var old_remain   = $("#return_total_customer_paid").attr('data-original-amount');
        // var old_remain   = $("#"+idd).attr('data-original-amount');
        
          // alert("old_remain="+old_remain)

        // if(real_price == null || real_price == undefined || isNaN(real_price)){real_price=0;}
        if(old_remain   == null || old_remain   == undefined || old_remain   == '' || isNaN(old_remain)){old_remain=0; }
       
        var new_remaind = old_remain - val;
          // alert("new_remaind="+new_remaind)

       
        if(new_remaind < 0){

           noty({
                  width: 200,
                  text: Translation("الرجاء التأكد من القيمة المدخلة لان المبلغ المسترجع اصبحت اكبر من المبلغ الكلي المدفوع للزبون"),
                  type: 'error',
                  dismissQueue: true,
                  timeout: 4000,
                  layout: 'topRight',
                });

          
          // $("#payment_withdraw_amount").val('');
          $("#"+idd).val('');
          
        }


    }

    function edit_compute_remain_price(){

        var val     = $("#edit_payment_withdraw_amount").val();
        var trans_  = $("#transaction_").val();

      
        var curnt_edit_amount = $("#edit_payment_withdraw_amount").attr('data-value'); // we should exculde it from remaind because its by default were add and computed but now we will edit it

        if(val !="" &&  !isNaN(val) && val !=null && val !=undefined ){
          val = val;
        }else{
          val = 0;
        }
        // var real_price = $("#product_row_total_"+row_num).attr('data-actual-row-price');
        if(trans_ == 'Return'){
          var old_remain   = $("#edit_total_customer_paid").attr('data-original-amount');
        }else{
          var old_remain   = $("#edit_total_customer_remaind").attr('data-original-amount');
        } 
        
        
          // alert("old_remain="+old_remain)

        // if(real_price == null || real_price == undefined || isNaN(real_price)){real_price=0;}
        if(old_remain   == null || old_remain   == undefined || old_remain   == '' || isNaN(old_remain)){old_remain=0; }
       
        var new_remaind = old_remain - val + +curnt_edit_amount;

          // alert("new_remaind="+new_remaind)
       
        if(new_remaind < 0){

           noty({
                  width: 200,
                  text: Translation("الرجاء التأكد من القيمة المدخلة لان المدفوعات اصبحت اكبر من السعر الكلي المتبقي"),
                  type: 'error',
                  dismissQueue: true,
                  timeout: 4000,
                  layout: 'topRight',
                });

          // $("#inv_row_remaind_price_"+row_num).val('');
          $("#edit_payment_withdraw_amount").val(curnt_edit_amount);
          
        }


    }

    function load_customer_account_details (cust_id){

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

                            $('span[id$="total_customer_account"]').html(currency_format_display(response.invoice[0].total_invoice_price));
                            $('span[id$="total_customer_account"]').attr('data-original-amount',(response.invoice[0].total_invoice_price));
                            
                            $('span[id$="total_customer_discount"]').html(currency_format_display(response.invoice[0].total_payment_discount));
                            $('span[id$="total_customer_discount"]').attr('data-original-amount',(response.invoice[0].total_payment_discount));
                            
                            $('span[id$="total_customer_paid"]').html(currency_format_display(response.invoice[0].total_Paid));
                            $('span[id$="total_customer_paid"]').attr('data-original-amount',(response.invoice[0].total_Paid));
                         
                            $('span[id$="total_customer_remaind"]').html(currency_format_display(response.invoice[0].total_remained));
                            $('span[id$="total_customer_remaind"]').attr('data-original-amount',(response.invoice[0].total_remained));
                         

                          }else{
                            swal({
                                        title: Translation("خطأ"),
                                        text: Translation(res.data),
                                        confirmButtonColor: "#2196F3",
                                        type: "error"
                                    });
                          }

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

                }); // submit ajax
    }


    function add_discount(){
      $('#discount_form_cont').modal('toggle');

    }

    function add_return(){
      $('#return_form_cont').modal('toggle');

    }


    function get_Item_Class(){

            $.ajax({
                  url : 'models/crul_items.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option value="0" selected="selected">'+Translation('جميع الاصناف')+'</option>';
                      var aaa='';
                        for(var i=response.length-1 ; i >= 0;i--){
                          
                          attach = attach + '<option value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          
                        }
                        $("#item_type_id_fk").html(attach);
                        $("#edit_item_type_id_fk").html(attach);
                        
                        $('#item_type_id_fk').selectpicker('refresh');
                        $('#edit_item_type_id_fk').selectpicker('refresh');
                        
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

    }


$(document).ready(function() {
  
    // get_Staff();
    get_Customer();
    get_Item_Class();


    $('select[id$="payment_gived_to_id_fk"]').change(function(e) {
                e.preventDefault();
                var cust_id = $(this).val();
                
                load_customer_account_details(cust_id);

         
    });




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

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

    $('#add_form').submit(function(event) {
      event.preventDefault();
     
          

          var cust_id                   = $("#payment_gived_to_id_fk").val();
          var payment_amount            = $("#payment_withdraw_amount").val();
          var paid_date                 = $("#paid_date").val();
          var payment_note              = $("#payment_note").val();
          var pay_type                  = $("#pay_type").val();
          var item_type_id_fk           = $("#item_type_id_fk").val();
         

          var check_paid  = false;
          var check_ids   = true;

          check_paid      = Checks('payment_withdraw_amount','No',0.000001);

        

          if(check_paid && check_ids){
            $("#submit_add_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_invoice.php",
                type:"POST",
                dataType: "JSON",
                data : {cust_id              :cust_id,
                        payment_amount       :payment_amount,
                        paid_date            :paid_date,
                        payment_note         :payment_note,
                        pay_type             :pay_type,
                        item_type_id_fk      :item_type_id_fk,
                        type                 :'add_payments'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

                    $("#add_form")[0].reset();
                    $("#payment_gived_to_id_fk").val('').selectpicker('refresh');
                    
                    // get_Customer();

                    $("#total_customer_account").html(currency_format_display(0));
                    $("#total_customer_account").attr('data-original-amount',(0));
                            
                    $("#total_customer_discount").html(currency_format_display(0));
                    $("#total_customer_discount").attr('data-original-amount',(0));
                            
                    $("#total_customer_paid").html(currency_format_display(0));
                    $("#total_customer_paid").attr('data-original-amount',(0));
                         
                    $("#total_customer_remaind").html(currency_format_display(0));
                    $("#total_customer_remaind").attr('data-original-amount',(0));
                         
                    $("#add-form-cont").collapse('hide');

                   

                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    
                    
                    noty({
                                    width: 200,
                                    text: Translation(res.data),
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 2000,
                                    layout: 'topRight',
                                    callback: {
                                              onShow: function() {},
                                              afterShow: function() {},
                                              onClose: function() {},
                                              afterClose: function() {},
                                              onCloseClick: function() {},
                                            },
                              });

                    // i will reload the page to reset all fields
                    
               
                  }else{
                      swal({
                          title: Translation("خطأ"),
                          text: Translation(res.data),
                          confirmButtonColor: "#66BB6A",
                          type: "warning"
                      });
                      //$("#add-form-cont").collapse('hide');
                  }

                $("#submit_add_btn").attr('disabled',false);
            })
            .fail(function(err) {
                 swal({
                    title: Translation("خطأ"),
                    text: (err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                $("#submit_add_btn").attr('disabled',false);
            })
            .always(function() {
                console.log("complete");
            });
          }else{
              noty({
                    width: 200,
                    text: Translation('الرجاء التأكد من القيم المدخلة وايضا يجب ادخال دفعة جديدة على الاقل'),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
          }

    });




    
    $('#edit_form').submit(function(event) {
              event.preventDefault();
             
              var payment_id          = $("#edit_objid").val();
              var customer_id_fk      = $("#edit_payment_gived_to_id_fk").val();
              var paid_amount         = $("#edit_payment_withdraw_amount").val();
              var paid_date           = $("#edit_payment_withdraw_date").val();
              var payment_note        = $("#edit_payment_withdraw_note").val();
              
              var pay_type            = $("#edit_pay_type").val();
              var item_type_id_fk     = $("#edit_item_type_id_fk").val();


              var Check1 = true;
              var Check2 = true;
              var Check3 = true;
              var Check4 = true;
              var Check5 = true;
              var Check6 = true;

              Check1 = Checks('edit_payment_gived_to_id_fk');
              Check2 = Checks('edit_payment_withdraw_amount');
              Check3 = Checks('edit_payment_withdraw_date');
              // Check4 = Checks('edit_withdraw_date');
              
            

              if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){

                  $.ajax({
                      url: "models/crul_payment.php",
                      type:"POST",
                      dataType : "JSON",
                      data : {payment_id      :payment_id,
                              customer_id_fk  :customer_id_fk,
                              paid_amount     :paid_amount,
                              paid_date       :paid_date,
                              payment_note    :payment_note,
                              pay_type        :pay_type,
                              item_type_id_fk :item_type_id_fk,
                              type            :'update'},
                      complete:function(){
                        //hideLoader();
                      },
                      beforeSend:function(){
                        //showLoader("Updating Product");
                      },
                      success: function(res) {
                        if(res.is_success == false){
                          $("#edit-form-cont").collapse('hide');
                          $('#edit_form_cont').modal('toggle');
                          $("#edit_form")[0].reset();
                          swal({
                              title: Translation("خطأ"),
                              text: Translation(res.data),
                              confirmButtonColor: "#66BB6A",
                              type: "warning"
                          });
                        }else{
                          $("#edit_form")[0].reset();
                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);

                          $('#edit_form_cont').modal('toggle');
                          noty({
                                          width: 200,
                                          text: Translation(res.data), //'Product Successfully Update',
                                          type: 'success',
                                          dismissQueue: true,
                                          timeout: 3000,
                                          layout: 'topRight',
                                    });
                        }
                      }
                  });
                }
      });


    $('#discount_form').submit(function(event) {
              event.preventDefault();
             
              
              var customer_id_fk      = $("#discount_payment_gived_to_id_fk").val();
              var paid_amount         = $("#discount_payment_withdraw_amount").val();
              var paid_date           = $("#discount_payment_withdraw_date").val();
              var payment_note        = $("#discount_payment_withdraw_note").val();
              



              var Check1 = true;
              var Check2 = true;
              var Check3 = true;
              var Check4 = true;
              var Check5 = true;
              var Check6 = true;

              Check1 = Checks('discount_payment_gived_to_id_fk');
              Check2 = Checks('discount_payment_withdraw_amount');
              Check3 = Checks('discount_payment_withdraw_date');
              // Check4 = Checks('edit_withdraw_date');
              
            

              if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
                  $("#discount_form_btn").attr('disabled',true);
                  $.ajax({
                      url: "models/crul_payment.php",
                      type:"POST",
                      dataType : "JSON",
                      data : {
                              customer_id_fk:customer_id_fk,
                              paid_amount:paid_amount,
                              paid_date:paid_date,
                              payment_note:payment_note,
                              type:'discount'},
                      complete:function(){
                        $("#discount_form_btn").attr('disabled',false);
                      },
                      beforeSend:function(){
                        $("#discount_form_btn").attr('disabled',true);
                      },
                      success: function(res) {
                        if(res.is_success == false){
                          
                          $('#discount_form_cont').modal('toggle');
                          $("#discount_form")[0].reset();
                          swal({
                              title: Translation("خطأ"),
                              text: Translation(res.data),
                              confirmButtonColor: "#66BB6A",
                              type: "warning"
                          });
                        }else{
                          $("#discount_form")[0].reset();
                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);

                          $('#discount_form_cont').modal('toggle');
                          noty({
                                          width: 200,
                                          text: Translation(res.data), //'Product Successfully Update',
                                          type: 'success',
                                          dismissQueue: true,
                                          timeout: 3000,
                                          layout: 'topRight',
                                    });
                        }
                        $("#discount_form_btn").attr('disabled',false);
                      }
                  });
                }
    });


    $('#return_form').submit(function(event) {
              event.preventDefault();
             
              
              var customer_id_fk      = $("#return_payment_gived_to_id_fk").val();
              var paid_amount         = $("#return_payment_withdraw_amount").val();
              var paid_date           = $("#return_payment_withdraw_date").val();
              var payment_note        = $("#return_payment_withdraw_note").val();
              



              var Check1 = true;
              var Check2 = true;
              var Check3 = true;
              var Check4 = true;
              var Check5 = true;
              var Check6 = true;

              Check1 = Checks('return_payment_gived_to_id_fk');
              Check2 = Checks('return_payment_withdraw_amount');
              Check3 = Checks('return_payment_withdraw_date');
              // Check4 = Checks('edit_withdraw_date');
              
            

              if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
                  $("#return_form_btn").attr('disabled',true);
                  $.ajax({
                      url: "models/crul_payment.php",
                      type:"POST",
                      dataType : "JSON",
                      data : {
                              customer_id_fk:customer_id_fk,
                              paid_amount:paid_amount,
                              paid_date:paid_date,
                              payment_note:payment_note,
                              type:'return'},
                      complete:function(){
                        $("#return_form_btn").attr('disabled',false);
                      },
                      beforeSend:function(){
                        $("#return_form_btn").attr('disabled',true);
                      },
                      success: function(res) {
                        if(res.is_success == false){
                          
                          $('#return_form_cont').modal('toggle');
                          $("#return_form")[0].reset();
                          swal({
                              title: Translation("خطأ"),
                              text: Translation(res.data),
                              confirmButtonColor: "#66BB6A",
                              type: "warning"
                          });
                        }else{
                          $("#return_form")[0].reset();
                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);

                          $('#return_form_cont').modal('toggle');
                          noty({
                                          width: 200,
                                          text: Translation(res.data), //'Product Successfully Update',
                                          type: 'success',
                                          dismissQueue: true,
                                          timeout: 3000,
                                          layout: 'topRight',
                                    });
                        }
                        $("#return_form_btn").attr('disabled',false);
                      }
                  });
                }
      });

});





$(function() {
//var singleSelect = $('.datatable-column-search-inputs').DataTable();
    

    $(".touchspin-basic").TouchSpin({
        min: 1,
        max: 1000000,
        step: 1
    });

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

   // for image uploader

  



    //
    // AJAX upload
    //





   // end image uploader



   // Setting datatable defaults
    $.extend( $.fn.dataTable.defaults, {
        autoWidth: false,
        columnDefs: [{ 
            orderable: false,
            width: '100px',
            targets: [ 10 ]
        }],
        dom: '<"datatable-header"fBl><"datatable-scroll"t><"datatable-footer"ip>',
        language: {
            search: '<span>'+Translation('بحث')+':</span> _INPUT_',
            searchPlaceholder: Translation('بحث عن')+'...',
            lengthMenu: '<span>'+Translation('عرض')+':</span> _MENU_',
            paginate: { 'first': 'First', 'last': 'Last', 'next': '&larr;', 'previous': '&rarr;' }
            
        },
        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="'+Translation('بحث عن')+' '+title+'" />');
    });
    
    
  var query_id  = getQueryVariable("id");
  var query_ic = getQueryVariable("ic");

  var c_typeo = $("#c_typeo").val();

   
  var table = $('.datatable-column-search-inputs').DataTable({
        keys: {
            className: 'focus focus-success'
        },
        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,-1 ],
            [  '10', '25', '50', '100','All' ]
        ],

        "processing": true,
        "serverSide": true,
        "ajax": {
        "url" : "models/crul_payment.php",
        "data": function(d){
          d.type = "load";
          if(query_id !='not'){
            d.id =query_id ;
          }

          if(query_ic !='not'){
            d.idc =query_ic ;
          }

          if(c_typeo !=null){
            d.c =c_typeo ;
          }
        }
        },
        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": 8,
              "data": null,
              "render": function (data,type,row) {

                            return  `<ul class='icons-list pull-right'>
                                        
                                        <li class='text-primary-600'>
                                            <a  class='text-purple-400' onclick="show_bills(`+row[0]+`,'`+escapeHtml(row[1])+`','`+row[2]+`','`+row[3]+`','`+row[4]+`','`+row[5]+`','`+escapeHtml(row[6])+`',`+row[13]+`)" data-popup='tooltip' data-original-title='`+Translation('وصل قبض')+`'>
                                                <i class='icon-certificate'></i>
                                            </a>
                                        </li>

                                        <li class='text-primary-600'>
                                            <a  class='text-primary-400' onclick="edit_items(`+row[0]+`,'`+row[3]+`','`+row[4]+`','`+escapeHtml(row[6])+`',`+row[13]+`,'`+row[5]+`','`+row[8]+`','`+row[9]+`')" data-popup='tooltip' data-original-title='`+Translation('تحرير')+`'>
                                                <i class='icon-pencil7'></i>
                                            </a>
                                        </li>

                                        <li class='text-danger-600'>
                                            <a  class='text-danger-400' onclick="delete_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('حذف')+`'>
                                                <i class='icon-trash'></i>
                                            </a>
                                        </li>

                                    </ul>`;
                        }
          },


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

                        
                          return  currency_format_display(data);
                       


               },
               "targets": 3
            },

            

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


                        return  `<a href='index.php?p=payment&id=`+row[13]+`'  data-popup='tooltip' data-original-title='`+Translation('عرض جميع دفعات القروض لهذا الزبون')+`'>`+data+`</a>`;


               },
               "targets": 1
            },

            {
                "render": function(data, type, row){
                   if(data =='Payment' ){
                     status=  `<span class="label label-success btn-block ">`+data+`</span>`;
                   }else if(data =='Discount'){
                     status = '<span class="label bg-orange-400  btn-block ">'+data+'  </span>';
                   }else if(data =='Return'){
                     status = '<span class="label bg-danger  btn-block ">'+data+'  </span>';
                   }else{
                      status = '<span class="label bg-purple  btn-block ">'+data+'  </span>';
                   }
                   return  status;
                },
                "targets": 5
            },

            {
                "render": function(data, type, row){
                   if(row[8] =='Raw' ){
                     status=  `<span class="label label-info btn-block ">النوع : مواد جملة</span>`;
                   }else if(row[8] =='Plural' ){
                     status=  `<span class="label label-warning btn-block ">النوع : ستائر جملة</span>`;
                   }else if(row[8] =='Single' ){
                     status=  `<span class="label label-primary btn-block ">النوع : ستائر مفرد</span>`;
                   }else{
                      status = '';
                   }

                   if(row[7] !=null ){
                     status=status +  `<span class="label label-success btn-block ">الصنف : `+row[7]+`</span>`;
                   }else{
                      status =status + '';
                   }
                   return  status;
                },
                "targets": 7
            },
            
            
            
           
            
            
            
            
            
        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {


            if(   aData[9] == 0 ){
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('warning-active');
                });
            }

            $("#total_amount").text(currency_format_display(aData[10]))
            $("#total_paid").text(currency_format_display(aData[11]))
            $("#total_unpaid").text(currency_format_display(aData[12]))
        },
        "order": [[0,'desc']],
        "displayLength": 25,


        initComplete: function () {
         
        // $("div.datatable-header").append(`<a  style="margin-left:15px;" class="btn bg-info-400"  id="headerBtn" onclick="add_item()"> <i class="icon-file-pdf position-right"></i> Add Category </a>`);   
         $("div.datatable-header").append(`<a data-toggle="collapse"
                                      style="margin-right: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> `+Translation(CURRENT_BTN)+`
                                    </a>`);


         $("div.datatable-header").append(`<a 
                                      style="margin-right:10px;"
                                      data-target="#add-form-cont"
                                      href="javascript:;"
                                      class="btn bg-orange"
                                      id="add_discount_btn" onclick="add_discount();">
                                        <i class="icon-price-tag"></i> `+Translation('اعطاء خصم للزبون')+`
                                    </a>`);

         $("div.datatable-header").append(`<a 
                                      style="margin-right:10px;"
                                      data-target="#add-form-cont"
                                      href="javascript:;"
                                      class="btn btn-danger"
                                      id="add_return_btn" onclick="add_return();">
                                        <i class="icon-reset "></i> `+Translation('ترجيع مبلغ')+`
                                    </a>`);




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


    // high light row and column
    var lastIdx = null;
     
    $('.datatable-highlight tbody').on('mouseover', 'td', function() {
        var chk_inx =table.cell(this).index();
        if(chk_inx != undefined && chk_inx !=null && chk_inx !='' ){ // because child row
          var colIdx = table.cell(this).index().column;

          if (colIdx !== lastIdx) {
              $(table.cells().nodes()).removeClass('active');
              $(table.column(colIdx).nodes()).addClass('active');
          }
        }
        
    }).on('mouseleave', function() {
        $(table.cells().nodes()).removeClass('active');
    });

    // end highlight row and column

    // 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'
    });


});



