@extends('layouts.app')

@section('title', 'Vehicle Register')


@section('css')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">

@endsection

@section('pages')

<style type="text/css">
    .breadcrumb-title {
        border-right: none;
    }

    tr td {
        vertical-align: middle !important; 
    }

.intl-tel-input .country-list {
    z-index: 8;
}

.intl-tel-input {
    width: 100%;
}

.autocomplete{
    position: relative;
}
.ui-autocomplete {
     z-index: 5000;
}
.autocomplete .searchResult{
    list-style: none;
    padding: 0px;
    width: 78%;
    position: absolute;
    margin: 0;
    margin-top: 40px;
    background: white;
    z-index: 5000;
}

.autocomplete .searchResult li{
    background: #F2F3F4;
    padding: 10px;
    margin-bottom: 1px;
    white-space: break-spaces;
}

.autocomplete .searchResult li:nth-child(even){
    background: #E5E7E9;
    color: black;
}

.autocomplete .searchResult li:hover{
    cursor: pointer;
    background: #CACFD2;
}



</style>



 <!--breadcrumb-->
  <div class="page-breadcrumb row align-items-center justify-content-between mb-3 px-3 px-md-0">
    <div class="breadcrumb-title col-md-6"> Vehicle Register
    </div>
    <div class="col-md-6">
      <nav aria-label="breadcrumb">
        <ol class="breadcrumb justify-content-md-end mb-0">
          <li class="breadcrumb-item"><i class="bi bi-info-circle-fill text-info show-help-support" data-id="28" data-bs-toggle="modal" data-bs-target="#commonModal"></i></li>
          <li class="breadcrumb-item" aria-current="page">Vehicle Register</li>
        </ol>
      </nav>
    </div>
  </div>
  <!--end breadcrumb-->

  <div class="card style_table shadow-none radius-5 min-height">
    <div class="card-header py-3">
      @include('layouts.partials.nav-menu')
      <div class="row gx-2">
        <div class="col-lg-3 col-md-3 col-8">
            <div class="position-relative">
                <div class="position-absolute top-50 translate-middle-y search-icon px-3"><i class="bi bi-search"></i></div>
                <input class="form-control ps-5" type="search" id="search" placeholder="Search" autofocus>
            </div>
        </div>
        <div class="col-lg-9 col-md-9">
          <div class="ms-auto float-md-end">
            <div class="btn-group">
             <button class="btn btn-primary" id="create_vehicle" type="button" data-bs-toggle="modal" data-bs-target="#commonModal">+ Add New Vehicle</button>
            </div>

            <div class="btn-group">
              <a href="#" class="btn btn-secondary"> Vehicle Statement </a>
            </div>
          </div>
          </div>
        </div>
      </div>
    </div>

    <div class="card-body bg-white" id="tables">

      @include('vehicles.table')


      <input type="hidden" name="hidden_page" id="hidden_page" value="1" />
      <input type="hidden" name="hidden_column_name" id="hidden_column_name" value="name" />
      <input type="hidden" name="hidden_sort_type" id="hidden_sort_type" value="asc" />
    </div>

@endsection

