$(document).ready(function() {
  
get_Products();
get_Invoices();         
$('#add_form').on('submit', function(e){
      //var me = $(this);
      e.preventDefault();

       //if ( me.data('requestRunning') ) {
       //    return;
       //}

      //me.data('requestRunning', true);
      var product_id             = $("#product_id").val();
      var quantity               = $("#quantity").val();
      var price                  = $("#price").val();
      var created_at             = $("#created_at").val();
      var sell_price             = $("#sell_price").val();
      var sell_price_percentage  = $("#sell_price_percentage").val();


      var acc_tok = $("#access_token").val();
      var ReqURL = 'http://www.keentech.co/projects/goran_api/public/products/'+product_id+'/purchase';

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

      Check1 = Checks('product_id');
      Check2 = Checks('quantity');
      Check3 = Checks('price');
      //Check4 = Checks('made_in');
      if(sell_price !='' && isNaN(sell_price)){
        Check5=false;
        $("#sell_price").closest('.form-group').removeClass('has-success');
        $("#sell_price").closest('.form-group').addClass('has-error');
         
         noty({
                  width: 200,
                  text: "Please Enter Numeric Value",
                  type: 'error',
                  dismissQueue: true,
                  timeout: 3000,
                  layout: 'top',
            });
      }else{
        $("#sell_price").closest('.form-group').addClass('has-success');
        $("#sell_price").closest('.form-group').removeClass('has-error');
      }

      if(sell_price_percentage !='' && isNaN(sell_price_percentage)){
        Check6=false;
        $("#sell_price_percentage").closest('.form-group').removeClass('has-success');
        $("#sell_price_percentage").closest('.form-group').addClass('has-error');
         
         noty({
                  width: 200,
                  text: "Please Enter Numeric Value",
                  type: 'error',
                  dismissQueue: true,
                  timeout: 3000,
                  layout: 'top',
            });
      }else{
        $("#sell_price_percentage").closest('.form-group').addClass('has-success');
        $("#sell_price_percentage").closest('.form-group').removeClass('has-error');
         
      }
      
      
      if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
  
            $.ajax({
                  url : ReqURL,
                  headers: {
                              'Authorization':'Bearer '+acc_tok,
                              'Accept':'application/json',
                              'Content-Type':'application/x-www-form-urlencoded'
                           },
                  type : 'POST',
                  data : {product_id:product_id,quantity:quantity,price:price,created_at:created_at,sell_price:sell_price,sell_price_percentage:sell_price_percentage},
                  dataType : 'json',
                  success : function(response) {
                        console.log(response)
                        if(response.is_success == true) {

                              noty({
                                    width: 200,
                                    text: 'Purchase Successfully Added',
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 3000,
                                    layout: 'top',
                              });
                              $("#product_id").val('');
                              $("#quantity").val('');
                              $("#price").val('');
                              $("#created_at").val('');
                              $("#sell_price").val('');
                              $("#sell_price_percentage").val('');
                              $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                        } else {

                           noty({
                                 width: 200,
                                 text: response.message,
                                 type: 'error',
                                 dismissQueue: true,
                                 timeout: 3000,
                                 layout: 'top',
                           });
                        }
                  },
                  complete: function() {
                          // me.data('requestRunning', false);
                  }

            }); // submit ajax
      }else{
            noty({
                                    width: 200,
                                    text: 'Enter Required Feilds!!',
                                    type: 'error',
                                    dismissQueue: true,
                                    timeout: 3000,
                                    layout: 'top',
                              });
      }
      
});


$('#edit_form').on('submit', function(e){
      //var me = $(this);
      e.preventDefault();

      var catId                  = $("#edit_objid").val();
      var product_id             = $("#edit_product_id").val();
      var invoice_id             = $("#edit_invoice_id").val();
      var quantity               = $("#edit_quantity").val();
      var price                  = $("#edit_price").val();
      var discount               = $("#edit_discount").val();
     // var sell_price             = $("#edit_sell_price").val();
     // var sell_price_percentage  = $("#edit_sell_price_percentage").val();


      var acc_tok = $("#access_token").val();
      var ReqURL = 'http://www.keentech.co/projects/goran_api/public/sell_items/'+catId;

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

      Check1 = Checks('edit_product_id');
      Check2 = Checks('edit_quantity');
      Check3 = Checks('edit_price');
      Check3 = Checks('edit_invoice_id');

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

  
            $.ajax({
                  url : ReqURL,
                  headers: {
                              'Authorization':'Bearer '+acc_tok,
                              'Accept':'application/json',
                              'Content-Type':'application/x-www-form-urlencoded'
                           },
                  type : 'PUT',
                  data : {product_id:product_id,quantity:quantity,price:price,discount:discount},
                  dataType : 'json',
                  success : function(response) {
                        console.log(response)
                        if(response.is_success == true) {

                              noty({
                                    width: 200,
                                    text: 'Purchase Successfully Updated',
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 3000,
                                    layout: 'top',
                              });
                              $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                        } else {

                           noty({
                                 width: 200,
                                 text: response.message,
                                 type: 'error',
                                 dismissQueue: true,
                                 timeout: 3000,
                                 layout: 'top',
                           });
                        }
                  },
                  complete: function() {
                        //   me.data('requestRunning', false);
                  }

            }); // submit ajax
      }else{
            noty({
                                    width: 200,
                                    text: 'Check Error Fields!!',
                                    type: 'error',
                                    dismissQueue: true,
                                    timeout: 3000,
                                    layout: 'top',
                              });
      }
      
});

});


