@extends('layouts.app')

@section('title', 'Vehicle Document Validity')


@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 Document Validity | {{ $vehicle_register->vehicle_no }} 
    </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 Document Validity</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">
                  <a href="{{route('vehicle-register.index')}}" class="btn btn-outline-secondary me-1"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
              </div> 
            

          </div>
          </div>
        </div>
      </div>
    </div>

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

      @include('vehicle-document-validity.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 Function ***************/
    function delay(callback, ms) {
        var timer = 0;
        return function() {
            var context = this;
            var args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function() {
                callback.apply(context, args);
            }, ms || 0);
        };
    }

    function clearIcon() {
        $('#id_icon').html('');
        $('#post_title_icon').html('');
    }

    function fetchData(page, sortType, sortBy, query, accountType, accountingGroups) {
        var searchType = $('[name="search_type"]').val();

        $.ajax({
            url: "?page=" + page +
                "&sortby=" + sortBy +
                "&sorttype=" + sortType +
                "&query=" + query +
                "&accounting_groups=" + accountingGroups +
                "&account_type=" + accountType +
                "&search_type=" + searchType,
            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 columnName = $('.sorting').val();
        var sortType = $('#hidden_sort_type').val();
        var page = 1 ? 1 : $(this).attr('href').split('page=')[1];
        var accountType = $('#account_type').val();
        var accountingGroups = $('#accounting_groups').val();

        fetchData(page, sortType, columnName, query, accountType, accountingGroups);
    }, 700));

    $('body').on('change', '.sorting', function() {
        var columnName = $(this).val();
        var orderType = $(this).data('sorting_type');
        var reverseOrder = '';
        var page = 1 ? 1 : $(this).attr('href').split('page=')[1];
        var query = $('#search').val() || '';
        var accountType = $('#account_type').val();
        var accountingGroups = $('#accounting_groups').val();

        fetchData(page, reverseOrder, columnName, query, accountType, accountingGroups);
    });

    $('body').on('change', '.accounting_groups', function() {
        var columnName = $('.sorting').val();
        var orderType = $(this).data('sorting_type');
        var reverseOrder = '';
        var page = 1 ? 1 : $(this).attr('href').split('page=')[1];
        var query = $('#search').val() || '';
        var accountType = $('#account_type').val();
        var accountingGroups = $('#accounting_groups').val();

        fetchData(page, reverseOrder, columnName, query, accountType, accountingGroups);
    });

    $('body').on('change', '.account_type', function() {
        var columnName = $('.sorting').val();
        var orderType = $(this).data('sorting_type');
        var reverseOrder = '';
        var page = 1 ? 1 : $(this).attr('href').split('page=')[1];
        var query = $('#search').val() || '';
        var accountType = $('#account_type').val();
        var accountingGroups = $('#accounting_groups').val();

        fetchData(page, reverseOrder, columnName, query, accountType, accountingGroups);
    });

    $('body').on('click', '.pager a', function(event) {
        event.preventDefault();
        var page = $(this).attr('href').split('page=')[1];
        $('#hidden_page').val(page);
        var columnName = $('.sorting').val() || '';
        var sortType = $('#hidden_sort_type').val();
        var query = $('#search').val() || '';
        var accountType = $('#account_type').val();
        var accountingGroups = $('#accounting_groups').val();
        $('li').removeClass('active');
        $(this).parent().addClass('active');
        fetchData(page, sortType, columnName, query, accountType, accountingGroups);
    });

    /********* 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 columnName = $('.sorting').val() || '';
                            var sortType = $('#hidden_sort_type').val();
                            var query = $('#search').val() || '';

                            fetchData(page, sortType, columnName, query);
                        } else {
                            var errorMsg = $(this).printErrorMsg(response.message);
                            $(this).Toastshow('error', errorMsg);
                        }
                    },
                    error: function(data) {
                        console.log("error ", data);
                    }
                });
            }
        });
    });

    /********* Change Status **********/
    $('body').on('click', '.changeStatusCustom', function(event) {
        var dataString = {
            "id": $(this).data('id'),
            "status": $(this).data('status')
        };
        var urlValue = $(this).data('url');
        var status = $(this).data('status');
        var changeStatus = $(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')
                    },
                    success: function(response) {
                        if (response.success) {
                            var errorMsg = $(this).printErrorMsg(response.message);
                            $(this).Toastshow('success', errorMsg);

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

                            fetchData(page, sortType, columnName, query);
                        } else {
                            var errorMsg = $(this).printErrorMsg(response.message);
                            if (errorMsg === '') {
                                errorMsg = "Something went wrong!";
                            }
                            $(this).Toastshow('error', errorMsg);

                            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 columnName = $('.sorting').val() || '';
                var sortType = $('#hidden_sort_type').val();
                var query = $('#search').val() || '';

                fetchData(page, sortType, columnName, query);
            }
        });
    });

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

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

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

        var error = 0;

        // Vehicle Document Validity Update
        if ($('#commonModal').find('form').hasClass('edit_vehicle_document_validity')) {
            if (error === 0) {
                $.ajax({
                    url: $('#edit_vehicle_document_validity_form').attr('action'),
                    data: $('#edit_vehicle_document_validity_form').serialize(),
                    type: 'PUT',
                    success: function(response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            $('#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 columnName = $('.sorting').val() || '';
                            var sortType = $('#hidden_sort_type').val();
                            var query = $('#search').val() || '';

                            fetchData(page, sortType, columnName, 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!');
                });
            }
        }
    });
</script>

@endsection