@section('js')
<script>

     /***************** Global Delay Fucntion ***************/
     function delay(callback, ms) {
        var timer = 0;
        return function() {
            var context = this,
                args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function() {
                callback.apply(context, args);
            }, ms || 0);
        };
    }

    function clear_icon(){
      $('#id_icon').html('');
      $('#post_title_icon').html('');
    }
    function fetch_data(page, sort_type, sort_by, query, account_type, accounting_groups){
      var search_type = $('[name="search_type"]').val();

      $.ajax({
        url:"?page="+page+"&sortby="+sort_by+"&sorttype="+sort_type+"&query="+query+"&accounting_groups="+accounting_groups+"&account_type="+account_type+"&search_type="+search_type,
        success:function(data){
          $('#tables').html('');
          $('#tables').html(data);
          $(document).ready(function(){$.switcher();});
        }
      })
    }

   /******** searching ********/
   $(document).on('keyup', '#search', delay(function() {
        var query = $('#search').val();

        if (query.length < 2 && query.length != 0) {
            return;
        }

        var column_name = $('.sorting').val();
        var sort_type   = $('#hidden_sort_type').val();
        var page        = 1 ? 1 : (this).attr('href').split('page=')[1];
        var account_type      = $('#account_type').val();
        var accounting_groups = $('#accounting_groups').val();


        fetch_data(page, sort_type, column_name, query,account_type,accounting_groups);
    }, 700));

    $('body').on('change', '.sorting', function(){

      var column_name = $(this).val();
      console.log('perpage',column_name);
      var order_type = $(this).data('sorting_type');
      var reverse_order = '';
      var page = 1?1:(this).attr('href').split('page=')[1];
      var query = $('#search').val()?$('#search').val():'';
      var account_type      = $('#account_type').val();
      var accounting_groups = $('#accounting_groups').val();
      fetch_data(page, reverse_order, column_name, query,account_type,accounting_groups);
    });

    $('body').on('change', '.accounting_groups', function(){

      var column_name = $('.sorting').val();
      console.log('perpage',column_name);
      var order_type = $(this).data('sorting_type');
      var reverse_order = '';
      var page = 1?1:(this).attr('href').split('page=')[1];
      var query = $('#search').val()?$('#search').val():'';
      var account_type      = $('#account_type').val();
      var accounting_groups = $('#accounting_groups').val();
      fetch_data(page, reverse_order, column_name, query,account_type,accounting_groups);
    });

    $('body').on('change', '.account_type', function(){

      var column_name = $('.sorting').val();
      console.log('perpage',column_name);
      var order_type = $(this).data('sorting_type');
      var reverse_order = '';
      var page = 1?1:(this).attr('href').split('page=')[1];
      var query = $('#search').val()?$('#search').val():'';
      var account_type      = $('#account_type').val();
      var accounting_groups = $('#accounting_groups').val();
      fetch_data(page, reverse_order, column_name, query,account_type,accounting_groups);
    });

    $('body').on('click', '.pager a', function(event){
      event.preventDefault();
      console.log('url', $(this).attr('href'));
      var page = $(this).attr('href').split('page=')[1];
      $('#hidden_page').val(page);
      var column_name       = $('.sorting').val()?$('.sorting').val():'';
      var sort_type         = $('#hidden_sort_type').val();
      var query             = $('#search').val()?$('#search').val():'';
      var account_type      = $('#account_type').val();
      var accounting_groups = $('#accounting_groups').val();
      $('li').removeClass('active');
      $(this).parent().addClass('active');
      fetch_data(page, sort_type, column_name, query,account_type,accounting_groups);
    });

   
    /*********delete data**********/
  $("body").on("click", '.deleteDataCustom', function(event) {
      var UrlValue = $(this).data('url');

      Swal.fire({
          title: 'Are you sure you want to delete this?',
          icon: 'warning',
          showDenyButton: true,
          showCancelButton: false,
          confirmButtonText: 'Yes',
          denyButtonText: 'No',
      }).then((result) => {
          if (result.isConfirmed) {
              $.ajax({
                  url: UrlValue,
                  method: 'delete',
                  data: {
                      "_token": $('meta[name="csrf-token"]').attr('content'),
                      "id": $(this).data('id')
                  },
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                  },
                  success: function(response) {
                      if (response.success) {
                     
                          $(this).Toastshow('success', response.message);

                          // Refreshing data after deletion
                          var page = $('.pager').find('.active a').attr('href') == undefined ? 1 : $('.pager').find('.active a').attr('href').split('page=')[1];
                          var column_name = $('.sorting').val() ? $('.sorting').val() : '';
                          var sort_type = $('#hidden_sort_type').val();
                          var query = $('#search').val() ? $('#search').val() : '';

                          fetch_data(page, sort_type, column_name, query);
                      } else {
                          // Handle failure case
                          var ErroMsg = $(this).printErrorMsg(response.message);
                          $(this).Toastshow('error', ErroMsg);
                      }
                  },
                  error: function(data) {
                      console.log("error ", data);
                  }
              });
          }
      });
  });

  /*********change status**********/
  $("body").on("click",'.changeStatusCustom', function(event){
        dataString       = {"id":$(this).data('id'),"status":$(this).data('status')};
        var UrlValue     = $(this).data('url');
        var status       = $(this).data('status');
        var changeStatus = $(this);
        var btn = $(this);

        Swal.fire({
            title: 'Are you sure you want to change status?',
            icon: 'warning',
            showDenyButton: true,
            showCancelButton: false,
            confirmButtonText: 'Yes',
            denyButtonText: 'No',
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url     : UrlValue,
                    method  : 'post',
                    data    :dataString,
                    headers:
                    {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    beforeSend: function( xhr ) {
                        // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                    },
                    success : function(response){
                        if(response.success){
                            var ErroMsg = $(this).printErrorMsg(response.message);
                            $(this).Toastshow('success',ErroMsg);

                            var page        = $('.pager').find('.active a').attr('href') == undefined ? 1 : $('.pager').find('.active a').attr('href').split('page=')[1];
                            var column_name = $('.sorting').val()?$('.sorting').val():'';
                            var sort_type   = $('#hidden_sort_type').val();
                            var query       = $('#search').val()?$('#search').val():'';

                            fetch_data(page, sort_type, column_name, query);
                        } else {
                            var ErroMsg = $(this).printErrorMsg(response.message);
                            if (ErroMsg === '') {
                                ErroMsg = "Something went wrong!";
                            }
                            $(this).Toastshow('error',ErroMsg);

                            if (status == 1) {
                                changeStatus.parent().find('.ui-switcher').attr('aria-checked', false);
                            } else {
                                changeStatus.parent().find('.ui-switcher').attr('aria-checked', true);
                            }
                        }
                    },
                    error: function (data) {
                        console.log("error ",data);

                        if (status == 1) {
                            changeStatus.parent().find('.ui-switcher').attr('aria-checked', false);
                        } else {
                            changeStatus.parent().find('.ui-switcher').attr('aria-checked', true);
                        }
                    }
                });
            }
            else if (result.isDenied) {
              var page        = $('.pager').find('.active a').attr('href') == undefined ? 1 : $('.pager').find('.active a').attr('href').split('page=')[1];
              var column_name = $('.sorting').val()?$('.sorting').val():'';
              var sort_type   = $('#hidden_sort_type').val();
              var query       = $('#search').val()?$('#search').val():'';

              fetch_data(page, sort_type, column_name, query);
            }
            //return false;
        });
    //return false;
  });


   // Create Vehicle Modal