function Checks(id){
   var name = $("#"+id).val();
   if(name =='') {
         $("#"+id).closest('.form-group').removeClass('has-success');
         $("#"+id).closest('.form-group').addClass('has-error');
         
         noty({
                  width: 200,
                  text: "Please Enter the Required Fields",
                  type: 'error',
                  dismissQueue: true,
                  timeout: 3000,
                  layout: 'top',
            });
         return false;
      }else{
         $("#"+id).closest('.form-group').removeClass('has-error');
         $("#"+id).closest('.form-group').addClass('has-success');
         return true;
      }

}


function get_Products(){

  $.ajax({
                  url : 'models/crul_product.php',                 
                  type : 'GET',
                  dataType : 'json',
                  success : function(response) {
                    console.log(response)
                      var attach ='<option value="" selected="selected">Product Name</option>';
                        for(var i=0 ; i < response.data.length;i++){
                          attach = attach + '<option value="'+response.data[i][0]+'">'+response.data[i][1]+'</option>';
                        }
                        $("#product_id").html(attach);
                             
                        
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

}


function get_Invoices(){

  $.ajax({
                  url : 'models/crul_invoice.php',                 
                  type : 'GET',
                  dataType : 'json',
                  success : function(response) {
                    console.log(response)
                      var attach ='<option value="" selected="selected">Invoice Number</option>';
                        for(var i=0 ; i < response.data.length;i++){
                          attach = attach + '<option value="'+response.data[i][0]+'">'+response.data[i][1]+'</option>';
                        }
                        $("#edit_invoice_id").html(attach);
                             
                        
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

}

function edit_items(itemid,prodId,invoicId,quan,pric,disc){
  $("#edit_product_id").html($("#product_id").html());
  $("#edit_objid").val(itemid);
  $("#edit_product_id").val(prodId);
  $("#edit_invoice_id").val(invoicId);
  $("#edit_quantity").val(quan);
  $("#edit_price").val(pric);
  $("#edit_discount").val(disc);
  $('#edit_form_cont').modal('toggle');
  
}




function delete_items(itemid) {
   // block = $("#list_of_items");
   // bootstrap modal confirmation box
   var acc_tok = $("#access_token").val();
   var ReqURL = 'http://www.keentech.co/projects/goran_api/public/sell_items/'+itemid;

    swal({
        title: "Are you sure?",
        text: "You will not be able to recover this record!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#EF5350",
        confirmButtonText: "Yes, delete it!",
        cancelButtonText: "No, cancel",
        closeOnConfirm: true,
        closeOnCancel: true
    },
    function(isConfirm){
        if (isConfirm) { 

               $.ajax({
                  url : ReqURL,
                  headers: {
                              'Authorization':'Bearer '+acc_tok,
                              'Accept':'application/json',
                              'Content-Type':'application/x-www-form-urlencoded'
                           },
                  type : 'DELETE',
                  data : {name:'name'},
                  dataType : 'json',
                  success : function(response) {
                        console.log(response)
                        if(response.is_success == true) {

                              noty({
                                    width: 200,
                                    text: 'Sell Item Successfully Removed',
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 3000,
                                    layout: 'top',
                              });
                              $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                        } else {

                           noty({
                                 width: 200,
                                 text: response.message,
                                 type: 'error',
                                 dismissQueue: true,
                                 timeout: 3000,
                                 layout: 'top',
                           });
                        }
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

           
        }
    }); // /confirm
}



$(function() {
//var singleSelect = $('.datatable-column-search-inputs').DataTable();
    
  $(".touchspin-basic").TouchSpin({
        min: 0,
        max: 100000,
        step: 1,
        postfix: '<i class="icon-paragraph-justify2"></i>'
    });

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


   // Setting datatable defaults
    $.extend( $.fn.dataTable.defaults, {
        autoWidth: false,
        columnDefs: [{ 
            orderable: false,
            width: '100px',
            targets: [ 9 ]
        }],
        dom: '<"datatable-header"fBl><"datatable-scroll"t><"datatable-footer"ip>',
        language: {
            search: '<span>Filter:</span> _INPUT_',
            searchPlaceholder: 'Type to filter...',
            lengthMenu: '<span>Show:</span> _MENU_',
            paginate: { 'first': 'First', 'last': 'Last', 'next': '&rarr;', 'previous': '&larr;' }
        },
        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="Search '+title+'" />');
    });
    
    

   
   var table = $('.datatable-column-search-inputs').DataTable({
         //"processing": true,
         //"serverSide": true,
        "order": [[ 0, "desc" ]],
        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 rows', '25 rows', '50 rows', '100 rows' ]
        ],
        
        ajax:({
                url : "models/crul_sell.php",
                type : 'post',
                data : {cid:CAT_ID} ,
                dataType : "json",
        }),
        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": 10,
                             "data": null,
                             "render": function (data,type,row) {
                                    //console.log(row);
                                          return  `<ul class='icons-list pull-right'>
                                                      <li class='text-primary-600'>
                                                          <a href='#' class='text-primary-400' onclick="edit_items(`+row[0]+`,'`+data[12]+`','`+data[7]+`','`+data[2]+`','`+data[3]+`','`+data[4]+`')" data-popup='tooltip' data-original-title='Edit'>
                                                              <i class='icon-pencil7'></i>
                                                          </a>
                                                      </li>
                                                      <li class='text-danger-600'>
                                                          <a href='#' class='text-danger-400' onclick="delete_items(`+row[0]+`,'`+row[1]+`')" data-popup='tooltip' data-original-title='Remove'>
                                                              <i class='icon-trash'></i>
                                                          </a>
                                                      </li>                                     
                                                  </ul>`;
                                      }
                        },
                        {
                           "render": function(data, type, row){

                                 
                                    return  data.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
                                 

                           },
                           "targets": 3
                        },
                        
                        {
                           "render": function(data, type, row){

                                 if(data <=20){
                                    return  `<span class="bg-danger-300 btn-block btn-xs">`+data+`</span>`;
                                 }else if(data <100 && data > 20){
                                    return  `<span class="bg-info-300 btn-block btn-xs">`+data+`</span>`;
                                 }else{
                                    return  `<span class="bg-success-300 btn-block btn-xs">`+data+`</span>`;
                                 }
                                 

                           },
                           "targets": 2
                        },

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

                                 
                                    return  `<a href='index.php?p=sell&cid=`+row[12]+`'  data-popup='tooltip' data-original-title='Show All Sells for this Product'>`+data+`</a>`;
                                 

                           },
                           "targets": 1
                        },

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

                                 
                                    return  `<a href='#' data-html="true"  data-popup="popover-custom" title="<i class='icon-vcard'></i> Job: `+row[11]+`" data-trigger="hover" data-content="<i class='icon-location3'></i> Address<br>`+row[10]+`">`+data+`</a>`;
                                 

                           },
                           "targets": 8
                        }
                        
                      ], 
         
         // for server side
        /* ajax: { 
                  "url" : "models/crul_category.php",
                  "data": function(d){
                     d.type = "load";
                  }
               },
         */
        initComplete: function () {
         
        /*
         $("div.datatable-header").append(`<a data-toggle="collapse"
                                      style="margin-left: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>`);  
        */

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

            });
        }
    });

    
    table.columns().every( function () {
        var that = this;
        $('input', this.footer()).on('keyup change', function () {
            that.search(this.value).draw();
        });
    });


    // Single row selection
    
    $('.datatable-column-search-inputs tbody').on('click', 'tr', function() {
        if ($(this).hasClass('success')) {
            $(this).removeClass('success');
        }
        else {
            table.$('tr.success').removeClass('success');
            $(this).addClass('success');
        }
    });


         // change filter to top
    $('.datatable-column-search-inputs tfoot tr').insertAfter($('.datatable-column-search-inputs thead tr'))


    $('.dataTables_length select').select2({
        minimumResultsForSearch: Infinity,
        width: 'auto'
    });


});



