
var table 
    
    function edit_items(itemid,itemName,S_location,branch_id_fk,notes){
      itemName      = decodeURIComponent_back(itemName);
      S_location    = decodeURIComponent_back(S_location);
      
      notes         = decodeURIComponent_back(notes);

      $("#edit_objid").val(itemid);
      $("#edit_stock_name").val(itemName);
      $("#edit_location").val(S_location);
      $("#edit_branch_id_fk").val(branch_id_fk);


       
      $("#edit_stock_note").val(notes);
      $('#edit_form_cont').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_stock.php",
                type:"POST",
                dataType : "JSON",
                data: {"type":"delete","obj_id":itemid} ,
                complete:function(){
                 // hideLoader();
                },
                beforeSend:function(){
                 // showLoader("Deleting Category");
                },
                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_Products(){

            $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(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][2]+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          
                           
                          
                        }
                        $("#product_id_search").html(attach);
                        $('#product_id_search').selectpicker('refresh');
                        
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

    }


    function get_Stock(){

            $.ajax({
                  url : 'models/crul_stock.php',
                  type : 'POST',
                  data : {type:'get',branch_id:BRANCH_ID},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='';
                      
                        for(var i=response.length-1 ; i >= 0;i--){
                          
                            attach = attach + '<li><a href="index.php?p=stock_detail&id='+response[i][0]+'"><i class="icon-store text-info"></i> '+response[i][1]+'</a></li>';
                          
                           
                          
                        }
                        $("#stock_filter").html(attach);
                        
                  },
                  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 value="" selected="selected">'+Translation('تحديد الفرع')+'</option>';
                      
                      for(var i=response.length-1 ; i >= 0;i--){
                          
                      
                        attach = attach + '<option data-subtext="'+response[i].location+'" value="'+response[i].branch_id+'">'+response[i].branch_name+'</option>';
                        
                      }
                        $("#branch_id_fk1").html(attach);
                        $("#edit_branch_id_fk1").html(attach);
                        $('#branch_id_fk').selectpicker('refresh');
                        // $("#edit_stock_id_fk").selectpicker('refresh');
                  },
                  complete: function() {
                         
                  }

            }); // submit ajax

    }


     function get_Branch_all(){



            $.ajax({
                  url : 'models/crul_branch.php',
                  type : 'POST',
                  data : {type:'get_branch',branch_id:BRANCH_ID},
                  dataType : 'json',
                  success : function(response) {
                      var attach ='<option value="" selected="selected">'+Translation('تحديد الفرع')+'</option>';
                      
                      for(var i=response.length-1 ; i >= 0;i--){
                          
                      
                        attach = attach + '<option data-subtext="'+response[i].location+'" value="'+response[i].branch_id+'">'+response[i].branch_name+'</option>';
                        
                      }
                        $("#branch_id_fk").html(attach);
                        $("#edit_branch_id_fk").html(attach);
                        $('#branch_id_fk').selectpicker('refresh');
                        // $("#edit_stock_id_fk").selectpicker('refresh');
                  },
                  complete: function() {
                         
                  }

            }); // submit ajax

    }