$(document).on('click', '#create_vehicle', function() {
    $('#commonModalLabel').text('New Vehicle Registration');
    $('.save_button_span').text('Save Vehicle');
    $.ajax({
        url: "{{ route('vehicle-account-create') }}",
        success: function(data) {
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
        }
    });
});


    //Create Vehicle
    $(document).on('click','.save_button', function(e) {
        e.preventDefault();

        var error = 0;

        if ($('#commonModal').find('form').hasClass('create_vehicle')) {
            if (error == 0) {
                let formdata = new FormData($('#create_vehicle_form')[0]);
                $.ajax({
                    url: $('#create_vehicle_form').attr('action'),
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="vehicle_id"]').val(response.data.id);
                            $('#vehicle_id').val(response.data.name);

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');


                            var page        = $('.pager').find('.active a').attr('href') == undefined ? 1 : $('.pager').find('.active a').attr('href').split('page=')[1];
                            var column_name = $('.sorting').val()?$('.sorting').val():'';
                            var sort_type   = $('#hidden_sort_type').val();
                            var query       = $('#search').val()?$('#search').val():'';

                      fetch_data(page, sort_type, column_name, query);
                    }   
                    else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
            }
        }


//Vehicle Update
        if ($('#commonModal').find('form').hasClass('edit_vehicle')) {
            if (error == 0) {
                $.ajax({
                    url: $('#edit_vehicle_form').attr('action'),
                    data: $('#edit_vehicle_form').serialize(),
                    // processData: false,
                    // contentType: false,
                    type: 'PUT',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            $('[name="vehicle_id"]').val(response.data.id);
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            // Refreshing data after deletion
                            var page = $('.pager').find('.active a').attr('href') == undefined ? 1 : $('.pager').find('.active a').attr('href').split('page=')[1];
                            var column_name = $('.sorting').val() ? $('.sorting').val() : '';
                            var sort_type = $('#hidden_sort_type').val();
                            var query = $('#search').val() ? $('#search').val() : '';

                            fetch_data(page, sort_type, column_name, query);
                        } else {
                          // Handle failure case
                          var ErroMsg = $(this).printErrorMsg(response.message);
                          $(this).Toastshow('error', ErroMsg);
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
            }
        }


        if ($('#commonModal').find('form').hasClass('create_driver')) {

            $('.error_name').hide();
            $('.error_email').hide();
            $('.error_phone').hide();
            $('.error_country_id').hide();
            var error = 0;
            if ($('#phone_no').val().trim() != '') {
                var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            }
            $('#year').trigger("change")
            
            if ($('#whatsapp_no').val().trim() != '') {
                var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="whatsapp_no"]').val("+" + dailcode_array[1] + $('#whatsapp_no').val());
            }

            if ($('input[name="name"]').val().trim() == '') {
              $('.error_name').show();
              error = 1;
              setTimeout(function () {
                $('.error_name').hide();
                }, 3000);
            }
            if ($('[name="country_id"]').val().trim() == '') {
              $('.error_country_id').show();
              error = 1;
            }
            if ($('input[name="phone_no"]').val().trim() == '') {
              $('.error_phone').show();
              error = 1;
              setTimeout(function () {
                    $('.error_name').hide();
                }, 3000);
            }
            

            if (error == 0) {
                let formdata = new FormData($('#create_driver_form')[0]);

                $.ajax({
                    url: $('#create_driver_form').attr('action'),
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="driver_ac_id"]').val(response.data.id);
                            $('#driver_ac_id').val(response.data.name);
                            $('#edit_driver').prop('disabled', false);
                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
            }
        }
        else if ($('#commonModal').find('form').hasClass('update_driver')) {
            console.log('as');
            if ($('#phone_no').val().trim() != '') {
                var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            }
            
            if ($('#whatsapp_no').val().trim() != '') {
                var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="whatsapp_no"]').val("+" + dailcode_array[1] + $('#whatsapp_no').val());
            }

            $('.error_name').hide();
            $('.error_email').hide();
            $('.error_phone').hide();
            $('.error_country_id').hide();
            var error = 0;

            if ($('input[name="name"]').val().trim() == '' || $('[name="account_title_id"]').val() == '') {
              $('.error_name').show();
              error = 1;
              setTimeout(function () {
                $('.error_name').hide();
                }, 3000);

            }

            if ($('[name="country_id"]').val().trim() == '') {
              $('.error_country_id').show();
              error = 1;
              setTimeout(function () {
                $('.error_country_id').hide();
                }, 3000);

            }

            if ($('input[name="phone_no"]').val().trim() == '') {
              $('.error_phone').show();
              error = 1;
              setTimeout(function () {
                $('.error_phone').hide();
                }, 3000);

            }

            if (error == 0) {
                let formdata = new FormData($('#update_driver_form')[0]);

                $.ajax({
                    url: $('#update_driver_form').attr('action'),
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="driver_ac_id"]').val(response.data.id);
                            $('#driver_name').val(response.data.name);

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
            }



        }
        else if ($('#commonModal').find('form').hasClass('create_vendor')) {
            if ($('#phone_no').val().trim() != '') {
                var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            }

            $('.error_name').hide();
            $('.error_email').hide();
            $('.error_country_id').hide();
            var error = 0;

            if ($('input[name="name"]').val().trim() == '') {
              $('.error_name').show();
              error = 1;
            }
            if ($('[name="country_id"]').val().trim() == '') {
              $('.error_country_id').show();
              error = 1;
            }

            if (error == 0) {
                let formdata = new FormData($('#create_vendor_form')[0]);

                $.ajax({
                    url: $('#create_vendor_form').attr('action'),
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="vendor_ac_id"]').val(response.data.id);
                            $('#vendor_ac_id').val(response.data.name);
                            $('#edit_vendor').prop('disabled', false);
                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
            }
        }
        else if ($('#commonModal').find('form').hasClass('create_cities')) {
            console.log('tset');
            event.preventDefault();
            $('.error_name').hide();
            var error = 0;
            setTimeout(function() {
                $('.error_name').hide();
            }, 3000);


            if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
                $('.error_name').show();
                error = 1;
            }

            if (error == 0) {
                let formdata = new FormData($('#commonModal').find('form')[0]);

                $.ajax({
                    url: $('#commonModal').find('form').attr('action'),
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function(response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // hide modal
                            $('#commonModal').removeClass('create_cities');
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            setTimeout(function() {
                                $('#create_driver').trigger('click');
                                CitySelected(response.data.id);
                            }, 1000);

                    } else {
                        toastr.error(response.message, 'Error!');
                    }
                }
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                console.log('AJAX request failed:', textStatus, errorThrown);
                toastr.error('An error occurred during the request.', 'Error!');

                // hide modal
                $('#commonModal').modal('hide');
                $('#commonModal').find('.modal-body').html('');
            });
            }
            error = 1;
        }
        else if ($('#commonModal').find('form').hasClass('update_vendor_details')) {
            console.log('as');
            if ($('#phone_no').val() != '') {
                var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            }

            $('.error_name').hide();
            var error = 0;

            if ($('input[name="name"]').val() == '' || $('[name="account_title_id"]').val() == '') {
              $('.error_name').show();
              error = 1;
              setTimeout(function () {
                $('.error_name').hide();
                }, 3000);

            }



            if (error == 0) {
                let formdata = new FormData($('#update_vendor_form')[0]);

                $.ajax({
                    url: $('#update_vendor_form').attr('action'),
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            // append new category to selection
                            $('[name="vendor_ac_id"]').val(response.data.id);
                            $('#vendor_ac_id').val(response.data.name);

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
            }
        }
        else {
            $('.error_driver_ac_id').hide();
            $('.error_vendor_ac_id').hide();
            $('.error_admission_date').hide();
            $('.error_ipd_file_no').hide();

            var error = 0;

            if ($('input[name="driver_ac_id"]').val().trim() == '') {
              $('.error_driver_ac_id').show();
              error = 1;
              setTimeout(function () {
                $('.error_driver_ac_id').hide();
                }, 3000);

            }
            if ($('input[name="vendor_ac_id"]').val() == '') {
              $('.error_vendor_ac_id').show();
              error = 1;
              setTimeout(function () {
                $('.error_vendor_ac_id').hide();
                }, 3000);

            }
           
           
        }

        error = 1;
    })


    $(document).on('click', '#bodyVitals', function(){
        if ($('#bodyVitals').hasClass('hiddenVitals')) {
            $('.body_vitals_details').show();
            $('#bodyVitals').html('<i class="bx bx-minus"></i> Hide Vitals');
            $('#bodyVitals').removeClass('hiddenVitals');
        } else {
            $('.body_vitals_details').hide();
            $('#bodyVitals').html('<i class="bx bx-plus"></i> Add Vitals');
            $('#bodyVitals').addClass('hiddenVitals');
        }
    });

    function allNumeric(inputtxt) {
        onlyNumbers = inputtxt.replace(/[^0-9]/g, '');
        if (onlyNumbers.length > 16) {
            onlyNumbers = onlyNumbers.substring(0, 16);
        }
        return onlyNumbers;
    }

    $("#ipd_file_no").on('input', function() {
        const onlyNumbers = allNumeric($(this).val());
        $("#ipd_file_no").val(onlyNumbers);
    });

    function reinitializeTelInput(countryCode) {
        var telInput = $('#commonModal').find('#phone_no , #whatsapp_no , #alternative_no');
        telInput.intlTelInput('destroy'); // Destroy the existing instances

        telInput.intlTelInput({
            utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@18.2.1/build/js/utils.js",
            initialCountry: countryCode || '{!! $countryCode ?? '' !!}',
            separateDialCode: true
        });
    }

    const driverSelect = document.querySelector(".driver-select");
    const vendorSelect  = document.querySelector(".vendor-select");
    const querySelector = document.querySelector(".searchResult");

    document.addEventListener("click", (event) => {
        if (event.target !== driverSelect && event.target !== vendorSelect && event.target !== querySelector) {
            $(".searchResult").empty();
        }
    });

    //Create Driver
    $(document).on('click', '#create_driver', function(){
        $('#commonModalLabel').text('Add New Driver');
        $('.save_button_span').text('Save Driver');
        $.ajax({
          url:"{!! route('driver-account-create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            reinitializeTelInput();
          }
        })
    })
    
    //Create Vendor
    $(document).on('click', '#create_vendor', function(){
        $('#commonModalLabel').text('Add New vendor');
        $('.save_button_span').text('Save vendor');
        $.ajax({
          url:"{!! route('vendor-account-create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            reinitializeTelInput();
          }
        })
    })
    
    //Edit Driver
    $(document).on('click', '#edit_driver', function() {

        var driverName = $('#driver_ac_id').val().trim();
        if (driverName === "") {
            $('.error_driver_ac_id').show();
        } else {
            $('.error_driver_ac_id').hide();

            $('#commonModalLabel').text('Edit Driver');
            $('.save_button_span').text('Update Driver');
            var id = $('[name="driver_ac_id"]').val();
            var url = `{!! route('driver-account-edit', ':id') !!}`.replace(':id', id);

            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            });
        }
    });

    //Edit Vendor
     $(document).on('click', '#edit_vendor', function() {
        var customerName = $('[name="vendor_ac_id"]').val();

        if (customerName.trim() === "") {
            $('.error_vendor_ac_id').show();
        } else {
            $('.error_vendor_ac_id').hide();

            $('#commonModalLabel').text('Edit Vendor');
            $('.save_button_span').text('Update Vendor');
            var id = $('[name="vendor_ac_id"]').val();

            var url = `{!! route('vendor-account-edit', ':id') !!}`.replace(':id', id);

            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            });
        }
    });

    /******* Disabling & Enabling edit button of driver ************/
    $(document).ready(function() {
        function toggleEditButton() {
            var driverId = $('[name="driver_ac_id"]').val();
            $('#edit_driver').prop('disabled', driverId === "");
        }

        toggleEditButton();

        $('#driver_name').on('input', function() {
            toggleEditButton();
        });

        $('#driver_name').on('change', function() {
            toggleEditButton();
        });


        function enableEditButton() {
            $('#edit_driver').prop('disabled', false);
        }

        function addValueTodriverId(newValue) {
            $('[name="driver_name"]').val(newValue);
            enableEditButton();
        }
    });

    /******* Disabling & Enabling edit button of vendor ************/
    $(document).ready(function() {
        function toggleEditButton() {
            var vendorId = $('[name="vendor_ac_id"]').val();
            $('#edit_vendor').prop('disabled', vendorId === "");
        }

        toggleEditButton();

        $('#vendor_ac_id').on('input', function() {
            toggleEditButton();
        });

        $('#vendor_ac_id').on('change', function() {
            toggleEditButton();
        });

        $('#edit_vendor').on('click', function() {
            var vendorName = $('#vendor_ac_id').val().trim();

            if (vendorName === "") {
                $('.error_vendor_ac_id').show();
            } else {
                $('.error_vendor_ac_id').hide();

                $('#commonModalLabel').text('Edit Vendor');
                $('.save_button_span').text('Update Vendor');
                var id = $('[name="vendor_ac_id"]').val();
                var url = `{!! route('vendor-account-edit', ':id') !!}`.replace(':id', id);

                $.ajax({
                    url: url,
                    success: function(data) {
                        $('#commonModal').find('.modal-body').html('');
                        $('#commonModal').find('.modal-body').html(data);
                    }
                });
            }
        });

        function enableEditButton() {
            $('#edit_vendor').prop('disabled', false);
        }

        function addValueTovendorId(newValue) {
            $('[name="vendor_ac_id"]').val(newValue);
            enableEditButton();
        }
    }); 

    function CitySelected(id) {
        if ($('[name="city_id"]').length > 0) {
            $('[name="city_id"]').val(id);
        } else {
            setTimeout(function() {
                CitySelected(id);
            }, 1000);
        }
    }

     /**************** Create City ********************/
     $(document).on('click', '#create_city', function() {
        $('#commonModalLabel').text('Add New City');
        $('.save_button_span').text('Save City');
        $.ajax({
            url: "{!! route('cities.create') !!}",
            success: function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
            }
        })
    })

   

