
var table 

   var query_id = getQueryVariable("id");
   var query_pid = getQueryVariable("pid");
   var query_sid = getQueryVariable("sid");
   var query_bid = getQueryVariable("bid");

    function transfer_stock(itemid,on_hand,stock_id){

      if(on_hand <= 0){
        swal({
                title: Translation("خطأ"),
                text: Translation('الكمية المتوفرة في جميع المخازن اقل من الصفر لا يمكن النقل'),
                confirmButtonColor: "#2196F3",
                type: "error"
            });
      }else{
        if(stock_id !='all'){
          $("#stock_id").val(stock_id);

        }
        $("#product_id").val(itemid);
        $("#on_hand_qty").val(on_hand);
        $(".on_hand_qty").text(on_hand)

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

    // finish_product

    


    function used_in_production(itemid,on_hand,stock_id){

      if(on_hand <= 0){
        swal({
                title: Translation("خطأ"),
                text: Translation('الكمية المتوفرة في جميع المخازن اقل من الصفر'),
                confirmButtonColor: "#2196F3",
                type: "error"
            });
      }else{
        if(stock_id !='all'){
          $("#stock_id_used").val(stock_id);

        }
        $("#product_id").val(itemid);
        $("#on_hand_qty").val(on_hand);
        $(".on_hand_qty").text(on_hand)

        // $("#on_hand_qty_used").val(on_hand);
        // $("#id_production").val(itemid);
        $('#production_form_cont').modal('toggle');
      }
       
    }

  

    
    

    function add_damage(itemid,on_hand,stock_id){

      if(on_hand <= 0){
        swal({
                title: Translation("خطأ"),
                text: Translation('الكمية المتوفرة في جميع المخازن اقل من الصفر'),
                confirmButtonColor: "#2196F3",
                type: "error"
            });
      }else{
        if(stock_id !='all'){
          $("#stock_id_damage").val(stock_id);

        }
        $("#product_id").val(itemid);
        $("#on_hand_qty").val(on_hand);
        $(".on_hand_qty").text(on_hand)

        // $("#on_hand_qty_damage").val(on_hand);
        // $("#id_damage").val(itemid);
       $('#add_damage_form_cont').modal('toggle');
      }
       
    }

    function add_expired(itemid,on_hand,stock_id){

      if(on_hand <= 0){
        swal({
                title: Translation("خطأ"),
                text: Translation('الكمية المتوفرة في جميع المخازن اقل من الصفر'),
                confirmButtonColor: "#2196F3",
                type: "error"
            });
      }else{
        if(stock_id !='all'){
          $("#stock_id_expire").val(stock_id);

        }
        $("#product_id").val(itemid);
        $("#on_hand_qty").val(on_hand);
        $(".on_hand_qty").text(on_hand)

        // $("#on_hand_qty_expire").val(on_hand);
        // $("#id_expire").val(itemid);
        $('#add_expire_form_cont').modal('toggle');
      }
       
    }

  


    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 ='<li><a  href="index.php?p=stock_detail"><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  =response[i][2]
                          
                          attach1 = attach1 + '<option data-subtext="'+tp+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';

                          attach = attach + '<li><a  href="index.php?p=stock_detail&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);
                        $("#to_stock_id").html(attach1);
                        $("#stock_id_used").html(attach1);
                        $("#stock_id_damage").html(attach1);
                        $("#stock_id_expire").html(attach1);

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

            }); // 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) {
                    //console.log(response)
                      var attach ='<li><a  href="index.php?p=stock_detail"><i class="icon-stackoverflow text-orange-800 text-black"></i><span id="branch_filter_link_0">'+Translation('جميع الافرع')+'</span></a></li>';
                      var attach1 ='<option value="" selected="selected">'+Translation('تحديد الفرع')+'</option>';
                      for(var i=response.length-1 ; i >= 0;i--){
                                         
                       
                            attach = attach + '<li><a  href="index.php?p=stock_detail&bid='+response[i].branch_id+'"><i class="icon-office text-info"></i> <span id="branch_filter_link_'+response[i].branch_id+'">'+response[i].branch_name+'</span></a></li>';  
                          
                      }
                        
                      $("#branch_filter").html(attach);
                        
                        change_filter_btn_text();
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                         get_Products();
                  }

            }); // submit ajax

    }


    function get_Supplier(){

            $.ajax({
                  url : 'models/crul_supplier.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<li><a  href="index.php?p=stock_detail"><i class="icon-stackoverflow text-orange-800 text-black"></i><span id="supplier_filter_link_0">'+Translation('جميع الموردين')+'</span></a></li>';
                      var attach1 ='<option value="" selected="selected">'+Translation('تحديد المورد')+'</option>';
                      for(var i=response.length-1 ; i >= 0;i--){
                                         
                       
                            attach = attach + '<li><a  href="index.php?p=stock_detail&sid='+response[i][0]+'"><i class="icon-truck text-info"></i> <span id="supplier_filter_link_'+response[i][0]+'">'+response[i][1]+'</span></a></li>';  
                          
                      }
                        
                      $("#supplier_filter").html(attach);
                        
                        change_filter_btn_text();
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                         get_Products();
                  }

            }); // 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>';
                      
                        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');
                        // change_status_btn_text();
                      
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);

                  }

            }); // submit ajax

    }

    function change_filter_btn_text(){

      var id = getQueryVariable("id");

      if(id != 'not' && id != 'all'){
        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 bid = getQueryVariable("bid");

      if(bid != 'not' ){
        var text_btn = $("#branch_filter_link_"+bid).text();
        $("#branch_btn").text(text_btn);
      }else{
        var text_btn = $("#branch_filter_link_0").text();
        $("#branch_btn").text(text_btn);

      }

      var sid = getQueryVariable("sid");

      if(sid != 'not' ){
        var text_btn = $("#supplier_filter_link_"+sid).text();
        $("#supplier_btn").text(text_btn);
      }else{
        var text_btn = $("#supplier_filter_link_0").text();
        $("#supplier_btn").text(text_btn);

      }
      
    }

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

    
    function get_totals(){

            $.ajax({
                  url : 'models/crul_stock_detail.php',
                  type : 'POST',
                  data : {id:query_id,
                          pid:query_pid,
                          bid:query_bid,
                          sid:query_sid,
                          type:'get_totals',
                          branch_id:BRANCH_ID,

                          },
                  dataType : 'json',
                  success : function(response) {
                    
                    $("#total_products").html( response.total_on_hand);
                    $("#total_cost").html( currency_format_display(response.total_cost));
                    $("#total_sell").html( currency_format_display(response.total_sell));

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

            }); // submit ajax

    }
   

$(document).ready(function() {


    $(".stock_class").on('change', function(){
      var stock_id_   = $(this).val();
      var product_id_ = $("#product_id").val();

      $.ajax({
                    url: "models/crul_stock_detail.php",
                    type:"POST",
                    dataType : "JSON",
                    data : {stock_id:stock_id_,
                            product_id:product_id_,
                            type:'get_on_hand'},
                    complete:function(){
                      
                    },
                    beforeSend:function(){
                      
                    },
                    success: function(res) {
                      console.log(res)
                      if(res.is_success == true){
                          $(".on_hand_qty").text(res.data[0].on_hand_quantity)
                          $("#on_hand_qty").val(res.data[0].on_hand_quantity)
                          
                      
                      }else{
                        $(this).val('');
                         swal({
                              title: Translation("خطأ"),
                              text: Translation(res.data),
                              confirmButtonColor: "#66BB6A",
                              type: "warning"
                          });
                      }
                     

                    }
                });
    });

    $('#add_form').submit(function(event) {
            event.preventDefault();
            
            var name          = $("#objname").val();
            var stock_type    = $("#stock_type").val();
            var stock_note    = $("#stock_note").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: "Please Enter the Category Name",
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'top',
                  });
            }else{
               $("#objname").closest('.form-group').removeClass('has-error');
               $("#objname").closest('.form-group').addClass('has-success');
            }

            if(stock_type =='') {
               $("#stock_type").closest('.form-group').removeClass('has-success');
               $("#stock_type").closest('.form-group').addClass('has-error');
               Check2 = false;
               noty({
                        width: 200,
                        text: "الرجاء قم بتحديد نوع المخزن",
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'top',
                  });
            }else{
               $("#stock_type").closest('.form-group').removeClass('has-error');
               $("#stock_type").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 : {name:name,stock_type:stock_type,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: res.data,
                                      type: 'success',
                                      dismissQueue: true,
                                      timeout: 3000,
                                      layout: 'topRight',
                                });
                  }else{
                      swal({
                          title: "خطأ",
                          text: res.data,
                          confirmButtonColor: "#66BB6A",
                          type: "error"
                      });
                  }
                  $("#submit_add_btn").attr('disabled',false);
                })
                .fail(function(err) {
                   swal({
                      title: "Error",
                      text: "Detail:"+err,
                      confirmButtonColor: "#66BB6A",
                      type: "error"
                    });
                   $("#submit_add_btn").attr('disabled',false);
                })
                .always(function() {
                    console.log("complete");
                });
            }

    });


    
  $('#edit_form').submit(function(event) {
            event.preventDefault();
            
            var stock_id      = $("#stock_id").val();
            var to_stock_id   = $("#to_stock_id").val();
            var catId         = $("#product_id").val();
            var moved_qty     = $("#moved_qty").val();
            var on_hand_qty   = $("#on_hand_qty").val();
           
            var Check1 = true;
            var Check2 = true;
            var Check3 = true;

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

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

            if(parseInt(moved_qty) > parseInt(on_hand_qty) ) {
              // alert( +" == "+ on_hand_qty)
               $("#moved_qty").closest('.form-group').removeClass('has-success');
               $("#moved_qty").closest('.form-group').addClass('has-error');
               Check3 = false;
               noty({
                        width: 200,
                        text: Translation("الكمية المنقولة اكبر من المتوفرة"),
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'top',
                  });
            }else{
               $("#moved_qty").closest('.form-group').removeClass('has-error');
               $("#moved_qty").closest('.form-group').addClass('has-success');
            }

            

           

            if(Check1 && Check2 && Check3){
                $("#btn_transfer").attr('disabled',true);

                $.ajax({
                    url: "models/crul_stock_detail.php",
                    type:"POST",
                    dataType : "JSON",
                    data : {stock_id:stock_id,
                            to_stock_id:to_stock_id,
                            moved_qty:moved_qty,
                            obj_id:catId,
                            type:'transfer_stock'},
                    complete:function(){
                      $("#btn_transfer").attr('disabled',false);
                      
                    },
                    beforeSend:function(){
                      $("#btn_transfer").attr('disabled',true);
                      
                    },
                    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',
                                });
                      }
                      $("#btn_transfer").attr('disabled',false);

                    }
                });
              }
    });

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

            var itemid              = $("#product_id").val();
            var on_hand_qty         = $("#on_hand_qty").val();
            
            // var itemid              = $("#id_damage").val();

            // var on_hand_qty         = $("#on_hand_qty_damage").val();

            var stock_id_damage     = $("#stock_id_damage").val();
            var damage_resons       = $("#damage_resons").val();
            var damage_qty          = $("#damage_qty").val();
           
            var Check1 = true;
            var Check2 = true;
            var Check3 = true;

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


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

            
            if(parseInt(damage_qty) > parseInt(on_hand_qty) ) {
              // alert( +" == "+ on_hand_qty)
               $("#damage_qty").closest('.form-group').removeClass('has-success');
               $("#damage_qty").closest('.form-group').addClass('has-error');
               Check3 = false;
               noty({
                        width: 200,
                        text: Translation("الكمية التالفة اكبر من المتوفرة"),
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'top',
                  });
            }else{
               $("#damage_qty").closest('.form-group').removeClass('has-error');
               $("#damage_qty").closest('.form-group').addClass('has-success');
            } 

           

            if(Check1 && Check2 && Check3){
              $("#btn_damage").attr('disabled',true);

              $.ajax({
                      url: "models/crul_stock_detail.php",
                      type:"POST",
                      dataType : "JSON",
                      data: {"type":"add_damage",
                             "obj_id":itemid,
                             damage_qty:damage_qty,
                             stock_id_damage:stock_id_damage,
                             damage_resons:damage_resons
                              } ,
                      complete:function(){
                        $("#btn_damage").attr('disabled',false);
                       
                      },
                      beforeSend:function(){
                         $("#btn_damage").attr('disabled',true);
                       
                      },
                      success: function(res) {

                        if(res.is_success == true){
                          $('#add_damage_form_cont').modal('toggle');
                          $("#add_damage_form")[0].reset();
                          noty({
                                        width: 200,
                                        text: Translation(res.data), //'Product Successfully Update',
                                        type: 'success',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'topRight',
                                      });
                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                        }else{
                          noty({
                                        width: 200,
                                        text: Translation(res.data), //'Product Successfully Update',
                                        type: 'error',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'topRight',
                                      });
                        }

                        $("#btn_damage").attr('disabled',true);

                      }
                  });

               
              }
    });

  
  $('#add_expire_form').submit(function(event) {
            event.preventDefault();
            
            var itemid              = $("#product_id").val();
            var on_hand_qty         = $("#on_hand_qty").val();
            
            // var itemid              = $("#id_expire").val();
            // var on_hand_qty         = $("#on_hand_qty_expire").val();
            
            var stock_id_expire     = $("#stock_id_expire").val();
            var expire_resons       = $("#expire_resons").val();
            var expire_qty          = $("#expire_qty").val();
           
            var Check1 = true;
            var Check2 = true;
            var Check3 = true;

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


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

            
            if(parseInt(expire_qty) > parseInt(on_hand_qty) ) {
              // alert( +" == "+ on_hand_qty)
               $("#expire_qty").closest('.form-group').removeClass('has-success');
               $("#expire_qty").closest('.form-group').addClass('has-error');
               Check3 = false;
               noty({
                        width: 200,
                        text: Translation("الكمية المنتهية صلاحيتها اكبر من المتوفرة"),
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'top',
                  });
            }else{
               $("#expire_qty").closest('.form-group').removeClass('has-error');
               $("#expire_qty").closest('.form-group').addClass('has-success');
            } 

           

            if(Check1 && Check2 && Check3){
              $("#btn_expire").attr('disabled',true);

              $.ajax({
                      url: "models/crul_stock_detail.php",
                      type:"POST",
                      dataType : "JSON",
                      data: {"type":"add_expire",
                             "obj_id":itemid,
                             expire_qty:expire_qty,
                             stock_id_expire:stock_id_expire,
                             expire_resons:expire_resons
                              } ,
                      complete:function(){
                        $("#btn_expire").attr('disabled',false);
                       
                      },
                      beforeSend:function(){
                         $("#btn_expire").attr('disabled',true);
                       
                      },
                      success: function(res) {

                        if(res.is_success == true){
                          $('#add_expire_form_cont').modal('toggle');
                          $("#add_expire_form")[0].reset();
                          noty({
                                        width: 200,
                                        text: Translation(res.data), //'Product Successfully Update',
                                        type: 'success',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'topRight',
                                      });
                          $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                        }else{
                          noty({
                                        width: 200,
                                        text: Translation(res.data), //'Product Successfully Update',
                                        type: 'error',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'topRight',
                                      });
                        }

                        $("#btn_expire").attr('disabled',true);

                      }
                  });

               
              }
    });


  $('#production_form').submit(function(event) {
            event.preventDefault();
            
            var itemid              = $("#product_id").val();

            var on_hand_qty         = $("#on_hand_qty").val();
            
            // var itemid            = $("#id_production").val();
            // var on_hand_qty       = $("#on_hand_qty_used").val();
            var stock_id_used     = $("#stock_id_used").val();
            var used_resons       = $("#used_resons").val();
            var qty               = $("#used_length").val();
           
            var Check1 = true;
            var Check2 = true;
            var Check3 = true;

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


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

            
            if(parseInt(qty) > parseInt(on_hand_qty) ) {
              // alert( +" == "+ on_hand_qty)
               $("#used_length").closest('.form-group').removeClass('has-success');
               $("#used_length").closest('.form-group').addClass('has-error');
               Check3 = false;
               noty({
                        width: 200,
                        text: Translation("الكمية المستخدمة اكبر من المتوفرة"),
                        type: 'error',
                        dismissQueue: true,
                        timeout: 3000,
                        layout: 'top',
                  });
            }else{
               $("#used_length").closest('.form-group').removeClass('has-error');
               $("#used_length").closest('.form-group').addClass('has-success');
            }

           

            if(Check1 && Check2 && Check3){
                  $("#btn_used").attr('disabled',true);
                  $.ajax({
                        url: "models/crul_stock_detail.php",
                        type:"POST",
                        dataType : "JSON",
                        data: {"type":"used_product",
                                "obj_id":itemid,
                                qty:qty,
                                stock_id_used:stock_id_used,
                                used_resons:used_resons
                                } ,
                        complete:function(){
                          $("#btn_used").attr('disabled',false);
                          
                        },
                        beforeSend:function(){
                          $("#btn_used").attr('disabled',true);
                         
                        },
                        success: function(res) {

                          if(res.is_success == true){
                            $('#production_form_cont').modal('toggle');
                            $("#production_form")[0].reset();
                            noty({
                                          width: 200,
                                          text: Translation(res.data), //'Product Successfully Update',
                                          type: 'success',
                                          dismissQueue: true,
                                          timeout: 3000,
                                          layout: 'topRight',
                                        });
                            $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                          }else{
                            noty({
                                          width: 200,
                                          text: Translation(res.data), //'Product Successfully Update',
                                          type: 'error',
                                          dismissQueue: true,
                                          timeout: 3000,
                                          layout: 'topRight',
                                        });
                          }
                          $("#btn_used").attr('disabled',false);

                        }
                    });
            
               
            }
    });
    
    

});


  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);
        if(product_id >0){
          window.location="index.php?p=stock_detail&pid="+product_id+id_+sid_;
        }else{
          window.location="index.php?p=stock_detail"+id_+sid_;
        }
    }

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




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

    function format ( d ) {
      // `d` is the original data object for the row
      var links ='';
      if(d[22] !='' && d[22] !=null){
        links   = `<button class="btn btn-success btn-raised legitRipple"><i class="icon-book"></i></button>`;
      }
      return `<table width=98% align=center  cellpadding="5" cellspacing="0" border="1" class="text-center text-wrap" style="padding-left:50px; border-color:#26a69a;">
       
                <tr class="text-black bg-teal-400">
                    <td>`+Translation('الكمية المستلمة')+`</td>
                    <td>`+Translation('الكمية المتوفرة')+`</td>
                    <td>`+Translation('الكمية المنقولة من المخزن')+`</td>
                    <td>`+Translation('الكمية المنقولة الى المخزن')+`</td>
                   
                    <td>`+Translation('الكمية المباعة')+`</td>
                    <td>`+Translation('الكمية التالفة')+`</td>
                    <td>`+Translation('المنتهية صلاحيتها')+`</td>
                    <td>`+Translation('Returned Qty')+`</td>
                    
                    <td>`+Translation('كلفة الخسائر')+`</td>
                    <td>`+Translation('Initial')+`</td>
                    
                    
                </tr>
                <tr>
                    <td>`+d[4]+`</td>
                    <td>`+d[5]+`</td>
                    <td>`+d[10]+`</td>
                    <td>`+d[9]+`</td>
                    
                    <td>`+d[6]+`</td>
                    <td>`+d[7]+`</td>
                    <td>`+d[11]+`</td>
                    <td>`+d[16]+`</td>
                    
                    <td>`+currency_format_display(+(d[15] * d[7]) + +(d[15] * d[11]))+`</td>
                    <td>`+d[12]+`</td>
                    
                    
                </tr>
                
              </table>`;
    }
    
   
   
   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_stock_detail.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(query_bid !='not'){
            d.bid =query_bid ;
          }

          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": 0,
                "className":      'details-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": '',
                "render": function(data, type, row){
                     
                        return `<i class="icon-add text-success"></i>`; 
                   
                },
            },

          {

              "targets": 10,
              "data": null,
              "render": function (data,type,row) {

                            var btns='';

                          

                  if(IS_VIEW==0){
                            

                            return  `<ul class='icons-list '>
                                      
                                        <li class='text-primary-600'>
                                            <a  class='text-success-600' onclick="transfer_stock(`+row[1]+`,`+row[5]+`,'`+row[13]+`')" data-popup='tooltip' data-original-title='`+Translation('نقل الى مخزن اخر')+`'>
                                                <i class='icon-transmission'></i>
                                            </a>
                                        </li>

                                        <li class='text-primary-600'>
                                            <a  class='text-danger-600' onclick="add_damage(`+row[1]+`,`+row[5]+`,'`+row[13]+`')" data-popup='tooltip' data-original-title='`+Translation('اضافة تالف')+`'>
                                                <i class='icon-trash-alt'></i>
                                            </a>
                                        </li>
                                        
                                        <li class='text-teal-600'>
                                            <a  class='text-purple-600' onclick="add_expired(`+row[1]+`,`+row[5]+`,'`+row[13]+`')" data-popup='tooltip' data-original-title='`+Translation('اضافة كمية منتهية الصلاحية')+`'>
                                                <i class='icon-alarm-cancel'></i>
                                            </a>
                                        </li>

                                        <!--
                                        <li class='text-primary-600'>
                                            <a href='#' class='text-primary-600' onclick="used_in_production(`+row[1]+`,`+row[5]+`,'`+row[13]+`')" data-popup='tooltip' data-original-title='`+Translation('اضافة كمية تم استخدامها في الانتاج')+`'>
                                                <i class='icon-design'></i>
                                            </a>
                                        </li>
                                        
                                        
                                        -->
                                    </ul>`;
                            }else{
                              return '';
                            }
                }
          },

          

          

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


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


             },
             "targets": 2
          },

          

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


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


             },
             "targets": 3
          },

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

                      // var on_hand = +row[5] + +row[9] - (+row[7] + +row[8]  + +row[10] + +row[11] + +row[12] + +row[13]);
                      var on_hand = data;
                      
                      if(on_hand <= 0){
                        return `<span class=" btn-block ">`+on_hand+`</span>` ;
                      }else{

                        
                          return `<span class=" btn-block ">`+on_hand+`</span>` ;

                        
                      }
                      


             },
             "targets": 4
          },


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

                      // var on_hand = +row[5] + +row[9] - (+row[7] + +row[8]  + +row[10] + +row[11] + +row[12] + +row[13]);
                      var on_hand = data;
                      
                      if(on_hand <= 0){
                        return `<label class="label btn-block label-danger">`+on_hand+`</label>` ;
                      }else{

                        
                          return `<label class="label btn-block label-success">`+on_hand+`</label>` ;

                        
                      }
                      


             },
             "targets": 5
          },


          {
             "render": function(data, type, row){
       
                if(PROFILE_TYPE != '0'){
                    var cost = row[5] * row[15];
                }else{
                    var cost = 0;
                }

                       
                return currency_format_display(cost) ;

             },
             "targets": 8
          },


          {
             "render": function(data, type, row){
       
                if(PROFILE_TYPE != '0'){
                    var cost = row[5] * row[17];
                }else{
                    var cost = 0;
                }

                       
                return currency_format_display(cost) ;

             },
             "targets": 9
          },


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


            if(   aData[4] == 0 ){
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('warning-active');
                });
            }
        },
        "order": [[5,'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>`); 
         $("#filter_btn_branch").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="branch_btn">`+Translation('الفرع')+`</span>  <span class="caret"></span></button>
                                          <ul class="dropdown-menu dropdown-menu-right" id="branch_filter">
                                          </ul>
                                          </div>`); 


         $("#filter_btn_stock").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>`); 


         $("#filter_btn_supplier").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="supplier_btn">`+Translation('الموردين')+`</span>  <span class="caret"></span></button>
                                          <ul class="dropdown-menu dropdown-menu-right" id="supplier_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 col-sm-3 " onclick="show_detail_page();">
                                                    <b><i class="icon-search4"></i></b>
                                                    `+Translation('عرض تفاصيل هذه المادة في جميع المخازن')+`
                                                  </button>

                                            </div>`); 

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

            });

            get_Stock(); 
            get_Branch(); 
            get_Supplier();
            get_totals();


        }
    });

    
    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


    //child row
    // Add event listener for opening and closing details
    $('.datatable-column-search-inputs tbody').on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        
        var row = table.row( tr );
 
        if ( row.child.isShown() ) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
            $(this).html('<i class="icon-add text-success"></i>');
        }
        else {
            // Open this row
            row.child( format(row.data()) ).show();
            tr.addClass('shown');
            $(this).html('<i class="icon-subtract text-danger"></i>');

        }
    } );

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


});



