
  var table ;
    
   
  var query_id = getQueryVariable("id");
  var query_pid = getQueryVariable("pid");
  var query_sid = getQueryVariable("sid");
  var product_id = $("#product_id_search").val();


    function get_Stock(){

            $.ajax({
                  url : 'models/crul_stock.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<li><a  href="index.php?p=stock_report"><i class="icon-stackoverflow text-orange-800 text-black"></i><span id="stocks_filter_link_0">'+Translation('جميع المخازن')+'</span></a></li>';
                      var attach1 ='<option value="" selected="selected">'+Translation('تحديد المخزن')+'</option>';
                        for(var i=response.length-1 ; i >= 0;i--){
                          var tp =Translation("خزن");
                          if(response[i][2]==1){tp =Translation("انتاج");}
                          attach1 = attach1 + '<option data-subtext="'+tp+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';

                          if(response[i][2]==1){
                            attach = attach + '<li><a  href="index.php?p=stock_report&id='+response[i][0]+'"><i class="icon-scissors text-success"></i> <span id="stocks_filter_link_'+response[i][0]+'">'+response[i][1]+'</span></a></li>';
                          }else{
                            attach = attach + '<li><a  href="index.php?p=stock_report&id='+response[i][0]+'"><i class="icon-store text-info"></i> <span id="stocks_filter_link_'+response[i][0]+'">'+response[i][1]+'</span></a></li>';
                          }
                           
                          
                        }
                        $("#stock_filter").html(attach);
                        $("#stock_id").html(attach1);

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

            }); // submit ajax

    }


    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>';
                      var attach ='';
                      
                        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]+' || '+Translation('الرمز التسلسلي')+' : '+response[i][3]+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          
                           
                          
                        }
                        $("#product_id_search").html(attach);
                        $('#product_id_search').selectpicker('refresh');
                        change_status_btn_text();
                        
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);

                  }

            }); // submit ajax

    }

    function change_filter_btn_text(){

      var id = getQueryVariable("id");

      if(id != 'not'){
        var text_btn = $("#stocks_filter_link_"+id).text();
        $("#stock_btn").text(text_btn);
      }else{
        var text_btn = $("#stocks_filter_link_0").text();
        $("#stock_btn").text(text_btn);

      }
      
    }

      var id_  ='';
      var pid_ ='';
      var sid_ ='';

    function change_status_btn_text(){

      var sid   = getQueryVariable("sid");
      var id    = getQueryVariable("id");
      var pid   = getQueryVariable("pid");

      

      if(id != 'not'){
        id_ = '&id='+id;
      }

      if(sid != 'not'){
        sid_ = '&sid='+sid;
      }

      if(pid != 'not'){
        pid_ = '&pid='+pid;
        $("#product_id_search").val(pid).selectpicker('refresh');

      }


     


      var attach ='';

      attach = `  <li><a  href="index.php?p=stock_report`+id_+pid_+`"><i class="icon-close2 text-danger-800 text-black"></i><span id="status_filter_link">`+Translation('ازالة الفلتر')+`</span></a></li>
                  <li><a  href="index.php?p=stock_report`+id_+pid_+`&sid=0"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_0">`+Translation('متوفر في مخزن الخزن من دون تالف')+`</span></a></li>
                  <li><a  href="index.php?p=stock_report`+id_+pid_+`&sid=1"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_1">`+Translation('مباع بالكامل')+`</span></a></li>
                  <li><a  href="index.php?p=stock_report`+id_+pid_+`&sid=2"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_2">`+Translation('متوفر في مخزن الانتاج /غير مستخدم من دون تالف')+`</span></a></li>
                  <li><a  href="index.php?p=stock_report`+id_+pid_+`&sid=3"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_3">`+Translation('استخدم في الانتاج')+`</span></a></li>
                  <li><a  href="index.php?p=stock_report`+id_+pid_+`&sid=4"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_4">`+Translation('تم الانتاج وانتهت المادة')+`</span></a></li>
                  <li><a  href="index.php?p=stock_report`+id_+pid_+`&sid=5"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_5">`+Translation('مباع بالتجزئة')+`</span></a></li>
                  <li><a  href="index.php?p=stock_report`+id_+pid_+`&sid=6"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_6">`+Translation('تالف بالكامل')+`</span></a></li>
                  <li><a  href="index.php?p=stock_report`+id_+pid_+`&sid=7"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_7">`+Translation('مسترجع')+`</span></a></li>
                  <li><a  href="index.php?p=stock_report`+id_+pid_+`&sid=8"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_8">`+Translation('متوفر في مخزن الخزن ويحوي تالف')+`</span></a></li>
                  <li><a  href="index.php?p=stock_report`+id_+pid_+`&sid=9"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_9">`+Translation('مباع بالتجزئة ومستخدم في الانتاج')+`</span></a></li>
                  <li><a  href="index.php?p=stock_report`+id_+pid_+`&sid=10"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_10">`+Translation('استخدم كليا (مباع بالتجزئة و مستخدم في الانتاج)')+`</span></a></li>
                  <li><a  href="index.php?p=stock_report`+id_+pid_+`&sid=11"><i class="icon-filter4 text-success-800 "></i><span id="status_filter_link_11">`+Translation('متوفر في مخزن الانتاج /غير مستخدم ويحتوي تالف')+`</span></a></li>
                  `;
      
      $("#status_filter").html(attach);

      if(sid != 'not'){       
        var text_btn = $("#status_filter_link_"+sid).text();
        $("#status_btn").text(text_btn);
        $("#status_color").removeClass('bg-danger-400');
        $("#status_color").addClass('bg-success-400');

      }
      
    }

    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
          var pair = vars[i].split("=");
          if (pair[0] == variable) {
            return pair[1];
          }
        }
        return 'not';
    }

    function select_all(){
        $('#product_id_search').selectpicker('selectAll');

    }

    function deselect_all(){
        $('#product_id_search').selectpicker('deselectAll');

        window.location="index.php?p=stock_report"+id_+sid_;


    }


    function get_totals(){

     

       $.ajax({
                  url : 'models/crul_stock_report.php',
                  type : 'POST',
                  data : {  type  : "get_total",
                            id    : query_id ,
                            pid   : query_pid ,
                            sid   : query_sid 
                                            },
                  dataType : 'json',
                  success : function(response) {
                   
                        $("#total_remaind").html(response['data'][0]);
                       
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

    }

            // $("#total_remaind").text( tot_rem.toFixed(2) + " م")


$(document).ready(function() {

    get_Stock(); 
    get_Products();
    get_totals();

 
    

});



    function search_Product(){
        product_id = $("#product_id_search").val();
        // $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
        if(product_id >0){
          window.location="index.php?p=stock_report&pid="+product_id+id_+sid_;
        }else{
          window.location="index.php?p=stock_report"+id_+sid_;
        }
    }

    function show_detail_page(){
        product_id = $("#product_id_search").val();
        console.log(product_id)
        if(product_id !=null){
          window.location="index.php?p=stock_report&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();
    




   // 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': '&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 tot_rem = 0;
   
   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 ],
            [  '10', '25', '50', '100' ]
        ],
        "processing": true,
        "serverSide": true,
        "ajax": {
        "url" : "models/crul_stock_report.php",
        "data": function(d){
          d.type = "load";
          if(query_id !='not'){
            d.id =query_id ;
          }
          if(query_pid !='not'){
            d.pid =query_pid ;
          }
          if(query_sid !='not'){
            d.sid =query_sid ;
          }

          if((product_id > 0 && product_id !=null && product_id !=undefined && product_id !='') ){
            d.pid =product_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": 11,
              "data": null,
              "render": function (data,type,row) {

                           


                            var tot_rem = row[6] -row[10] -row[9] -row[8] -row[7];
                            return tot_rem.toFixed(2) + " م";
                        }
          },

         

         

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

            
            // tot_rem+= (aData[6] - aData[10] - aData[9] - aData[8] - aData[7] );
            // $("#total_remaind").text( tot_rem.toFixed(2) + " م")
            


            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>`);   
         // $("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> `+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><span id="stock_btn">`+Translation('المخازن')+`</span>  <span class="caret"></span></button>
         //                                  <ul class="dropdown-menu dropdown-menu-right" id="stock_filter">
         //                                  </ul>
         //                                  </div>`); 

         // $("div.datatable-header").append(`&nbsp;<div class="btn-group">
         //                                  <button type="button" id="status_color"
         //                                  class="btn bg-danger-400 btn-labeled dropdown-toggle" 
         //                                  data-toggle="dropdown"><b><i class="icon-filter4">
         //                                  </i></b><span id="status_btn">`+Translation('فلتر الحالة')+`</span>  <span class="caret"></span></button>
         //                                  <ul class="dropdown-menu dropdown-menu-right" id="status_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 onchange1="search_Product();" multiple="multiple" class="form-control  multi_lang" data-live-search="true" name="product_id_search" id="product_id_search" data-width="100%" placeholder="اسم المادة">
                                                    
         //                                              </select>
         //                                            </div>
         //                                          </div>

         //                                          <div class="input-group-btn">
         //                                            <!--<button type="button" class="btn btn-info" onclick="select_all();" id="select-all-values">Select all</button> -->
         //                                            <button type="button" class="btn btn-default" onclick="deselect_all();" id="deselect-all-values">Deselect all</button>
                                                  

         //                                            <button type="button" class="btn bg-pink-400 btn-labeled " onclick="show_detail_page();">
         //                                              <b><i class="icon-search4"></i></b>
         //                                              `+Translation('عرض تفاصيل هذه المادة في جميع المخازن')+`
         //                                            </button>
         //                                          </div>


         //                                    </div>`); 

            this.api().columns().every( function() {
                var column = this;
                // change_filter_btn_text();   

            });


        }
    });

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


});



