@extends('layouts.app')
@section('title','Students')
@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/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> Students</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 Student</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('students.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('students.update', $account->id)}}" method="post" enctype='multipart/form-data'>
                        <!-- For validation comment on -->
                        <!-- <form class="row g-3 was-validated"> -->
                        @csrf
                        @method('patch')
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body g-3 row">
                                    <h5 class="mb-0">Account Details</h5>
                                    <hr class="mb-0">
                                    <div class="col-md-12">
                                        <div>
                                            <label for="name" class="form-label">Account Name  <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" name="name" class="form-control" value="{!! $account->name !!}">
                                        </div>
                                        @if ($errors->has('name'))
                                            <span class="text-danger">{{ $errors->first('name') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-4">
                                        <div>
                                            <label for="admission_date" class="form-label">Admission Date </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="" value="{!! isset($admission->admission_date) ?formatedDate($admission->admission_date) : '' !!}" name="admission_date" class="form-control" id="admission_date" readonly style="cursor: pointer" ></div>
                                        @if ($errors->has('admission_date'))
                                            <span class="text-danger">{{ $errors->first('admission_date') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-4">
                                        <div>
                                            <label for="date_of_birth" class="form-label"> Date Of Birth </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" name="date_of_birth" class="form-control" id="date_of_birth" value="{!! isset($account->account_contact->date_of_birth) && $account->account_contact->date_of_birth!='' ? formatedDate($account->account_contact->date_of_birth):'' !!}" autocomplete="off" readonly>
                                        </div>
                                        @if ($errors->has('date_of_birth'))
                                            <span class="text-danger">{{ $errors->first('date_of_birth') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Gender</label>
                                        <select class="single-select form-control" id="account_gender_id" name="account_gender_id">
                                            <option value=""> -Select- </option>
                                            @foreach($genders as $list)
                                            <option value="{{ $list->id}}" {!! isset($account->account_contact->account_gender_id) && $account->account_contact->account_gender_id==$list->id?'selected':''   !!}>{{$list->name}}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="accounting_group_id" class="form-label">Accounting Group  <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select" name="accounting_group_id">
                                                @foreach($accounting_groups as $list)
                                                <option value="{{ $list->id }}" {!! $account->accounting_group_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_accounting_group" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        @if ($errors->has('accounting_group_id'))
                                            <span class="text-danger">{{ $errors->first('accounting_group_id') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="code" class="form-label">Account Code </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" class="form-control account_code" value="{!! $account->code !!}" readonly>
                                        </div>
                                    </div>
                                    <div class="col-md-12">
                                        <div>
                                            <label for="print_name" class="form-label">Print Name </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" name="print_name" class="form-control" value="{!! $account->print_name !!}">
                                        </div>
                                        @if ($errors->has('print_name'))
                                            <span class="text-danger">{{ $errors->first('print_name') }}</span>
                                        @endif
                                    </div>
                                </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 Account Details</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">
                                        <div>
                                            <label for="settlement_type" class="form-label">Account Settlement Type </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select" name="settlement_type">
                                                <option value="BILL_TO_BILL" {!! $account->settlement_type == 'BILL_TO_BILL' ? 'selected' : '' !!}>BILL TO BILL</option>
                                                <option value="LEDGER" {!! $account->settlement_type == 'LEDGER' ? 'selected' : '' !!}>LEDGER</option>
                                            </select>
                                        </div>
                                        @if ($errors->has('settlement_type'))
                                            <span class="text-danger">{{ $errors->first('settlement_type') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="tax_register_category_id" class="form-label">Tax Register Category</label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select" name="tax_register_category_id">
                                                @foreach($tax_register_categories as $list)
                                                <option value="{{ $list->id }}" {!! $account->tax_register_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_tax_register_categories" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        @if ($errors->has('tax_register_category_id'))
                                            <span class="text-danger">{{ $errors->first('tax_register_category_id') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="account_category_id" class="form-label">Account Category </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select" name="account_category_id">
                                                @foreach($account_categories as $list)
                                                <option value="{{ $list->id }}" {!! $account->account_category_id == $list->id ? 'selected' : ($list->is_default == 1 ? '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_account_category" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        @if ($errors->has('account_category_id'))
                                            <span class="text-danger">{{ $errors->first('account_category_id') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="class_id" class="form-label">Class <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select class_id" name="class_id" required>
                                                <option value="">Select Class</option>
                                                @foreach ($classes as $key => $record)
                                                    <option value="{!! $record->id !!}" {!! (isset($admission->class_id) && $admission->class_id == $record->id) ? 'selected' : '' !!}>{!! $record->class_name !!}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_class" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        @if ($errors->has('class_id'))
                                            <span class="text-danger">{{ $errors->first('class_id') }}</span>
                                        @endif
                                        <span class="text-danger error_enquiry_date" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="section_id" class="form-label">Section <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select section_id" name="section_id" >
                                                @foreach ($sections as $key => $record)
                                                    <option value="{!! $record->academics_section_id !!}"  {!! (isset($admission->section_id) && $admission->section_id == $record->academics_section_id) ? 'selected' : '' !!}>{!! $record->section !!}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_section" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        @if ($errors->has('section_id'))
                                            <span class="text-danger">{{ $errors->first('section_id') }}</span>
                                        @endif
                                        <span class="text-danger error_enquiry_date" style="display:none;">This field is required.</span>
                                    </div>
                                    <!-- <div class="col-md-6">
                                        <div>
                                            <label for="account_type_id" class="form-label">Account Type </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select account_type_id" name="account_type_id" disabled>
                                                @foreach($account_types as $list)
                                                <option value="{{ $list->id }}" data-identifier="{!! strtolower($list->type_name) !!}" {!! $account->account_type_id == $list->id ? 'selected' : ($list->is_default == 1 ? 'selected' : '') !!}>{{ $list->type_name }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        @if ($errors->has('account_type_id'))
                                            <span class="text-danger">{{ $errors->first('account_type_id') }}</span>
                                        @endif
                                    </div> -->
                                    <div class="col-md-6 unique_no" style="display:none;">
                                        <div>
                                            <label for="unique_register_no" class="form-label">Admission/Unique Number </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" name="unique_register_no" class="form-control" value="{!! $account->unique_register_no !!}">
                                        </div>
                                        @if ($errors->has('unique_register_no'))
                                            <span class="text-danger">{{ $errors->first('unique_register_no') }}</span>
                                        @endif
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <div>
                                            <label for="admission_type" class="form-label">Admission Type </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select" name="admission_type">
                                                <option value="Promoted" {!! (isset($admission->admission_type) && $admission->admission_type == 'Promoted') ? 'selected' : '' !!}>Promoted</option>
                                                <option value="Direct" {!! (isset($admission->admission_type) && $admission->admission_type == 'Direct') ? 'selected' : '' !!}>Direct</option>
                                                <option value="Readmission" {!! (isset($admission->admission_type) && $admission->admission_type == 'Readmission') ? 'selected' : '' !!}>Readmission</option>
                                            </select>
                                        </div>
                                        @if ($errors->has('admission_type'))
                                            <span class="text-danger">{{ $errors->first('admission_type') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6 house_id" style="display:none;">
                                        <div>
                                            <label for="house_group_id" class="form-label">Student House </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select" name="house_group_id">
                                                @foreach ($houses as $key => $house)
                                                    <option value="{!! $house->id !!}" @if(isset($account->account_contact->house_group_id)){!! ($account->account_contact->house_group_id == $house->id) ? 'selected' : '' !!}@endif>{!! $house->name !!}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        @if ($errors->has('house_group_id'))
                                            <span class="text-danger">{{ $errors->first('house_group_id') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="opening_balance" class="form-label">Opening Balance </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" name="opening_balance" class="form-control"  value="{!! $account->opening_balance ?? '0' !!}">
                                        </div>
                                        @if ($errors->has('opening_balance'))
                                            <span class="text-danger">{{ $errors->first('opening_balance') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="balance_type" class="form-label">Account Balance Type </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select" name="balance_type">
                                                <option value="DEBIT" {!! $account->balance_type == 'DEBIT' ? 'selected' : '' !!}>DEBIT</option>
                                                <option value="CREDIT" {!! $account->balance_type == 'CREDIT' ? 'selected' : '' !!}>CREDIT</option>
                                            </select>
                                        </div>
                                        @if ($errors->has('balance_type'))
                                            <span class="text-danger">{{ $errors->first('balance_type') }}</span>
                                        @endif
                                    </div>
                                    {{--<div class="col-md-6">
                                        <div>
                                            <label for="referred_by" class="form-label"> Referred By </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" name="referred_by" class="form-control" value="{!! $account->referred_by !!}">
                                        </div>
                                        @if ($errors->has('referred_by'))
                                            <span class="text-danger">{{ $errors->first('referred_by') }}</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 type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>

<script>
     $( function() {
        $('#admission_date').datepicker({
        format: "{!! $companyDateFormate??'dd-mm-yyyy' !!}",
        autoclose: true,
        //startDate: financialYearDates.fromDate,//optional
        //endDate: financialYearDates.toDate//optional
        });
    });
    $(function () {
        $('#date_of_birth').datepicker({
        format: "{!! $companyDateFormate??'dd-mm-yyyy' !!}",
        autoclose: true,
        //startDate: financialYearDates.fromDate,//optional
        //endDate: financialYearDates.toDate//optional
        });

    });
    $(document).on('click', '#create_class', function() {
        $('#commonModalLabel').text('Add New Class');
        $('.save_button_span').text('Save Class Details');
        $.ajax({
            url:"{!! route('classes.create') !!}",
            success:function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
                $('.sections-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', '#create_section', function() {
        $('#commonModalLabel').text('Add New Section');
        $('.save_button_span').text('Save Section Details');
        $.ajax({
            url:"{!! route('sections.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 == 'student' || acc_type == undefined) {
            // show
            $('.unique_no').show();
            $('.house_id').show();
            // 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 == 'student') {
            // show
            $('.unique_no').show();
            $('.house_id').show();
            // 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();

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

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

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

        if ($('input[name="name"]').val().trim() == '') {
          $('.error_name').show();
          error = 1;
        }
        if ($('[name="accounting_group_id"]').val().trim() == '') {
          $('.error_accounting_group_id').show();
          error = 1;
        }
        if ($('[name="country_id"]').val().trim() == '') {
          $('.error_country_id').show();
          error = 1;
        }
        if ($('[name="state_id"]').val().trim() == '') {
          $('.error_state_id').show();
          error = 1;
        }
        if ($('[name="city_id"]').val().trim() == '') {
          $('.error_city_id').show();
          error = 1;
        }
        if ($('input[name="phone_no"]').val().trim() == '') {
          $('.error_phone').show();
          error = 1;
        }

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

            $.ajax({
                url: "{{ route('accounts.store')}}",
                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('accounts.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);
          }
        })
    })

    $(".class_id").on("change", function() {
        var classId = $(this).val();

        // Get sections against selected class.
        $.ajax({
            url:"{!! route('class.sections') !!}",
            // data: formdata,
            /*processData: false,
            contentType: false,*/
            type: 'GET',
            data: {'class': classId},
            success:function(response) {
                if (response.success == false) {
                    toastr.error(response.message, 'Error!');
                }

                if (response.success == true && response.data && response.data != '') {
                    var options = ``;
                    $.each(response.data, function(index, record) {
                        options += `<option value="` + record.academics_section_id + `">` + record.section + `</option>`;
                    });

                    $(".section_id").html(options);

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

                    // toastr.success(response.message, 'Success.');
                } else {
                    $(".section_id").html('');
                }
            }
        }).fail(function(jqXHR, textStatus, errorThrown) {
            toastr.error('An error occurred during the request.', 'Error!');
        });
    });

    $(document).on('click', '.save_button', function(event){
        event.preventDefault();
        if ($('#commonModal').find('form').hasClass('classes') || $('#commonModal').find('form').hasClass('sections')) {
            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('classes')) {
                            $('[name="class_id"]').append(`<option value="${response.data.id}" selected>${response.data.class_name}</option>`);
                            $('[name="class_id"]').trigger('change');
                        }

                        if ($('#commonModal').find('form').hasClass('sections')) {
                            // $('[name="section_id"]').append(`<option value="${response.data.id}" selected>${response.data.section}</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('');
            });
        } else {
            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
