<script src="https://cdn.datatables.net/plug-ins/1.10.21/sorting/datetime-moment.js"></script>
<script>
$("#table_filter_vehicle").select2({
  placeholder: "Select Vehicle"
})
$("#table_filter_vehicle_category").select2({
  placeholder: "Select Vehicle Category"
})
$("#table_filter_allocation_status").select2({
  placeholder: "Select Status"
})
$("#table_filter_allocated_location").select2({
  placeholder: "Select Location"
})

$("#allocation_status_add").select2({
  placeholder: "Select Status",
  dropdownParent: $("#form_vehicle_allocation_add")
})
$("#allocated_location_add").select2({
  placeholder: "Select Location",
  dropdownParent: $("#form_vehicle_allocation_add")
})
$("#allocated_driver_add").select2({
  placeholder: "Select Driver",
  dropdownParent: $("#form_vehicle_allocation_add")
})
$("#allocation_status_edit").select2({
  placeholder: "Select Status",
  dropdownParent: $("#form_vehicle_allocation_edit")
})
$("#allocated_location_edit").select2({
  placeholder: "Select Location",
  dropdownParent: $("#form_vehicle_allocation_edit")
})
$("#allocated_driver_edit").select2({
  placeholder: "Select Driver",
  dropdownParent: $("#form_vehicle_allocation_edit")
})
$('body').on('click', '#allocation_add_btn', function() {
  var no = $(this).closest('tr').children('td');
  var vehicle_id = no.eq(8).text();
  $('#vehicle_name_allocation_add').val(no.eq(2).text());
  $('#vehicle_id_allocation_add').val(vehicle_id);
  $('#date_allocation_add').val(no.eq(1).text());
})
$("#allocation_status_add").change(function() {
  var status = $('#allocation_status_add').val();
  if(status==1){
    $(".allocated_details_add_div").show();
    $("#allocated_location_add,#allocated_driver_add").attr('required',true);
  }else{
    $(".allocated_details_add_div").hide();
    $("#allocated_location_add,#allocated_driver_add").removeAttr('required',true);
  }
});
$("#allocation_status_edit").change(function() {
  var status = $('#allocation_status_edit').val();
  if(status==1){
    $(".allocated_details_edit_div").show();
    $("#allocated_location_edit,#allocated_driver_edit").attr('required',true);
  }else{
    $(".allocated_details_edit_div").hide();
    $("#allocated_location_edit,#allocated_driver_edit").removeAttr('required',true);
  }
});

function GetSearchVehicle(){
  return $('#table_filter_vehicle').val();
}
function GetSearchDate(){
  return $('#table_filter_date_vehicle_allocation').val();
}
function GetSearchVehicle(){
  return $('#table_filter_vehicle').val();
}
function GetSearchVehicleCategory(){
  return $('#table_filter_vehicle_category').val();
}
function GetSearchAllocationStatus(){
  return $('#table_filter_allocation_status').val();
}
function GetSearchAllocatedLocation(){
  return $('#table_filter_allocated_location').val();
}

