var table ;

    function edit_items(itemid){
      
      $.ajax({
          url: "models/crul_expenses.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_expenses_group_id_fk").val(res.data[0].expenses_group_id_fk).selectpicker('refresh');
      
                $("#edit_expenses_name").val(res.data[0].expenses_name);
                $("#edit_expenses_unit_price").val(res.data[0].expenses_unit_price);
                $("#edit_expenses_date").val(res.data[0].expenses_date);
                $("#edit_bill_number").val(res.data[0].bill_number);
                $("#edit_expenses_note").val(res.data[0].expenses_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"
                  });

            }
            
          }
      });    
      
      $("#edit_objid").val(itemid);
     

    }

    function show_files(itemid) {

             

      var attach =  `
                      <div class="col-lg-3 col-sm-6">
                        <div class="thumbnail">
                          <div class="thumb">
                            <img src="`+itemid+`" alt="">
                            <div class="caption-overflow">
                              <span>
                                <a href="`+itemid+`" target="_blank" data-popup="lightbox" class="btn border-white text-white btn-flat btn-icon btn-rounded"><i class="icon-plus3"></i></a>
                                
                              </span>
                            </div>
                          </div>

                          <div class="caption">
                            <h6 class="no-margin"><a href="#" class="text-default">File No : `+1+`</a> <a href="#" class="text-muted"><i class="icon-three-bars pull-right"></i></a></h6>
                          </div>
                        </div>
                      </div>` ;


                    
                    $("#file_attach").html(attach);
                    $('#show_files').modal('toggle');
                



    }



    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_expenses.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 get_Expenses_Group(){

      $.ajax({
                      url : 'models/crul_expenses_group.php',
                      type : 'POST',
                      data : {type:'get'},
                      dataType : 'json',
                      success : function(response) {
                        console.log(response)
                          var attach ='<option value="" selected="selected">'+Translation('اسم الفئة')+'</option>';
                          
                            for(var i=response.length-1 ; i >= 0;i--){
                              
                              attach = attach + '<option value="'+response[i][0]+'">'+response[i][1]+'</option>';
                             

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

                }); // submit ajax

    }

    function get_Expenses_Sub_Group(){

      $.ajax({
                      url : 'models/crul_expenses_sub_group.php',
                      type : 'POST',
                      data : {type:'get'},
                      dataType : 'json',
                      success : function(response) {
                        console.log(response)
                          var attach ='<option value="" selected="selected">'+Translation('اسم المجموعة الفرعية')+'</option>';
                          
                            for(var i=response.length-1 ; i >= 0;i--){
                              var tp = response[i][2]
                              attach = attach + '<option data-group-id="'+response[i][3]+'" data-subtext="'+Translation('الفئة')+' : '+tp+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                              

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

                }); // submit ajax

    }

    function set_date(){

        var now = new Date();
        var month = (now.getMonth() + 1);               
        var day = now.getDate();
        if (month < 10) 
            month = "0" + month;
        if (day < 10) 
            day = "0" + day;
        var today = now.getFullYear() + '-' + month + '-' + day;
        $('#first_date').val(today);
        $('#second_date').val(today);
    }

    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

    }


$(document).ready(function() {
  
    get_Expenses_Group();
    set_date();
    get_Branch();



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

      // var expenses_sub_group_id_fk  = $("#expenses_sub_group_id_fk").val();
      var expenses_group_id_fk      = $("#expenses_group_id_fk").val();
      var expenses_name             = $("#expenses_name").val();
      // var expenses_quantity         = $("#expenses_quantity").val();
      var expenses_quantity         = 1;
      var expenses_unit_price       = $("#expenses_unit_price").val();
      var expenses_currency         = 1;
      // var expenses_currency         = $("#expenses_currency").val();
      var expenses_date             = $("#expenses_date").val();
      var expenses_note             = $("#expenses_note").val();
      var branch_id_fk              = $("#branch_id_fk").val();

      // var expenses_group_id_fk = $("#expenses_sub_group_id_fk  option:selected").attr('data-group-id');



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

      // Check1 = Checks('expenses_group_id_fk');
      // Check2 = Checks('expenses_sub_group_id_fk');
      Check2 = Checks('expenses_name');
      // Check3 = Checks('expenses_quantity');
      Check4 = Checks('expenses_unit_price');
      // Check5 = Checks('expenses_currency');

      var formData = new FormData(this);
      // formData.append("expenses_group_id_fk", expenses_group_id_fk);
      formData.append("type", 'create');


      //Check5 = Checks('sell_price');
      //Check6 = Checks('sell_price_percentage');




      if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
            $("#submit_add_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_expenses.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) {
                
                if(res.is_success == true){

                    $("#add_form")[0].reset();

                    $("#expenses_group_id_fk").val('').selectpicker('refresh');

                    $(".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: (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 expenses_sub_group_id_fk  = $("#edit_expenses_sub_group_id_fk").val();
              var expenses_group_id_fk      = $("#edit_expenses_group_id_fk").val();
              var expenses_name             = $("#expenses_name").val();
              var expenses_quantity         = $("#edit_expenses_quantity").val();
              var expenses_unit_price       = $("#edit_expenses_unit_price").val();
              var expenses_currency         = $("#edit_expenses_currency").val();
              var expenses_date             = $("#edit_expenses_date").val();
              var expenses_note             = $("#edit_expenses_note").val();

              // var expenses_group_id_fk      = $("#edit_expenses_sub_group_id_fk  option:selected").attr('data-group-id');
              
              var Check1 = true;
              var Check2 = true;
              var Check3 = true;
              var Check4 = true;
              var Check5 = true;
              var Check6 = true;

              // Check1 = Checks('edit_expenses_group_id_fk');
              Check2 = Checks('edit_expenses_name');
              // Check3 = Checks('edit_expenses_quantity');
              Check4 = Checks('edit_expenses_unit_price');
              // Check5 = Checks('edit_expenses_currency');

              var formData = new FormData(this);
              // formData.append("edit_expenses_group_id_fk", expenses_group_id_fk);
              formData.append("type", 'update');
            

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

                  $.ajax({
                          url: "models/crul_expenses.php",
                          type:"POST",
                          dataType : "JSON",
                          data:formData,
                          cache:false,
                          contentType: false,
                          processData: false
                          ,
                      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',
                                });
                        }
                      }
                  });
                }
      });


    $('#filter_btn').on('click',function(){
      
      if($("#first_date").val()!='' && $("#second_date").val()!='' ){
        var d1 = $("#first_date").val();
        var d2 = $("#second_date").val();
        
        var _href ="index.php?p=expenses";

        if(d1 !=''){
         
          _href = _href + "&d1="+d1;
        }

        if(d2 !=''){
         
          _href = _href + "&d2="+d2;
        }



      
        window.location = _href;
      }else{
            swal({
                    title:"Error",
                    text: Translation('الرجاء قم بتحديد السنة وا الشهر'),
                    confirmButtonColor: "#66BB6A",
                    type: "warning"
                });
      }


    });



});


  $('#add_new_category_form').on('submit', function(e){

        e.preventDefault();

        block = $(this).parent();
        // \block

        var name                 = $("#objname").val();
        var group_description    = $("#group_description").val();

        var Check1 = true;
        var Check2 = true;

        if(name =='') {
           $("#objname").closest('.form-group').removeClass('has-success');
           $("#objname").closest('.form-group').addClass('has-error');
           Check1 = false;
           noty({
                    width: 200,
                    text: Translation("الرجاء قم بادخال اسم الفئة"),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'top',
              });
        }else{
           $("#objname").closest('.form-group').removeClass('has-error');
           $("#objname").closest('.form-group').addClass('has-success');
        }

      

        if(Check1 && Check2){
          $("#submit_add_cat_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_expenses_group.php",
                type:"POST",
                dataType:"JSON",
                data : {name:name,group_description:group_description,type:'create'}
            })
            .done(function(res) {
                //alert(res);
                if(res.is_success == true){
                    get_Expenses_Group();
                    noty({
                                    width: 200,
                                    text: Translation(res.data),
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 3000,
                                    layout: 'topRight',
                              });
                    $('#add_new_category').modal('toggle');
                }else{
                    swal({
                        title: Translation("خطأ"),
                        text: Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "error"
                    });
                }
                $("#submit_add_cat_btn").attr('disabled',false);
            })
            .fail(function(err) {
                 swal({
                    title: Translation("خطأ"),
                    text: Translation(err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                 $("#submit_add_cat_btn").attr('disabled',false);
            })
            .always(function() {
                console.log("complete");
            });
        }

  });

  



  var query_y    = getQueryVariable("d1");
  var query_m    = getQueryVariable("d2");
  var query_d    = getQueryVariable("d");


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

 

  if(query_y != 'not' ){
    $("#first_date").val(query_y);
  }

  if( query_m != 'not'){
    $("#second_date").val(query_m);
  }

 


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

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

   // for image uploader

  



    //
    // AJAX upload
    //





   // end image uploader



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


    

    // Individual column searching with text inputs
    $('.datatable-column-search-inputs tfoot td').not(':last-child').each(function () {
        var title = $('.datatable-column-search-inputs thead th').eq($(this).index()).text();
        $(this).html('<input type="text" class="form-control input-sm" placeholder="'+Translation('بحث عن')+' '+title+'" />');
    });
    
    
  var query_id = getQueryVariable("id");
  var query_sid = getQueryVariable("sid");
   
  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_expenses.php",
        "data": function(d){
          d.type = "load";
          if(query_id !='not'){
            d.id =query_id ;
          }

          if(query_sid !='not'){
            d.sid =query_sid ;
          }

          if(query_y !='not'){
            d.d1 =query_y ;
          }
          if(query_m !='not'){
            d.d2 =query_m ;
          }

          if(query_d !='not'){
            d.d =query_d ;
          }
          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) {

                        if(IS_VIEW==0){


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

                                        <li class='text-primary-600'>
                                            <a  class='text-primary-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  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>

                                    </ul>`;

                        }else{
                          return '';
                        }
                  }
          },


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

                       
                          return  currency_format_display(data,'$');
                        
                        


               },
               "targets": 2
            },

            

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


                        return  `<a href='index.php?p=expenses&id=`+row[8]+`'  data-popup='tooltip' data-original-title='`+Translation('عرض جميع المصاريف التابعة لهذه الفئة')+`'>`+data+`</a>`;


               },
               "targets": 7
            },

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

                      if(data == null || data ==''){
                        
                        return  ` <img  src="assets/images/placeholder.jpg" class="img-rounded img-lg">   `;
                      }else{
                        return  `<a  onclick="show_files('`+row[5]+`')"> <img src="`+data +`" width="100" class="img-rounded img-l">  </a>`;

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


            if(   aData[9] == 0 ){
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('warning-active');
                });
            }
        },
        "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>`);   
          if(IS_VIEW==0){
            $("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'
    });


});



