@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%;
    }
    .account_title {
        width: 50px;
        border: 1px solid #ced4da;
        border-top-left-radius: 4px;
        border-bottom-left-radius: 4px;
    }
</style>
<link rel="stylesheet" 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">
<!--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">Add New 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="">
                    {{ \Request::get('redirect_back') }}
                    <form class="row g-3 auto-width" action="{{ route('books.store')}}" method="post" enctype='multipart/form-data' id="account_form">
                        <!-- For validation comment on -->
                        <!-- <form class="row g-3 was-validated"> -->
                        @csrf
                        <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') !!}" 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="isbn_no" value="{!! old('shortcode') !!}" name="shortcode">
                                        @if ($errors->has('shortcode'))
                                        <span class="text-danger">{{ $errors->first('shortcode') }}</span>
                                        @endif
                                            <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>
                                        </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}}">{{$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}}">{{$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}}">{{$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}}">{{$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}}">{{$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') !!}" 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}}">{{$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}}">{{$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') !!}" 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}}">{{$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') !!}" 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"></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 type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js') }}"></script>
<script src="{!! asset('admin/js/accounts.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]);

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

    $( function() {
        $('#date_of_birth').datepicker();
    });

    $("#phone_no").on('input', function() {
        const onlyNumbers = allNumeric($(this).val());
        $("#phone_no").val(onlyNumbers);
    });
    $("#whatsapp_no").on('input', function() {
        const onlyNumbers = allNumeric($(this).val());
        $("#whatsapp_no").val(onlyNumbers);
    });
    function allNumeric(inputtxt) {
        onlyNumbers = inputtxt.replace(/[^0-9]/g, '');
        if (onlyNumbers.length > 16) {
            onlyNumbers = onlyNumbers.substring(0, 16);
        }
        return onlyNumbers;
    }
    $("[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;
    }

    $("[name='name']").on('input', function() {
        const input = $(this).val();
        $("[name='print_name']").val(input);
    });

    $(document).on('click','.save_account', function(e) {
        e.preventDefault();

        $('.error_name').hide();
        $('.error_email').hide();
        $('.error_phone').hide();
        $('.error_accounting_group_id').hide();
        $('.error_country_id').hide();
        $('.error_state_id').hide();
        $('.error_city_id').hide();
        $('.error_account_category_id').hide();
        $('.error_tax_register_category_id').hide();
        $('.error_account_type_id').hide();
        var error = 0;

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

            $.ajax({
                url: "{{ route('books.store')}}",
                data: formdata,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (response) {
                    if (response.success === true) {
                        var redirectBack = "{{ request()->input('redirect_back') }}";
                        console.log(redirectBack);
                        if (redirectBack === 'true') {
                            window.history.back();
                        }

                        else{
                            toastr.success(response.message, 'Success.');
                            setTimeout(window.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;
    })
    $(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();
            $('input[name="opening_balance"]').closest('.col-md-6').hide();
            $('select[name="balance_type"]').closest('.col-md-6').hide();
            $('select[name="settlement_type"]').closest('.col-md-6').hide();
            $('select[name="tax_register_category_id"]').closest('.col-md-6').hide();
            $('select[name="accounting_group_id"]').closest('.col-md-12').hide();
        } else {
            // hide
            $('.unique_no').hide();
            $('.house_id').hide();
            // show
            $('input[name="opening_balance"]').closest('.col-md-6').show();
            $('select[name="balance_type"]').closest('.col-md-6').show();
            $('select[name="settlement_type"]').closest('.col-md-6').show();
            $('select[name="tax_register_category_id"]').closest('.col-md-6').show();
            $('select[name="accounting_group_id"]').closest('.col-md-12').show();
        }
        // End

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content')
            }
        });
        changecontry();
        $('#states').trigger('change');

    });
    function changecontry()
    {
        $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        let country=$('#country').val();
        let stateid=$('#stateid').val();

        $.ajax({
            type: "POST",
            url: "{{ url('companies/getstate') }}",
            data: {country:country,stateid:stateid},
            success: function (data) {
                $('#states').html(data);
                $('#states').trigger('change');
            },
            error: function (data) {
                console.log(data);
            }
        });
        $.ajax({
            type: "POST",
            url: "{{ url('companies/getcountrycode') }}",
            data: {
                country: country
            },
            success: function (countryCode) {
                var telInput = $('#phone_no, #whatsapp_no, #alternative_no');

                // Destroy the existing instances
                telInput.intlTelInput('destroy');

                // Reinitialize the input fields with the new country code
                telInput.intlTelInput({
                    utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js',
                    initialCountry: countryCode, // Set the received country code directly
                    separateDialCode: true
                });
            },
            error: function (data) {
                // Handle error
            }
        });
    }

    $(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();
            $('input[name="opening_balance"]').closest('.col-md-6').hide();
            $('select[name="balance_type"]').closest('.col-md-6').hide();
            $('select[name="settlement_type"]').closest('.col-md-6').hide();
            $('select[name="tax_register_category_id"]').closest('.col-md-6').hide();
            $('select[name="accounting_group_id"]').closest('.col-md-12').hide();
        } else {
            // hide
            $('.unique_no').hide();
            $('.house_id').hide();
            // show
            $('input[name="opening_balance"]').closest('.col-md-6').show();
            $('select[name="balance_type"]').closest('.col-md-6').show();
            $('select[name="settlement_type"]').closest('.col-md-6').show();
            $('select[name="tax_register_category_id"]').closest('.col-md-6').show();
            $('select[name="accounting_group_id"]').closest('.col-md-12').show();
        }
        // End
    });

    $(document).on('change', '#states', function () {
        let states_id=$('#states').val()?$('#states').val():"{{isset($company_address->state_id) ? $company_address->state_id : ''}}";
        let cityid=$('#cityid').val();

        $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            type: "POST",
            url: "{{ url('companies/getcity') }}",
            data: {states_id:states_id,cityid:cityid},
            success: function (data) {
                $('#cities').html(data);
            },
            error: function (data) {
                console.log(data);
            }
        });
    })

    $(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;
      })


function getisbn() {

$.ajax({
    type: 'get',
    url: "{{ route('books.getisbn') }}",
    success: function (result)
    {
       $('#isbn_no').val(result);
    }
});

}
</script>
@endsection