$.fn.dataTable.moment('DD-MM-YYYY');
var vehicle_allocations_view_table = $('#vehicle_allocations_view_table').DataTable({
  "ajax":{
    url :"<?php echo base_url().'vehicles/select_vehicle_allocations' ?>", // json datasource
    type: "post", // type of method  , by default would be get
    data: function(d){
      <?php if($page_name=='vehicle_profile') { ?>
        d.vehicle_id = <?= $vehicle_data->id ?>;
        <?php } else { ?>
          d.vehicle_id = GetSearchVehicle();
          <?php } ?>
          d.date = GetSearchDate();
          d.location_id = GetSearchAllocatedLocation();
          d.allocation_type = GetSearchAllocationStatus();
          d.vehicle_category = GetSearchVehicleCategory();
          <?php if($page_name=='user_profile') { ?>
            d.user_id = <?= $user_data->user_id ?>;
            <?php } ?>
          }
        },
        "bProcessing": true,
        "deferRender": true,
        "bDeferRender": true,
        "scrollX" : true,
        buttons: [
          { extend: 'print', className: 'btn dark btn-outline',exportOptions: {columns: ':visible'},title: 'Vehicle Allocations' },
          { extend: 'csv', className: 'btn purple btn-outline ' },
          { extend: 'colvis', className: 'btn dark btn-outline', text: 'Columns'}
        ],
        dom:"<'row'<'col-sm-6 text-left'B><'col-sm-6 text-right'f>>\n\t\t\t<'row'<'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>", // horizobtal scrollable datatable
        "lengthMenu": [
          [25, 50, 100, -1],
          [25, 50, 100, "All"] // change per page values here
        ],
        // set the initial value
        "pageLength": 25,
        "columnDefs": [
          {
            "targets": [ 0,8,9,10,11,12,<?php if($page_name=='vehicle_profile'){ echo "2"; }?>],
            className: "hidden"
          }
        ],
        'order': [[1, 'desc']]
      });

      $(".table_filter").on("change", function() {
        vehicle_allocations_view_table.ajax.reload();
      });
      $(".hide_column").hide();


      // Date Range Picker
      var start = moment();
      var end = moment();

      function cb(start, end) {
        $('#table_filter_date_vehicle_allocation').val(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
        vehicle_allocations_view_table.ajax.reload();
      }

      $('#table_filter_date_vehicle_allocation').daterangepicker({
        buttonClasses: "m-btn btn",
        applyClass: "btn-primary",
        cancelClass: "btn-secondary",
        startDate: start,
        endDate: end,
        locale: {
          format: 'MMMM D, YYYY'
        },
        ranges: {
          'Today': [moment(), moment()],
          'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
          'Last 7 Days': [moment().subtract(6, 'days'), moment()],
          'Last 30 Days': [moment().subtract(29, 'days'), moment()],
          'This Month': [moment().startOf('month'), moment().endOf('month')],
          'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
          'All time': [moment('1970-01-01'), moment().add(9999, 'days')],
        }
      }, cb);

      cb(start, end);

      <?php if($page_name!='vehicle_profile') { ?>
        $(".form_submit_btn").click(function (e) {
          e.preventDefault();
          var a = $(this),
          l = $(this).closest("form"),
          action = l.attr('action');
          var form_id = l.attr('id');
          l.validate({
            rules: {
              worked_duration: {
                number: !0,
                min: 1
              },
              basic_charge: {
                number: !0,
                min:0
              }
            }, invalidHandler: function (e, r) {
              var i = $("#" + form_id + "_msg");
              i.removeClass("m--hide").show(), mUtil.scrollTo(i, -200)
            }, submitHandler: function (e) {
            }
          }), l.valid() && (a.addClass("m-loader m-loader--right m-loader--light").attr("disabled", !0),
          l.ajaxSubmit({
            url: action,
            success: function (e, t, r, s) {
              var modal_id = l.attr('data-modal-id');
              var form_type = l.attr('data-form-type');
              $("#" + form_id + "_msg").addClass("m--hide");
              // Block UI
              mApp.blockPage({
                overlayColor: "#000000",
                type: "loader",
                state: "success",
                message: "Please wait..."
              }), setTimeout(function () {
                mApp.unblockPage()
              }, 2e3);
              var obj = $.parseJSON(e);
              if (obj.status == 1) {
                a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                $("#"+modal_id).modal('toggle');
                $("."+form_id+"_fields").val('');
                $("."+form_id+"_fields_1").val(0);
                $("."+form_id+"_fields_2").val(1);
                $("."+form_id+"_select").val('').trigger("change");
                toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
                vehicle_allocations_view_table.ajax.reload();
              } else {
                a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
              }
              if (obj == null) {
                setTimeout(function () {
                  a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                  toastr["warning"]("Your Attempt is Timed Out. Please Try Again.", "Timed Out");
                }, 2e4)
              }
            },error: function() {
              a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
              toastr["error"]("Sorry. There Has Been Some Error Occurred. Please Try Again.", "Error");
            }
          })
        )
      });

      <?php } ?>

      </script>


      <script type="text/javascript">

      </script>


      <script type="text/javascript">
      $('body').on('click', '#vehicle_allocation_edit_btn', function() {
        var no = $(this).closest('tr').children('td');
        $('#vehicle_name_allocation_edit').val(no.eq(2).text());
        $('#date_allocation_edit').val(no.eq(1).text());
        var allocation_status = no.eq(9).text();
        $('#allocation_status_edit').val(allocation_status).trigger('change');
        if(allocation_status==1){
          $(".allocated_details_edit_div").show();
          $("#allocated_location_edit,#allocated_driver_edit").attr('required',true);
          $('#allocated_location_edit').val(no.eq(10).text()).trigger('change');
          $('#allocated_driver_edit').val(no.eq(11).text()).trigger('change');
        }else{
          $(".allocated_details_edit_div").hide();
          $("#allocated_location_edit,#allocated_driver_edit").removeAttr('required',true);
        }
        $('#allocation_remarks').val(no.eq(6).text());
        $('#allocation_id_edit').val(no.eq(12).text());
      })
      $('body').on('click', '#vehicle_allocation_delete_btn', function() {
        var no = $(this).closest('tr').children('td');
        $('#allocation_id_delete').val(no.eq(12).text());
      })

      </script>