//Edit Vehicle Modal 
$(document).on('click', '.edit_vehicle', function() {
    var id = $(this).data('id');
     $('#commonModalLabel').text('Edit vehicle');
        $('.save_button_span').text('Update vehicle');
        var url = `{!! route('vehicle-register.edit', ':id') !!}`.replace(':id', id);

        $.ajax({
            url: url,
            success: function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
            }
        });
});


// Edit Vehicle
$(document).on('click', '#edit_vehicle', function(e) {
    e.preventDefault();

    var error = 0;

    // Check if the form has the 'edit_vehicle' class
    if ($('#commonModal').find('form').hasClass('edit_vehicle')) {
        if (error == 0) {
            let formdata = new FormData($('#edit_vehicle_form')[0]);
            $.ajax({
                url: $('#edit_vehicle_form').attr('action'),
                data: formdata,
                processData: false,
                contentType: false,
                type: 'PUT',
                success: function(response) {
                    if (response.success === true) {
                        toastr.success(response.message, 'Success.');
                        // Append new category to selection
                        $('[name="vehicle_id"]').val(response.data.id);
                        $('#vehicle_id').val(response.data.name);

                        // Hide modal
                        $('#commonModal').modal('hide');
                        $('#commonModal').find('.modal-body').html('');
                    } else {
                        toastr.error(response.message, 'Error!');
                    }
                }
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                console.log('AJAX request failed:', textStatus, errorThrown);
                toastr.error('An error occurred during the request.', 'Error!');
            });
        }
    }
});






</script>
@endsection