$(document).ready(function() {

    get_Branch();

    get_Branch_all();
    
    
    $('#add_form').submit(function(event) {
            event.preventDefault();
            
            var stock_name    = $("#stock_name").val();
            var location      = $("#location").val();
            var branch_id_fk  = $("#branch_id_fk").val();
            
            var sku           = '';
            var stock_note    = $("#stock_note").val();

            var Check1 = true;
            var Check2 = true;

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

            
          

            if(Check1 && Check2){
              $("#submit_add_btn").attr('disabled',true);
                $.ajax({
                    url: "models/crul_stock.php",
                    type:"POST",
                    dataType : "JSON",
                    data : {stock_name    : stock_name,
                            location      : location,
                            branch_id_fk  : branch_id_fk,
                            stock_note    : stock_note,
                            type          : 'create'}
                })
                .done(function(res) {
                  //alert(res);
                  if(res.is_success == true){
                      $("#add_form")[0].reset();
                      $(".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: Translation("خطأ"),
                          text: Translation(res.data),
                          confirmButtonColor: "#66BB6A",
                          type: "error"
                      });
                  }
                  $("#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 catId         = $("#edit_objid").val();
            var stock_name    = $("#edit_stock_name").val();
            var location      = $("#edit_location").val();
            // var sku           = $("#edit_sku").val();
            var branch_id_fk  = $("#edit_branch_id_fk").val();
            
            var stock_note    = $("#edit_stock_note").val();

            var Check1 = true;
            var Check2 = true;

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

          
           

            if(Check1 && Check2 ){
                $.ajax({
                    url: "models/crul_stock.php",
                    type:"POST",
                    dataType : "JSON",
                    data : {stock_name    :stock_name,
                            location      :location,
                            branch_id_fk  :branch_id_fk,
                            stock_note    :stock_note,
                            obj_id        :catId,
                            type          :'update'},
                    complete:function(){
                      
                    },
                    beforeSend:function(){
                      
                    },
                    success: function(res) {
                      if(res.is_success == false){
                          
                          $('#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',
                                });
                      }
                    }
                });
              }
    });


    

});

    
    var product_id = $("#product_id_search").val();

    function search_Product(){
        product_id = $("#product_id_search").val();
        $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
    }

    function show_detail_page(){
        product_id = $("#product_id_search").val();
        if(product_id >0){
          window.location="index.php?p=stock_detail&pid="+product_id;
        }else{
          noty({
                  width: 200,
                  text: Translation('قم باختيار مادة'), //'Product Successfully Update',
                  type: 'error',
                  dismissQueue: true,
                  timeout: 3000,
                  layout: 'topRight',
                });
        }
    }




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


    $('.select-size-xs').select2({
        containerCssClass: 'select-xs'
    });

   // Setting datatable defaults
    $.extend( $.fn.dataTable.defaults, {
        autoWidth: false,
        columnDefs: [{ 
            orderable: false,
            width: '100px',
            targets: [ 4 ]
        }],
        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 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 ],
            [  '10', '25', '50', '100' ]
        ],
        "processing": true,
        "serverSide": true,
        "ajax": {
        "url" : "models/crul_stock.php",
        "data": function(d){
          d.type = "load";

          if(product_id > 0 && product_id !=null && product_id !=undefined && product_id !=''){
            d.pid =product_id ;
          }

          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": 6,
              "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]+`,'`+escapeHtml(row[1])+`','`+escapeHtml(row[2])+`','`+row[6]+`','`+escapeHtml(row[4])+`')" data-popup='tooltip' data-original-title='`+Translation('تعديل')+`'>
                                                <i class='icon-pencil7'></i>
                                            </a>
                                        </li>

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

                                    </ul>`;
                  }else{
                    return '';
                  }
                }
          },

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


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


             },
             "targets": 1
          },

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


            if(   aData[4] == 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>`); 
          }

         $("div.datatable-header").append(`&nbsp;<div class="btn-group">
                                          <button type="button" 
                                          class="btn bg-teal-400 btn-labeled dropdown-toggle" 
                                          data-toggle="dropdown"><b><i class="icon-filter4">
                                          </i></b>`+Translation('المخازن')+`  <span class="caret"></span></button>
                                          <ul class="dropdown-menu dropdown-menu-right" id="stock_filter">
                                          </ul>
                                          </div>`); 

         $("div.datatable-header").append(` <div class="form-group">

                                                  <div class="col-sm-6">
                                                    <div class="input-group">
                                                      <label class="input-group-addon text-black text-danger-800">`+Translation('بحث عن مادة في جميع المخازن')+`</label>
                                                      <select onchange="search_Product();" class="form-control  multi_lang" data-live-search="true" name="product_id_search" id="product_id_search" data-width="100%" placeholder="اسم المادة">
                                                    
                                                      </select>
                                                    </div>
                                                  </div>
                                                  <button type="button" class="btn bg-pink-400 btn-labeled " onclick="show_detail_page();">
                                                    <b><i class="icon-search4"></i></b>
                                                    `+Translation('عرض تفاصيل هذه المادة في جميع المخازن')+`
                                                  </button>

                                            </div>`); 


                



            this.api().columns().every( function() {
                var column = this;
                
                // $('#product_id_search').selectpicker('refresh');
            });

            get_Stock();   
            get_Products();   
        }
    });

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


});



