var table ;
    

    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,no_,amount,date_,staff_anme,notes,printing=null){
          
          notes       = decodeURIComponent_back(notes);
          staff_anme  = decodeURIComponent_back(staff_anme);

          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;">`+no_+`</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: left; font-size: 16px;" id="inv_slogan">`

                                          +Translation('استُلم من السيد')+` : <span style='font-weight:bold;'>` + staff_anme + `</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){
      
      
      
      $("#edit_objid").val(itemid);


      $.ajax({
          url: "models/crul_safe.php",
          type:"POST",
          dataType : "JSON",
          data: {"type":"get_edit","obj_id":itemid} ,
          complete:function(){
            //hideLoader();
          },
          beforeSend:function(){
            //showLoader("Deleting Product");
          },
          success: function(res) {

            if(res.is_success == true){
               
                $("#edit_staff_id_fk").val(res.data[0].staff_id_fk).selectpicker('refresh');
                $("#edit_capital_amount").val(res.data[0].safe_amount);
                $("#edit_date_of_add").val(res.data[0].date_of_add);
                $("#edit_capital_note").val(res.data[0].safe_note);
                $("#edit_branch_id_fk").val(res.data[0].branch_id_fk);
        
                $('#edit_form_cont').modal('toggle');

            }else{

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

            }
            
          }
      });

    

    }

  



    function delete_items(itemid) {
      block = $("#list_of_items_tbl");
      // bootstrap modal confirmation box
        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_capital.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 show_msg_accept(name=null){

      var msg ='';
      
        msg ='تمت الموافقة على الطلب من قبل السيد' ;
      
      swal({
                title: Translation("موافقة"),
                text: Translation(msg) + " : " + name,
                confirmButtonColor: "#66BB6A",
                type: "info"
            });

    }


    function show_msg_reject(name=null){

      var msg ='';
      
        msg ='تم رفض الطلب من قبل السيد' ;
      
      swal({
                title: Translation("رفض"),
                text: Translation(msg) + " : " + name,
                confirmButtonColor: "#66BB6A",
                type: "info"
            });

    }

    function show_msg(name=null){

      var msg ='';
      if(name==null){
        name='';
        msg ='لم يتم تأكيد استلام المبلغ لحد هذه اللحظة';
      }else{
        msg ='تم تأكيد استلام المبلغ من قبل السيد' ;
      }
      swal({
                title: Translation("معلومات"),
                text: Translation(msg) + " : " + name,
                confirmButtonColor: "#66BB6A",
                type: "info"
            });

    }


    function accept_request(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_capital.php",
                type:"POST",
                dataType : "JSON",
                data: {"type":"accepted","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 reject_request(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_capital.php",
                type:"POST",
                dataType : "JSON",
                data: {"type":"rejected","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 add_transfer(){
      $('#transfer_form_cont').modal('toggle');

    }


    function add_profit(){
      $('#profit_form_cont').modal('toggle');

    }


    

  

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

                            }
                            $("#amount_owner_staff_id_fk").html(attach);
                            $("#edit_staff_id_fk").html(attach);
                            $("#staff_name").html(attach);
                            $("#profit_staff_name").html(attach);
                            $("#edit_staff_name").html(attach);
                            $('#amount_owner_staff_id_fk').selectpicker('refresh');
                            $("#edit_staff_id_fk").selectpicker('refresh');
                            $("#staff_name").selectpicker('refresh');
                            $("#edit_staff_name").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
    }

    function get_Branch(){

                $.ajax({
                      url : 'models/crul_branch.php',
                      type : 'POST',
                      data : {type:'get',branch_id:BRANCH_ID},
                      dataType : 'json',
                      success : function(response) {
                          var attach ='<option class="text-black text-danger-800" selected="selected" value="">'+Translation('اختيار الفرع')+'</option>';
                          
                          for(var i=response.length-1 ; i >= 0;i--){

                            var tp =response[i][2];
                              
                            attach = attach + '<option class="text-black text-danger-800" data-subtext="'+Translation('الموقع')+' : '+response[i]['location']+'" value="'+response[i]['branch_id']+'">'+response[i]['branch_name']+'</option>';
                              
                               
                              
                          }
                          $("#branch_id_fk").html(attach);
                          $("#branch_id_fk1").html(attach);
                          // $('#branch_id_fk').selectpicker('refresh');

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

                }); // submit ajax

    }


    function get_Branch_btn_filter(){

                $.ajax({
                      url : 'models/crul_branch.php',
                      type : 'POST',
                      data : {type:'get',branch_id:BRANCH_ID},
                      dataType : 'json',
                      success : function(response) {
                          var attach =`<li><a href="index.php?p=safe"><i class="icon-close2 text-danger-600"></i>`+Translation('ازالة الفلتر')+`  </a></li>`;
                          
                          
                          for(var i=response.length-1 ; i >= 0;i--){

                            
                              
                            attach = attach + `<li><a href="index.php?p=safe&bid=`+response[i]['branch_id']+`"><i class="icon-store  text-teal"></i>`+response[i]['branch_name']+`  </a></li>`;
                               
                               
                              
                          }
                          $("#branch_filter").html(attach);
                          
                            
                      },
                      complete: function() {
                             //  me.data('requestRunning', false);
                      }

                }); // submit ajax

    }

$(document).ready(function() {
  
    get_Staff();
    get_Branch();

    $('#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 amount_owner_staff_id_fk  = $("#amount_owner_staff_id_fk").val();
      var capital_amount            = $("#capital_amount").val();
      var date_of_add               = $("#date_of_add").val();
      var capital_note              = $("#capital_note").val();
      


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

      Check1 = Checks('amount_owner_staff_id_fk');
      Check2 = Checks('capital_amount');
      Check3 = Checks('date_of_add');
      
      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_capital.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();

                    get_Staff();

                    $(".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 staff_id_fk               = $("#edit_staff_id_fk").val();
              var capital_amount            = $("#edit_capital_amount").val();
              var date_of_add               = $("#edit_date_of_add").val();
              var capital_note              = $("#edit_capital_note").val();
              var branch_id_fk              = $("#edit_branch_id_fk").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_staff_id_fk');
              Check2 = Checks('edit_capital_amount');
              Check3 = Checks('edit_date_of_add');
              Check4 = Checks('edit_branch_id_fk');
              
            

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

                  $.ajax({
                      url: "models/crul_safe.php",
                      type:"POST",
                      dataType : "JSON",
                      data : {staff_id_fk:staff_id_fk,
                              capital_amount:capital_amount,
                              date_of_add:date_of_add,
                              capital_note:capital_note,
                              branch_id_fk:branch_id_fk,
                              obj_id:catId,
                              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',
                                    });
                        }
                      }
                  });
                }
      });


    $('#transfer_form').submit(function(event) {
              event.preventDefault();
             
              
              
              var transfer_amount     = $("#transfer_amount").val();
              var factory_date_of_add = $("#factory_date_of_add").val();
              var transfer_note       = $("#transfer_note").val();
              var staff_name          = $("#staff_name").val();
              var branch_id_fk        = $("#branch_id_fk").val();
              



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

              Check1 = Checks('transfer_amount');
              Check2 = Checks('factory_date_of_add');
              Check3 = Checks('staff_name');
              Check4 = Checks('branch_id_fk');
              
            

              if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
                  $("#transfer_form_btn").attr('disabled',true);
                  $.ajax({
                      url: "models/crul_safe.php",
                      type:"POST",
                      dataType : "JSON",
                      data : {
                              staff_name:staff_name,
                              transfer_amount:transfer_amount,
                              factory_date_of_add:factory_date_of_add,
                              transfer_note:transfer_note,
                              branch_id_fk:branch_id_fk,
                              type:'withdraw'},
                      complete:function(){
                        $("#transfer_form_btn").attr('disabled',false);
                      },
                      beforeSend:function(){
                        $("#transfer_form_btn").attr('disabled',true);
                      },
                      success: function(res) {
                        if(res.is_success == false){
                          
                          $('#transfer_form_cont').modal('toggle');
                          $("#transfer_form")[0].reset();
                          swal({
                              title: Translation("خطأ"),
                              text: Translation(res.data),
                              confirmButtonColor: "#66BB6A",
                              type: "warning"
                          });
                        }else{
                          $("#transfer_form")[0].reset();
                          $("#staff_name").val('').selectpicker('refresh');
                          

                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);

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



    $('#profit_form').submit(function(event) {
              event.preventDefault();
             
              
              
              var transfer_amount     = $("#profit_amount").val();
              var factory_date_of_add = $("#profit_date_of_add").val();
              var transfer_note       = $("#profit_note").val();
              var staff_name          = $("#profit_staff_name").val();
              var branch_id_fk        = $("#branch_id_fk1").val();
              



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

              Check1 = Checks('profit_amount');
              Check2 = Checks('profit_date_of_add');
              Check3 = Checks('profit_staff_name');
              Check4 = Checks('branch_id_fk1');
              
            

              if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
                  $("#profit_form_btn").attr('disabled',true);
                  $.ajax({
                      url: "models/crul_safe.php",
                      type:"POST",
                      dataType : "JSON",
                      data : {
                              staff_name:staff_name,
                              transfer_amount:transfer_amount,
                              factory_date_of_add:factory_date_of_add,
                              transfer_note:transfer_note,
                              branch_id_fk:branch_id_fk,
                              type:'profit'},
                      complete:function(){
                        $("#profit_form_btn").attr('disabled',false);
                      },
                      beforeSend:function(){
                        $("#profit_form_btn").attr('disabled',true);
                      },
                      success: function(res) {
                        if(res.is_success == false){
                          
                          $('#profit_form_cont').modal('toggle');
                          $("#profit_form")[0].reset();
                          swal({
                              title: Translation("خطأ"),
                              text: Translation(res.data),
                              confirmButtonColor: "#66BB6A",
                              type: "warning"
                          });
                        }else{
                          $("#profit_form")[0].reset();
                          $("#profit_staff_name").val('').selectpicker('refresh');
                          

                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);

                          $('#profit_form_cont').modal('toggle');
                          noty({
                                          width: 200,
                                          text: Translation(res.data), //'Product Successfully Update',
                                          type: 'success',
                                          dismissQueue: true,
                                          timeout: 3000,
                                          layout: 'topRight',
                                    });
                        }
                        $("#profit_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'
        }
    });

  


   // 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': '&'+Left_Arraw+'arr;', 'previous': '&'+Right_Arraw+'arr;' }
            
        },
        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_tr = getQueryVariable("tr");
  var query_bid = getQueryVariable("bid");
   
  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_safe.php",
        "data": function(d){
          d.type = "load";
          if(query_id !='not'){
            d.id =query_id ;
          }

          if(query_tr !='not'){
            d.tr =query_tr ;
          }

          if(query_bid !='not'){
            d.bid =query_bid ;
          }

          d.branch_id=BRANCH_ID;
        }
        },
        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) {

                        var btns ='';

                      if(IS_VIEW==0){


                        if(row[4]=="Add" || row[4]=="Withdraw"){
                          btns = `

                                  <li class='text-primary-600'>
                                      <a href='#' class='text-purple-400' onclick="edit_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('تعديل')+`'>
                                          <i class='icon-pencil7 icon-2x'></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 icon-2x'></i>
                                      </a>
                                  </li>

                                        `;
                        }
                      }



                            return  `<ul class='icons-list pull-right'>
                                        
                                        `+btns+`                                       

                                    </ul>`;
                        }
          },


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

                        
                          return  currency_format_display(data);
                       


               },
               "targets": 2
            },


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

                        if(row[5] == '1'){

                          // return  `<span class="label btn-block bg-green-400">`+(data)+`</span>`;
                          return  `<a href='index.php?p=safe&tr=`+row[4]+`'  data-popup='tooltip' data-original-title='`+Translation('فلتر حسب النوع')+`'>`+(data)+`</a>`;

                        }else{
                          // return  `<span class="label btn-block bg-warning-400">`+(data)+`</span>`;
                          return  `<a href='index.php?p=safe&tr=`+row[4]+`'  data-popup='tooltip' data-original-title='`+Translation('فلتر حسب النوع')+`'>`+(data)+`</a>`;

                        }

                       


               },
               "targets": 4
            },


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

                        if(row[5] == '1'){

                          return  `<span class="label btn-block bg-green-400">`+Translation('اضافة')+`</span>`;
                        }else{
                          return  `<span class="label btn-block bg-warning-400">`+Translation('سحب')+`</span>`;
                        }

                       


               },
               "targets": 5
            },

            

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


                        return  `<a href='index.php?p=safe&id=`+row[11]+`'  data-popup='tooltip' data-original-title='`+Translation('فلتر حسب الاسم')+`'>`+data+`</a>`;


               },
               "targets": 6
            },


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


                        return  `<a href='index.php?p=safe&bid=`+row[12]+`'  data-popup='tooltip' data-original-title='`+Translation('Filter According to Branch')+`'>`+data+`</a>`;


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


            if(   aData[13] == 1 ){
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('success');
                });
            }

            if(   aData[5] == 'Withdraw' ){
                 
              $(nRow).children().each(function (index, td) {
                $(this).addClass('danger');
              });
                 
                
            }

            $("#total_amount").text(currency_format_display(aData[9]))
            $("#total_transfer").text(currency_format_display(aData[10]))
            $("#total_remain").text(currency_format_display(aData[9] - aData[10]))


        },
        "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>`); 

        if(IS_VIEW==0){

        
            $("div.datatable-header").append(`<a 
                                      style="margin-right:10px; text-transform: none !important;"
                                      data-target="#add-form-cont"
                                      href="javascript:;"
                                      class="btn bg-orange"
                                      id="add_transfer_btn" onclick="add_transfer();">
                                        <i class="icon-briefcase3"></i> `+Translation('سحب مبلغ')+`
                                    </a>`);


            $("div.datatable-header").append(`<a 
                                      style="margin-right:10px; text-transform: none !important;"
                                      data-target="#add-form-cont"
                                      href="javascript:;"
                                      class="btn bg-green"
                                      id="add_profit_btn" onclick="add_profit();">
                                        <i class="icon-cash"></i> `+Translation('اضافة مبلغ')+`
                                    </a>`);
        }


          $("div.datatable-header").append(`&nbsp;<div class="btn-group">
                          <button id="inv_filter_btn" type="button"
                          class="btn bg-teal-400 btn-labeled dropdown-toggle" style="text-transform: none !important;"
                          data-toggle="dropdown"><b><i class="icon-filter4">
                          </i></b> <span id="inv_filter">`+Translation('الفرع')+`</span> <span class="caret"></span></button>
                          <ul class="dropdown-menu dropdown-menu-right" id="branch_filter">
                          
                        </ul>
                      </div>`);


          get_Branch_btn_filter();

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


});



