@extends('layouts.app')
@section('title','Enquiries')
@section('pages')
<style type="text/css">
    .add_btn {
        height: 30px; width: 30px; border-radius: 100%; padding: 0
    }
    .intl-tel-input {
        width: 100%;
    }
    .more-less {
        float: right;
        color: #212121;
    }
</style>
<link rel="stylesheet/less" type="text/css" href="{{ asset('admin/plugins/datepicker/less/datepicker.less') }}">
<link href="{{ asset('admin/plugins/datepicker/css/datepicker.css')}}" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<!--breadcrumb-->
<div class="page-breadcrumb d-flex align-items-center mb-3 px-3 px-md-0">
    <div class="breadcrumb-title pe-3"><i class="bi bi-list"></i> Enquiries</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">

                <li class="breadcrumb-item active" aria-current="page">Edit Enquiry</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('enquiries.index')}}" class="btn btn-outline-secondary"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
        </div>
    </div>
</div>
<!--end breadcrumb-->


<div class="row auto">
    <div class="col-xl-12 mx-auto">
        <div class=" shadow-none radius-5 min-height">
            <div class="">
                <div class="">
                    <form class="row g-3 auto-width" action="{{ route('enquiries.update', $enquiry->id)}}" method="post" enctype='multipart/form-data'>
                        @csrf
                        @method('patch')
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body g-3 row">
                                    <h5 class="mb-0">Enquiry Details</h5>
                                    <hr class="mb-0">
                                    <div class="col-md-6">
                                        <div>
                                            <label for="enquiry_category_id" class="form-label">Enquiry Category </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control" name="enquiry_category_id">
                                                @foreach($categories as $list)
                                                <option value="{{ $list->id }}" {!! $list->id == $enquiry->enquiry_category_id ? 'selected' : '' !!}>{{ $list->category_name }}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_category" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        @if ($errors->has('enquiry_category_id'))
                                            <span class="text-danger">{{ $errors->first('enquiry_category_id') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="enquiry_type_id" class="form-label">Enquiry Type </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control" name="enquiry_type_id">
                                                @foreach($types as $list)
                                                <option value="{{ $list->id }}" {!! $list->id == $enquiry->enquiry_type_id ? 'selected' : '' !!}>{{ $list->enquiry_type_name }}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_types" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        @if ($errors->has('enquiry_type_id '))
                                            <span class="text-danger">{{ $errors->first('enquiry_type_id ') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-12">
                                        <label for="contact_id" class="form-label">Full Name <span class="text-danger"><b>*</b></span></label>
                                        <input type="text" class="form-control" value="{{ $enquiry->contact_name }}" disabled>
                                        @if ($errors->has('contact_id'))
                                            <span class="text-danger">{{ $errors->first('contact_id') }}</span>
                                        @endif
                                    </div>
                                </div>
                                <div class="card-body g-3 row additional_fields">
                                </div>
                                <div class="card-body g-3 row">
                                    <div class="col-12" align="center">
                                        <div class="d-grid gap-2 with-100">
                                          <button class="btn btn-primary"  type="submit"><i class="bx bx-save"></i> Update Enquiry</button>
                                      </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body g-3 row">
                                    <h5 class="mb-0">Additional Information</h5>
                                    <hr class="mb-0">
                                    <div class="col-md-6">
                                        <label for="enquiry_date" class="form-label">Enquiry Date </label>
                                        <input type="text" class="form-control" id="enquiry_date" name="enquiry_date" aria-describedby="inputGroupPrepend" value="{!! old('enquiry_date', $enquiry->enquiry_date) !!}">
                                        @if ($errors->has('enquiry_date'))
                                            <span class="text-danger">{{ $errors->first('enquiry_date') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="enquiry_source_id" class="form-label">Enquiry Source </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control" name="enquiry_source_id">
                                                @foreach($sources as $list)
                                                <option value="{{ $list->id }}" {!! $list->id == $enquiry->enquiry_source_id ? 'selected' : '' !!}>{{ $list->enquiry_source_name }}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_source" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        @if ($errors->has('enquiry_source_id'))
                                            <span class="text-danger">{{ $errors->first('enquiry_source_id') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="enquiry_status_id" class="form-label">Enquiry Status </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control" name="enquiry_status_id">
                                                @foreach($statuses as $list)
                                                <option value="{{ $list->id }}" {!! $list->id == $enquiry->enquiry_status_id ? 'selected' : '' !!}>{{ $list->enquiry_status_name }}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_status" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        @if ($errors->has('enquiry_status_id'))
                                        <span class="text-danger">{{ $errors->first('enquiry_status_id') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="enquiry_quality_id" class="form-label">Enquiry Lead Quality </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control" name="enquiry_quality_id">
                                                @foreach($qualities as $list)
                                                <option value="{{ $list->id }}" {!! $list->id == $enquiry->enquiry_quality_id ? 'selected' : '' !!}>{{ $list->enquiry_quality_name }}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_quality" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        @if ($errors->has('enquiry_quality_id'))
                                        <span class="text-danger">{{ $errors->first('enquiry_quality_id') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label" for="enquiry_details">Details </label>
                                        <textarea class="form-textarea" name="enquiry_details" placeholder="Enter Enquiry Details (If Any)">{!! $enquiry->enquiry_details !!}</textarea>
                                        @if ($errors->has('enquiry_details'))
                                        <span class="text-danger">{{ $errors->first('enquiry_details') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-12">
                                        <div>
                                            <label for="contact_id" class="form-label">Attachments</label>
                                        </div>
                                        <div class="input-group">
                                            <input type="file" name="attachments[]" multiple class="form-control">
                                        </div>
                                    </div>
                                    <div class="col-md-12">
                                        <ul class="p-0">
                                            @foreach($attachments as $value)
                                                @if(file_exists(public_path($value->attachment_name)))
                                                    <li style="list-style: none;padding: 5px 0;" class="attachment-{{$value->id}}">
                                                        <a data-url="{{route('attachment.destroy')}}" data-id="{{$value->id}}" class="attachment-delete" href="#" class="text-danger" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Delete">
                                                            <i class="bi bi-trash" style="cursor:pointer; color: red"></i>
                                                        </a> {{ formatPermissionsText($value->attachment_title) }}
                                                        <a href="{!! asset($value->attachment_name) !!}" download="">Download</a>
                                                    </li>
                                                @endif
                                            @endforeach
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                  </form>
              </div>
          </div>
      </div>
  </div>
</div>
<!--end row-->
@endsection

@section('js')
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>

@php $auth_format = \Session::get('company_data')['date_format'] ?? ''; @endphp

<script>
    $("body").on("click",'.attachment-delete', function(event){
        var idValue  = $(this).data('id');
        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  : 'post',
                    data    :{
                        "_token": $('meta[name="csrf-token"]').attr('content'),
                        "id": idValue
                    },
                    headers:
                    {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    success : function(response){
                        if(response.success){
                            $('.attachment-' + idValue).remove();
                            $(this).Toastshow('success',ErroMsg);
                        } else {
                            var ErroMsg = $(this).printErrorMsg(response.message);
                            $(this).Toastshow('error',ErroMsg);
                        }
                    },
                });
            }
        });
    });
    $(document).ready( function() {
        $('[name="enquiry_category_id"]').trigger('change');
    });

    $(document).on('change', '.checkbox_input', function() {
        var checkboxValue = this.checked ? '1' : '0';
        $(this).next('.checkbox_value').val(checkboxValue);
    });

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

        telInput.intlTelInput({
            utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js', // Update the URL to the correct one
            initialCountry: '{!! $countryCode  !!}', // Set the new country code
            separateDialCode: true
        });
    }
    $('#commonModal').on("hidden.bs.modal", function() {
        $('#commonModal').removeClass('contact');
        $('#commonModal').removeClass('category');
        $('#commonModal').removeClass('type');
        $('#commonModal').removeClass('source');
        $('#commonModal').removeClass('status');
        $('#commonModal').removeClass('quality');
        $('#commonModal').removeClass('quality');
    });

    $(document).on('change','select[name="enquiry_category_id"]', function(e) {
        e.preventDefault();
        var id = $(this).val();
        var url = `{!! route('enquiry-category-fields.get', [':id', $id]) !!}`.replace(':id', id);
        var url = url.replace(':enquiry', id);

        $.ajax({
          url:url,
          success:function(data){
            $('.additional_fields').html('');
            $('.additional_fields').html(data);
          }
        })
    })

    $( function() {
        $('#enquiry_date').datepicker({
            format: "{!! phpToJsDateFormat($auth_format) !!}",
        }).on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })
    });

    $('.single-select-clients').select2({
        theme: 'bootstrap4',
        width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
        placeholder: $(this).data('placeholder'),
        allowClear: Boolean($(this).data('allow-clear')),
        ajax: {
            url: "{!! route('get-contacts') !!}",
            dataType: 'json',
            delay: 250,
            processResults: function (data) {
              return {
                results:  $.map(data, function (item) {
                      return {
                          text: item.name,
                          id: item.id
                      }
                  })
              };
            },
            cache: true
        }
    });

    $(document).on('click', '#create_category', function(){
        $('#commonModalLabel').text('Add New Enquiry Category');
        $('.save_button_span').text('Save Enquiry Category');
        $.ajax({
          url:"{!! route('enquiry-categories.create') !!}",
          success:function(data){
            $('#commonModal').addClass('category');
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

    $(document).on('click', '#create_types', function(){
        $('#commonModalLabel').text('Add New Enquiry Types');
        $('.save_button_span').text('Save Enquiry Types');
        $.ajax({
          url:"{!! route('enquiry-types.create') !!}",
          success:function(data){
            $('#commonModal').addClass('type');
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

    $(document).on('click', '#create_source', function(){
        $('#commonModalLabel').text('Add New Enquiry Source');
        $('.save_button_span').text('Save Enquiry Source');
        $.ajax({
          url:"{!! route('enquiry-sources.create') !!}",
          success:function(data){
            $('#commonModal').addClass('source');
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

    $(document).on('click', '#create_status', function(){
        $('#commonModalLabel').text('Add New Enquiry Status');
        $('.save_button_span').text('Save Enquiry Status');
        $.ajax({
          url:"{!! route('enquiry-statuses.create') !!}",
          success:function(data){
            $('#commonModal').addClass('status');
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

    $(document).on('click', '#create_quality', function(){
        $('#commonModalLabel').text('Add New Enquiry quality');
        $('.save_button_span').text('Save Enquiry quality');
        $.ajax({
          url:"{!! route('enquiry-qualities.create') !!}",
          success:function(data){
            $('#commonModal').addClass('quality');
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

    $(document).on('click', '#create_contact', function(){
        $('#commonModalLabel').text('Add New Contact');
        $('.save_button_span').text('Save Contact');
        $.ajax({
          url:"{!! route('contact-model') !!}",
          success:function(data){
            $('#commonModal').addClass('contact');
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            reinitializeTelInput();
          }
        })
    })

    $(document).on('click','.save_button', function(event) {
        event.preventDefault();
        if ($('#commonModal').hasClass('contact')) {
            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());
            }

            if ($('#alternative_no').val().trim() != '') {
                var dailcode_title = $('.alternative_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="alternative_no"]').val("+" + dailcode_array[1] + $('#alternative_no').val());
            }

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

            if ($('input[name="name"]').val() == '') {
              $('.error_name').show();
              error = 1;
            }
            if ($('input[name="email"]').val() == '') {
              $('.error_email').show();
              error = 1;
            }
            if ($('input[name="phone_no"]').val() == '') {
              $('.error_phone').show();
              error = 1;
            }

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

                $.ajax({
                    url: "{!! route('contacts.store') !!}",
                    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="contact_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                            $('[name="contact_id"]').trigger('change');

                            // hide modal
                            $("#commonModal .btn-close").click()
                            $('#commonModal').removeClass('contact');
                            $('#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!');

                    // hide modal
                    $("#commonModal .btn-close").click()
                    $('#commonModal').removeClass('contact');
                    $('#commonModal').find('.modal-body').html('');
                });
            }
            error = 1;
        }
        else if ($('#commonModal').hasClass('category')) {
            if ($('#commonModal').find('form').find('input[name="category_name"]').val().trim() == '') {
              $('.error_category').show();
              return;
            } else {
                let formdata = new FormData($('#category_form')[0]);

                $.ajax({
                    url: "{!! route('enquiry-categories.store') !!}",
                    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="enquiry_category_id"]').append(`<option value="${response.data.id}" selected>${response.data.category_name}</option>`);
                            $('[name="enquiry_category_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').removeClass('category');
                        } 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('');
                    $('#commonModal').removeClass('category');
                });
            }
        }
        else if ($('#commonModal').hasClass('type')) {
            $('.error_enquiry_type_name').hide();
            $('.error_enquiry_type_priority').hide();
            $('.error_enquiry_type_description').hide();
            var error = 0;

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

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

                $.ajax({
                    url: "{!! route('enquiry-types.store') !!}",
                    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="enquiry_type_id"]').append(`<option value="${response.data.id}" selected>${response.data.enquiry_type_name}</option>`);
                            $('[name="enquiry_type_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').removeClass('type');
                        } 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('');
                    $('#commonModal').removeClass('type');
                });
            }
        }
        else if ($('#commonModal').hasClass('source')) {
            $('.error_enquiry_source_name').hide();
            $('.error_enquiry_source_code').hide();
            $('.error_enquiry_source_priority').hide();
            var error = 0;

            if ($('#commonModal').find('form').find('input[name="enquiry_source_name"]').val().trim() == '') {
              $('.error_enquiry_source_name').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('input[name="enquiry_source_code"]').val().trim() == '') {
              $('.error_enquiry_source_code').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('input[name="enquiry_source_priority"]').val().trim() == '') {
              $('.error_enquiry_source_priority').show();
              error = 1;
            }

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

                $.ajax({
                    url: "{!! route('enquiry-sources.store') !!}",
                    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="enquiry_source_id"]').append(`<option value="${response.data.id}" selected>${response.data.enquiry_source_name}</option>`);
                            $('[name="enquiry_source_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').removeClass('source');
                        } 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('');
                    $('#commonModal').removeClass('source');
                });
            }
        }
        else if ($('#commonModal').hasClass('status')) {
            $('.error_enquiry_status_name').hide();
            $('.error_enquiry_status_priority').hide();
            $('.error_color').hide();
            $('.error_bg_color').hide();
            var error = 0;

            if ($('#commonModal').find('form').find('input[name="enquiry_status_name"]').val().trim() == '') {
              $('.error_enquiry_status_name').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('input[name="enquiry_status_priority"]').val().trim() == '') {
              $('.error_enquiry_status_priority').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('input[name="color"]').val().trim() == '') {
              $('.error_color').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('input[name="bg_color"]').val().trim() == '') {
              $('.error_bg_color').show();
              error = 1;
            }

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

                $.ajax({
                    url: "{!! route('enquiry-statuses.store') !!}",
                    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="enquiry_status_id"]').append(`<option value="${response.data.id}" selected>${response.data.enquiry_status_name}</option>`);
                            $('[name="enquiry_status_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').removeClass('status');
                        } 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('');
                    $('#commonModal').removeClass('status');
                });
            }
        }
        else if ($('#commonModal').hasClass('quality')) {
            $('.error_enquiry_quality_name').hide();
            $('.error_enquiry_quality_priority').hide();
            var error = 0;

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

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

                $.ajax({
                    url: "{!! route('enquiry-qualities.store') !!}",
                    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="enquiry_quality_id"]').append(`<option value="${response.data.id}" selected>${response.data.enquiry_quality_name}</option>`);
                            $('[name="enquiry_quality_id"]').trigger('change');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').removeClass('quality');
                        } 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('');
                    $('#commonModal').removeClass('quality');
                });
            }
        }
    })
</script>
@endsection
