@extends('layouts.app')
@section('title','Books')
@section('pages')
<style type="text/css">
    .add_btn {
        height: 30px; width: 30px; border-radius: 100%; padding: 0
    }
    .intl-tel-input {
        width: 100%;
    }
</style>
<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> Books</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 Book</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('books.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" id="account_form" action="{{ route('books.update', $data->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">Book</h5>
                                    <hr class="mb-0">
                                    <div class="col-md-12">
                                        <label class="form-label">Book Title <span class="text-danger"><b>*</b></span></label>
                                        <input type="text" class="form-control" placeholder="" id="text" value="{!! old('short_name', $data->short_name) !!}" name="short_name">
                                        @if ($errors->has('short_name'))
                                        <span class="text-danger">{{ $errors->first('short_name') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label">ISBN No <span class="text-danger"><b>*</b></span></label>
                                        <div class="input-group">
                                        <input type="text" class="form-control" placeholder="" id="text" value="{!! old('shortcode', $data->shortcode) !!}" name="shortcode">
                                        @if ($errors->has('shortcode'))
                                        <span class="text-danger">{{ $errors->first('shortcode') }}</span>
                                        @endif
                                        @if($data->shortcode=='')
                                        <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success" onclick="getisbn()" type="button"><i class="bi bi-arrow-counterclockwise"></i> Generate ISBN </button>
                                            </div>
                                        @endif
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Category/Genres <span class="text-danger"><b></b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select form-control" name="category_id" >
                                                <option value=" "> Select Genres</option>
                                                @foreach($categories as $list)
                                                <option value="{{ $list->id}}" {!! ($data->category_id == $list->id) ? 'selected' : '' !!}>{{$list->name}}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_genres" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_country_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Authors <span class="text-danger"><b></b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select form-control" name="author_id" >
                                                <option value=" "> Select Author</option>
                                                @foreach($authors as $list)
                                                <option value="{{ $list->id}}" {!! ($data->book_details->author_id == $list->id) ? 'selected' : '' !!}>{{$list->first_name . ' ' . $list->last_name}}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_author" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_country_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Publisher <span class="text-danger"><b></b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select form-control" name="publisher_id" >
                                                <option value=" "> Select Publisher</option>
                                                @foreach($publishers as $list)
                                                <option value="{{ $list->id}}" {!! ($data->book_details->publisher_id == $list->id) ? 'selected' : '' !!}>{{$list->name}}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_publisher" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_country_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Language <span class="text-danger"><b></b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select form-control" name="laguages_id" >
                                                <option value=" "> Select Language</option>
                                                @foreach($languages as $list)
                                                <option value="{{ $list->id}}" {!! ($data->book_details->laguages_id == $list->id) ? 'selected' : '' !!}>{{$list->name}}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_language" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_country_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Streams <span class="text-danger"><b></b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select form-control" name="stream_id">
                                                <option value=" "> Select Streams</option>
                                                @foreach($streams as $list)
                                                <option value="{{ $list->id}}" {!! ($data->book_details->stream_id == $list->id) ? 'selected' : '' !!}>{{$list->stream_name}}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_streams" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_country_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">No Of Pages</label>
                                        <input type="text" class="form-control" placeholder="" id="text" value="{!! old('no_of_pages', $data->book_details->no_of_pages) !!}" name="no_of_pages">
                                        @if ($errors->has('no_of_pages'))
                                        <span class="text-danger">{{ $errors->first('no_of_pages') }}</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 save_account"  type="button"><i class="bx bx-save"></i> Save Book</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">Book Info</h5>
                                    <hr class="mb-0">
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Book Class <span class="text-danger"><b></b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select form-control" name="book_class_id">
                                                <option value=" "> Select Class</option>
                                                @foreach($bookClasses as $list)
                                                <option value="{{ $list->id}}" {!! ($data->book_details->book_class_id == $list->id) ? 'selected' : '' !!}>{{$list->class_name}}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_book_class" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_country_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Tags <span class="text-danger"><b></b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select form-control" name="book_tag_id" >
                                                <option value=" "> Select Tag</option>
                                                @foreach($tags as $list)
                                                <option value="{{ $list->id}}" {!! ($data->book_details->book_tag_id == $list->id) ? 'selected' : '' !!}>{{$list->tag_name}}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_tag" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_country_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Dimensions</label>
                                        <input type="text" class="form-control" placeholder="" id="text" value="{!! old('dimensions', $data->book_details->dimensions) !!}" name="dimensions">
                                        @if ($errors->has('dimensions'))
                                        <span class="text-danger">{{ $errors->first('dimensions') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label class="form-label">Translator <span class="text-danger"><b></b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select form-control" name="translator_id" >
                                                <option value=" "> Select Translator</option>
                                                @foreach($translators as $list)
                                                <option value="{{ $list->id}}" {!! ($data->book_details->translator_id == $list->id) ? 'selected' : '' !!}>{{$list->translator_name}}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_translator" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_country_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label">Url</label>
                                        <input type="text" class="form-control" placeholder="Book Url" id="text" value="{!! old('book_url', $data->book_details->book_url) !!}" name="book_url">
                                        @if ($errors->has('book_url'))
                                        <span class="text-danger">{{ $errors->first('book_url') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label">About Book</label>
                                        <textarea name="description" class="form-control">{!! $data->description !!}</textarea>
                                        @if ($errors->has('description'))
                                        <span class="text-danger">{{ $errors->first('description') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label">Cover Image</label>
                                        <input type="file" class="form-control" placeholder="" value="{!! old('image') !!}" name="image">
                                        @if ($errors->has('image'))
                                        <span class="text-danger">{{ $errors->first('image') }}</span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </div>
                  </form>
              </div>
          </div>
      </div>
  </div>
</div>
  <!--end row-->
@endsection

@section('js')
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>

<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script>
    $(document).on('click', '#create_genres', function() {
        $('#commonModalLabel').text('Add New Category');
        $('.save_button_span').text('Save Category Details');
        $.ajax({
            url:"{!! route('genere.view') !!}",
            success:function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
            }
        });
    });

    $(document).on('click', '#create_author', function() {
        $('#commonModalLabel').text('Add New Author');
        $('.save_button_span').text('Save Author Details');
        $.ajax({
            url:"{!! route('author.view') !!}",
            success:function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
            }
        });
    });

    $(document).on('click', '#create_publisher', function() {
        $('#commonModalLabel').text('Add New Publisher');
        $('.save_button_span').text('Save Publisher Details');
        $.ajax({
            url:"{!! route('publisher.view') !!}",
            success:function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
                $('.single-select').select2({
                    dropdownParent: $('#commonModal'),
                    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')),
                });
            }
        });
    });

    $(document).on('click', '.save_button', function(event){
            event.preventDefault();

            let formdata = new FormData($('#commonModal').find('form')[0]);
            console.log($('#commonModal').find('form').attr('action'));

            $.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.');

                        if ($('#commonModal').find('form').hasClass('genres')) {
                            $('[name="category_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                        }

                        if ($('#commonModal').find('form').hasClass('author')) {
                            $('[name="author_id"]').append(`<option value="${response.data.id}" selected>${response.data.first_name}</option>`);
                        }

                        if ($('#commonModal').find('form').hasClass('publisher')) {
                            $('[name="publisher_id"]').append(`<option value="${response.data.id}" selected>${response.data.name}</option>`);
                        }

                        if ($('#commonModal').find('form').hasClass('language')) {
                            $('[name="laguages_id"]').append(`<option value="${response.data.id}" selected>${response.data.lang_name}</option>`);
                        }

                        if ($('#commonModal').find('form').hasClass('stream')) {
                            $('[name="stream_id"]').append(`<option value="${response.data.id}" selected>${response.data.stream_name}</option>`);
                        }

                        if ($('#commonModal').find('form').hasClass('book_classes')) {
                            $('[name="book_class_id"]').append(`<option value="${response.data.id}" selected>${response.data.class_name}</option>`);
                        }

                        if ($('#commonModal').find('form').hasClass('library-tags')) {
                            $('[name="book_tag_id"]').append(`<option value="${response.data.id}" selected>${response.data.tag_name}</option>`);
                        }

                        if ($('#commonModal').find('form').hasClass('translators')) {
                            $('[name="translator_id"]').append(`<option value="${response.data.id}" selected>${response.data.translator_name}</option>`);
                        }

                        $('.single-select').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')),
                        });

                        // 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!');

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

    $(document).on('click', '#create_language', function() {
        $('#commonModalLabel').text('Add New Language');
        $('.save_button_span').text('Save Language Details');
        $.ajax({
            url:"{!! route('language.view') !!}",
            success:function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
            }
        });
    });

    $(document).on('click', '#create_streams', function() {
        $('#commonModalLabel').text('Add New Stream');
        $('.save_button_span').text('Save Stream Details');
        $.ajax({
            url:"{!! route('stream.view') !!}",
            success:function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
            }
        });
    });

    $(document).on('click', '#create_book_class', function() {
        $('#commonModalLabel').text('Add New Book Class');
        $('.save_button_span').text('Save Book Class Details');
        $.ajax({
            url:"{!! route('book_classes.create') !!}",
            success:function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
            }
        });
    });

    $(document).on('click', '#create_tag', function() {
        $('#commonModalLabel').text('Add New Tag');
        $('.save_button_span').text('Save Tag Details');
        $.ajax({
            url:"{!! route('library-tags.create') !!}",
            success:function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
            }
        });
    });

    $(document).on('click', '#create_translator', function() {
        $('#commonModalLabel').text('Add New Translator');
        $('.save_button_span').text('Save Translator Details');
        $.ajax({
            url:"{!! route('translators.create') !!}",
            success:function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
            }
        });
    });
    $(document).ready(function(){
        // For Student
        var acc_type = $('.account_type_id').find(':selected').attr('data-identifier');
        if (acc_type == 'faculty') {
            // hide
            $('.unique_no').hide();
            $('.house_id').hide();
            $('select[name="settlement_type"]').closest('.col-md-6').hide();
            $('select[name="tax_register_category_id"]').closest('.col-md-6').hide();
            $('input[name="opening_balance"]').closest('.col-md-6').hide();
            $('select[name="balance_type"]').closest('.col-md-6').hide();
            $('select[name="accounting_group_id"]').closest('.col-md-6').hide();
            $('.account_code').closest('.col-md-6').hide();
        } else {
            // hide
            $('.unique_no').hide();
            $('.house_id').hide();
            // show
            $('select[name="settlement_type"]').closest('.col-md-6').show();
            $('select[name="tax_register_category_id"]').closest('.col-md-6').show();
            $('input[name="opening_balance"]').closest('.col-md-6').show();
            $('select[name="balance_type"]').closest('.col-md-6').show();
            $('select[name="accounting_group_id"]').closest('.col-md-6').show();
            $('.account_code').closest('.col-md-6').show();
        }
        // End
    });

    $(document).on('change', '.account_type_id', function () {
        // For Student
        var acc_type = $(this).find(':selected').attr('data-identifier');
        if (acc_type == 'faculty') {
            // hide
            $('.unique_no').hide();
            $('.house_id').hide();
            $('select[name="settlement_type"]').closest('.col-md-6').hide();
            $('select[name="tax_register_category_id"]').closest('.col-md-6').hide();
            $('input[name="opening_balance"]').closest('.col-md-6').hide();
            $('select[name="balance_type"]').closest('.col-md-6').hide();
            $('select[name="accounting_group_id"]').closest('.col-md-6').hide();
            $('.account_code').closest('.col-md-6').hide();
        } else {
            // hide
            $('.unique_no').hide();
            $('.house_id').hide();
            // show
            $('select[name="settlement_type"]').closest('.col-md-6').show();
            $('select[name="tax_register_category_id"]').closest('.col-md-6').show();
            $('input[name="opening_balance"]').closest('.col-md-6').show();
            $('select[name="balance_type"]').closest('.col-md-6').show();
            $('select[name="accounting_group_id"]').closest('.col-md-6').show();
            $('.account_code').closest('.col-md-6').show();
        }
        // End
    });

    $("[name='name']").on('input', function() {
        const input = $(this).val();
        $("[name='print_name']").val(input);
    });
    $(document).on('click','.save_account', function(e) {
        e.preventDefault();
        var error = 0;

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

            $.ajax({
                url: $('#account_form').attr('action'),
                data: formdata,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (response) {
                    if (response.success === true) {
                        toastr.success(response.message, 'Success.');
                        setTimeout(windows.location.href = "{!! route('books.index') !!}", 3000);
                    } 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!');
            });
        }
        error = 1;
    })
    $("[name='opening_balance']").on('input', function() {
        const onlyNumbers = allNumericDecimal($(this).val());
        $("[name='opening_balance']").val(onlyNumbers);
    });
    function allNumericDecimal(inputtxt) {
        onlyNumbers = inputtxt.replace(/[^0-9.]/g, '');
        return onlyNumbers;
    }

    $(document).on('click', '#create_accounting_group', function(){
        $('#commonModalLabel').text('Add New Accounting Group');
        $('.save_button_span').text('Save Accounting Group');
        $.ajax({
          url:"{!! route('accounting-groups.create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

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

    $(document).on('click', '#create_account_type', function(){
        $('#commonModalLabel').text('Add New Account Type');
        $('.save_button_span').text('Save Account Type');
        $.ajax({
          url:"{!! route('account-types.create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

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

    $(document).on('click', '.save_button', function(event){
        event.preventDefault();
        var error = 0;

        if ($('#commonModal').find('form').hasClass('accounting-groups'))
        {
            $('.error_name').hide();
            var error = 0;

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

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

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

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

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

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

                            // 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!');

                    // hide modal
                    $('#commonModal').modal('hide');
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').removeClass('category');
                });
            }
        }
        else if ($('#commonModal').find('form').hasClass('account-category'))
        {

            $('.error_category_name').hide();
            $('.error_category_code').hide();
            $('.error_prefix').hide();
            var error = 0;

            if ($('#commonModal').find('form').find('input[name="category_name"]').val().trim() == '') {
              $('#commonModal').find('.error_category_name').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('input[name="category_code"]').val().trim() == '') {
              $('#commonModal').find('.error_category_code').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('input[name="prefix"]').val().trim() == '') {
              $('#commonModal').find('.error_prefix').show();
              error = 1;
            }

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

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

                            // 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!');

                    // hide modal
                    $('#commonModal').modal('hide');
                    $('#commonModal').find('.modal-body').html('');
                });
            }
        }
        else if ($('#commonModal').find('form').hasClass('account-type'))
        {
            $('.error_enquiry_source_name').hide();
            $('.error_enquiry_source_code').hide();
            $('.error_enquiry_source_priority').hide();

            if ($('#commonModal').find('form').find('input[name="type_name"]').val().trim() == '') {
              $('#commonModal').find('.error_type_name').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('input[name="type_code"]').val().trim() == '') {
              $('#commonModal').find('.error_type_code').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('input[name="prefix"]').val().trim() == '') {
              $('#commonModal').find('.error_prefix').show();
              error = 1;
            }

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

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

                            // 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!');

                    // hide modal
                    $('#commonModal').modal('hide');
                    $('#commonModal').find('.modal-body').html('');
                });
            }
        }
        else if ($('#commonModal').find('form').hasClass('tax_register_categories'))
        {
            if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
              $('#commonModal').find('.error_name').show();
              return;
            } else {
                let formdata = new FormData($('#commonModal').find('form')[0]);

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

                            // 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!');

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

        error = 1;
      })
</script>
@endsection
