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

    var HTML_VIEW_PAY = '';
    var print_page =  `
                        <script>
                          window.print();
                          window.onload = function() { window.print(); }
                        </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,amount,date_,notes,printing=null){
          
          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         = "";


           headers =`

                      <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;border:none;padding:0in 5.4pt 0in 5.4pt'>       
                            <span style="float: left; font-size: 20px;" id="inv_slogan">`+COMPANY_NAME+`</span>
                          </td>
                         </tr>
                         <tr style='height:9.95pt'>
                          <td width=295 colspan=3 style='width:221.4pt;' class="table0_td">
                          <span id="inv_address"> `+Translation(COMPANY_ADDRESS)+` </span>
                          </td>
                          <td width=295 colspan=3 rowspan=2 style='width:221.4pt;' class="table0_td">
                          <span id="inv_logo">  </span>
                          </td>
                         </tr>

                         
                         
                         <tr style='height:9.95pt'>
                          <td width=295 colspan=3 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 width=118 style='width:88.55pt;' class="table0_td1">
                         `+Translation('رقم الوصل')+`  :
                          </td>
                          <td width=139 style='width:1.45in;' class="table0_td1">
                          <span id="inv_num" style="color:red;">`+itemid+`</span>
                          </td>
                          <td width=77 colspan=2 style='width:.8in;' class="table0_td1">
                          
                          </td>
                          <td width=116 style='width:87.3pt;' class="table0_td1">
                         `+Translation('التــــــــــــاريخ')+`  :     
                          </td>
                          <td width=140 style='width:104.95pt;' class="table0_td1">
                          <span id="inv_date">`+date_+`</span>
                          </td>
                         </tr>
                         
                         
                        </table>
                        <br>
                            `;

          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('وصل قبض')+` </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">`

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

           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;' class="table2_td">
                                   `+Translation('المبلغ المستلم')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt;' class="table2_td">
                                   `+Translation('تاريخ القرض')+` 
                                    </td>
                                    
                                    <td width=74 style='width:55.5pt;' class="table2_td last_td">
                                   `+Translation('الملاحظات')+` 
                                    </td>
                                   </tr>

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

          if(printing != null){
            print_attach = `
                            <script>
                              window.print();
                              window.onload = function() { window.print(); }
                            </script>
                            `;
          }else{
            print_attach = "";
          }


          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:.1in; background-color: white'>
                      <td width=517 colspan=2  style='width:388.0pt;border:none;
                      padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                      `+Translation('توقيع المُسلم')+`
                      </td>
                      <td width=74 colspan=2 style='width:55.5pt;border:none;padding:2.15pt .15in 2.15pt .15in;
                      height:.1in'>
                     `+Translation('توقيع المستلم')+` 
                      </td>
                     </tr>
                    </table>

                    </div>




                    </body>

                    `+print_attach+`

                    </html>`;

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


    }



    function edit_items(itemid,calls,amount,date_,notes,cust_id){
      
      notes = decodeURIComponent_back(notes);
      
      
      $("#edit_objid").val(itemid);
      $("#edit_customer_id_fk").val(cust_id);
      $("#edit_customer_id_fk").val(cust_id).selectpicker('refresh');
      
      $("#edit_call_date").val(calls);
      
      $("#edit_expect_pay_amount").val(amount);
      $("#edit_expect_pay_date").val(date_);
      $("#edit_pay_note").val(notes);
      
      $('#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_notify.php",
                type:"POST",
                dataType : "JSON",
                data: {"type":"delete","obj_id":itemid} ,
                complete:function(){
                 
                },
                beforeSend:function(){
                 
            },
                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 make_paid(itemid) {
     
        swal({
            title: Translation("هل انت متأكد؟!"),
            text: Translation("سيتم تغيير حالة التنبيه الى واصل"),
            type: "info",
            showCancelButton: true,
            confirmButtonColor: "#EF5350",
            confirmButtonText: Translation("موافق"),
            cancelButtonText: Translation("الغاء الامر"),
            closeOnConfirm: false,
            closeOnCancel: true
            
        },
        function(isConfirm){
            if (isConfirm) {
              $.ajax({
                url: "models/crul_payment_notify.php",
                type:"POST",
                dataType : "JSON",
                data: {"type":"paid","obj_id":itemid} ,
                complete:function(){
                 
                },
                beforeSend:function(){
                 
            },
                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(){

                $.ajax({
                      url : 'models/crul_payment_notify.php',
                      type : 'POST',
                      data : {type:'get_Customer'},
                      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].customer_id+'">'+res.data[i].customer_full_name+'</option>';
                             

                            }
                            $("#customer_id_fk").html(attach);
                            $("#edit_customer_id_fk").html(attach);
                            $('#customer_id_fk').selectpicker('refresh');
                            $("#edit_customer_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'){
        window.open().document.write(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
    }



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

    $('#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 customer_id_fk      = $("#customer_id_fk").val();
      var call_date           = $("#call_date").val();
      var expect_pay_amount   = $("#expect_pay_amount").val();
      var expect_pay_date     = $("#expect_pay_date").val();
      var pay_note            = $("#pay_note").val();
      


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

      Check1 = Checks('customer_id_fk');
      Check2 = Checks('call_date');
      Check3 = Checks('expect_pay_amount');
      Check4 = Checks('expect_pay_date');
      
      var formData = new FormData(this);
      formData.append("type", 'create');


      if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
            $("#submit_add_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_payment_notify.php",
                type:"POST",
                dataType : "JSON",
                data:formData,
                cache:false,
                contentType: false,
                processData: false
                // data : {category_id:category_id,product_name:product_name,erbil_code:erbil_code,turkish_code:turkish_code,
                //   barcode:barcode,product_note:product_note,product_min_notification:product_min_notification,type:'create'}
            })
            .done(function(res) {
                //alert(res);
                if(res.is_success == true){

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

                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    $("#add-form-cont").collapse('hide');
                    noty({
                                    width: 200,
                                    text: Translation(res.data),
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 3000,
                                    layout: 'topRight',
                              });

                    
               
                }else{
                    swal({
                        title:"Error",
                        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: Translation(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();
              
              var customer_id_fk      = $("#edit_customer_id_fk").val();
              var call_date           = $("#edit_call_date").val();
              var expect_pay_amount   = $("#edit_expect_pay_amount").val();
              var expect_pay_date     = $("#edit_expect_pay_date").val();
              var pay_note            = $("#edit_pay_note").val();
      


              var catId    = $("#edit_objid").val();

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

              Check1 = Checks('edit_customer_id_fk');
              Check2 = Checks('edit_call_date');
              Check3 = Checks('edit_expect_pay_amount');
              Check4 = Checks('edit_expect_pay_date');
              
            

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

                  $.ajax({
                      url: "models/crul_payment_notify.php",
                      type:"POST",
                      dataType : "JSON",
                      data : {customer_id_fk:customer_id_fk,
                              call_date:call_date,
                              expect_pay_amount:expect_pay_amount,
                              expect_pay_date:expect_pay_date,
                              pay_note:pay_note,
                              obj_id:catId,type:'update'},
                      complete:function(){
                        
                      },
                      beforeSend:function(){
                       
                      },
                      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',
                                    });
                        }
                      }
                  });
                }
      });

});





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

   



   // 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 table = $('.datatable-column-search-inputs').DataTable({
        
        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_notify.php",
        "data": function(d){
          d.type = "load";
          if(query_id !='not'){
            d.id =query_id ;
          }

          if(query_ic !='not'){
            d.idc =query_ic ;
          }
        }
        },
        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 '>
                                        
                                        <li class='text-primary-600'>
                                            <a href='#' class='text-success-600' onclick="make_paid(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('تم الدفع')+`'>
                                                <i class='icon-bell-check'></i>
                                            </a>
                                        </li>
                                        
                                        <li class='text-primary-600'>
                                            <a href='#' class='text-primary-400' onclick="edit_items(`+row[0]+`,'`+row[3]+`','`+row[4]+`','`+row[5]+`','`+escapeHtml(row[8])+`',`+row[10]+`)" data-popup='tooltip' data-original-title='`+Translation('تحرير')+`'>
                                                <i class='icon-pencil7'></i>
                                            </a>
                                        </li>

                                        <li class='text-danger-600'>
                                            <a href='#' 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": 4
            },

            

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


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


               },
               "targets": 1
            },


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

                        var state =``;
                        if(data ==1 ){
                          state =`<span class="label btn-block bg-success-400">`+Translation('تم الدفع')+`</span>`;
                        }else{

                          if(row[9] >=0){
                            state =`<span class="label btn-block bg-danger-400">`+Translation('تجاوز المدة بـ')+` (`+row[9]+`) `+Translation('ايام')+`</span>`;

                          }else{
                            state =`<span class="label btn-block bg-primary-400">`+Translation('بقي له')+` (`+(row[9] * -1)+`) `+Translation('ايام')+`</span>`;
                            
                          }

                        }
                        return  state;


               },
               "targets": 7
            },
            
            
            
           
            
            
            
            
            
        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {


            if(   aData[7] == 0 ){

              if(aData[9] >= 0){
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('danger');
                });
              }else{
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('info');
                });
              }
                
            }

            $("#total_amount").text(currency_format_display(aData[6]))
            $("#total_paid").text(currency_format_display(aData[7]))
            $("#total_unpaid").text(currency_format_display(aData[6] - aData[7]))
        },
        "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>`);  


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


});



