<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_allocation_status").select2({
  placeholder: "Select Status"
})
$("#table_filter_allocated_location").select2({
  placeholder: "Select Location"
})

$("#vehicle_doc_type_add").select2({
  placeholder: "Select Type",
  dropdownParent: $("#form_vehicle_document_add")
})
$("#vehicle_doc_type_edit").select2({
  placeholder: "Select Type",
  dropdownParent: $("#form_vehicle_document_edit")
})

function GetSearchVehicle(){
  return $('#table_filter_vehicle').val();
}
function GetSearchDocType(){
  return $('#table_filter_document_type').val();
}

$.fn.dataTable.moment('DD-MM-YYYY');
var vehicle_documents_view_table = $('#vehicle_documents_view_table').DataTable({
  "ajax":{
    url :"<?php echo base_url().'vehicles/select_vehicle_documents' ?>", // 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.file_type = GetSearchDocType();
          <?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 Documents' },
          { 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": [ 7,8,9,10<?php if($page_name=='vehicle_profile'){ echo ",1"; }?>],
            className: "hidden"
          },
          {
            render: function (data, type, full, meta) {
              return "<div class='text-wrap width-500'>" + data + "</div>";
            },
            targets: 3
          }
        ],
        'order': [[1, 'desc']]
      });

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


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

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

      $('#table_filter_date').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_documents_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_document_edit_btn', function() {
        var no = $(this).closest('tr').children('td');
        $('#document_id_edit').val(no.eq(10).text());
        $('#vehicle_doc_type_edit').val(no.eq(2).text()).trigger('change');
        $('#document_file_edit').val(no.eq(9).text());
        $('#document_remarks_edit').val(no.eq(4).text());
      })
      $('body').on('click', '#vehicle_document_delete_btn', function() {
        var no = $(this).closest('tr').children('td');
        $('#document_id_delete').val(no.eq(10).text());
      })

      </script>
