@extends('layouts.app')
@section('title','Accounts')
@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> Accounts</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 Account</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('accounts.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('accounts.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">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">
                                            <select class="account_title" name="account_title_id" style="width:70px;">
                                                <option value="">Title</option>
                                                @foreach($account_title as $list)
                                                <option value="{{ $list->id }}" {!! matchSelected($list->account_title_id, $list->id) !!}>{{ $list->name }} - {{ $list->gender->name ?? '' }}</option>
                                                @endforeach
                                            </select>
                                            <input type="text" name="name" class="form-control" value="{!! old('name') !!}" placeholder="Account Name">
                                        </div>
                                        @if ($errors->has('name'))
                                            <span class="text-danger">{{ $errors->first('name') }}</span>
                                        @endif
                                        <span class="text-danger error_name" 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<span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="account_type_id form-control" name="account_type_id">
                                                @foreach($account_types as $list)
                                                <option value="{{ $list->id }}" data-identifier="{!! strtolower($list->type_name) !!}" {!! $list->is_default == 1 ? 'selected' : '' !!} {!! request()->has('type') && strtolower(request()->type) == strtolower($list->type_name) ? 'selected' : '' !!}>{{ $list->type_name }}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append" style="margin: auto 10px;">
                                                <button class="btn btn-success add_btn" id="create_account_type" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div>
                                        </div>
                                        @if ($errors->has('account_tyxpe_id'))
                                            <span class="text-danger">{{ $errors->first('account_type_id') }}</span>
                                        @endif
                                        <span class="text-danger error_account_type_id" style="display:none;">This field is required.</span>
                                    </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="form-control" name="accounting_group_id">
                                                <option value=""> -Select -</option>
                                                @foreach($accounting_groups as $list)
                                                <option value="{{ $list->id }}" {!! old('accounting_group_id') == $list->id ? 'selected' : '' !!} {!! request()->has('type') && request()->type == 'customer' && strtolower($list->name) == 'sundry debtors' ? 'selected' : '' !!} {!! request()->has('type') && request()->type == 'doctor' && strtolower($list->name) == 'sundry creditors' ? '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
                                        <span class="text-danger error_accounting_group_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-12 qualification">
                                        <label for="qualification" class="form-label">Qualification <span class="text-danger"><b>*</b></span></label>
                                        <input type="text" class="form-control" id="qualification" name="qualifications" placeholder="e.g. MBBS" aria-describedby="inputGroupPrepend">
                                        <span class="text-danger error_qualification" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-8">
                                        <div>
                                            <label for="address_line1" class="form-label">Account address </label>
                                        </div>
                                        <div class="input-group">
                                            <textarea class="form-textarea" name="address_line1" rows="1">{!! old('address_line1') !!}</textarea>
                                        </div>
                                        @if ($errors->has('address_line1'))
                                            <span class="text-danger">{{ $errors->first('address_line1') }}</span>
                                        @endif
                                        <span class="text-danger error_address_line1" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Country</label>
                                        <select class="form-control" id="country" name="country_id" onchange="changecontry()" required>
                                            <option value=" "> Select Country</option>
                                            @foreach($country as $list)
                                            <option value="{{ $list->id}}" {!! old('country_id', ($company_address->country_id ?? '')) == $list->id ? 'selected' : '' !!}
                                                    {!! $company_address['country_id']?($company_address['country_id']==$list->id?'selected':''):'' !!}>{{$list->name}}</option>
                                            @endforeach
                                        </select>
                                        <span class="text-danger error_country_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">State</label>
                                        <input type="hidden" value="@if(isset($company_address['state_id'])){{$company_address['state_id']}}@endif" id="stateid">
                                        <select class="form-control" name="state_id" id="states">
                                        </select>
                                        <span class="text-danger error_state_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">City</label>
                                        {{-- @dd($company_address['city_id']); --}}
                                        <input type="hidden" value="@if(isset($company_address['city_id'])){{$company_address['city_id']}}@endif" name="cityid">
                                        <select class="form-control" name="city_id" id="cities">
                                        </select>
                                        <span class="text-danger error_city_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Pin Code</label>
                                        <input class="form-control" name="pin" id="pin" placeholder="Pin Code" />
                                    </div>
                                    <div class="col-md-6 phone_no_col">
                                        <label class="form-label">Phone no<span class="text-danger"><b>*</b></span></label>
                                        <input type="tel" class="form-control" placeholder="" id="phone_no" value="{!! old('phone_no') !!}" />
                                        <input type="hidden" name="phone_no">

                                        @if ($errors->has('phone_no'))
                                        <span class="text-danger">{{ $errors->first('phone_no') }}</span>
                                        @endif
                                        <span class="text-danger error_phone" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6 whatsapp_no_col">
                                        <label class="form-label">Whatsapp no </label>
                                        <input type="tel" class="form-control" placeholder="" id="whatsapp_no" value="{!! old('whatsapp_no') !!}"/>
                                        <input type="hidden" name="whatsapp_no">
                                        @if ($errors->has('whatsapp_no'))
                                        <span class="text-danger">{{ $errors->first('whatsapp_no') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-12">
                                        <label class="form-label">Email </label>
                                        <input type="email" class="form-control" placeholder="Email" id="email" value="{!! old('email') !!}" name="email">
                                        @if ($errors->has('email'))
                                        <span class="text-danger">{{ $errors->first('email') }}</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 Account Details</button>
                                      </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card">

                                <div class="card-body g-3 row">
                                    <div class="col-md-7"><h5 class="mb-0">Additional Information</h5></div>
                                    <div class="col-md-5" style="text-align: right;display: flex; justify-content: space-between;">
                                        <label for="validationCustomOrder" style="    margin-left: 24px; margin-top: 3px;" class="form-label">Primary Account </label><br>
                                        <input name="primary_account" class="form-check-inputFeatured btn-lg primary_account" type="checkbox" id="primary_account" value="0">
                                        @if ($errors->has('primary_account'))
                                        <span class="text-danger">{{ $errors->first('primary_account') }}</span>
                                        @endif
                                        <span class="text-danger error_name" style="display: none;">This field is required.</span>
                                    </div>
                                    <hr class="mb-0">

                                    <div class="col-md-6">
                                        <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="{!! old('print_name') !!}">
                                        </div>
                                        @if ($errors->has('print_name'))
                                            <span class="text-danger">{{ $errors->first('print_name') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Contact Person </label>
                                        <input type="text" class="form-control" placeholder="" id="contact" value="{!! old('contact') !!}" name="contact">
                                        @if ($errors->has('contact'))
                                        <span class="text-danger">{{ $errors->first('contact') }}</span>
                                        @endif
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="settlement_type" class="form-label">Account Settlement Type </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control" name="settlement_type">
                                                <option value="BILL_TO_BILL">BILL TO BILL</option>
                                                <option value="LEDGER">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="form-control" name="tax_register_category_id">
                                                @foreach($tax_register_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_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
                                        <span class="text-danger error_tax_register_category_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="account_category_id" class="form-label">Account Category <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control" name="account_category_id">
                                                @foreach($account_categories as $list)
                                                <option value="{{ $list->id }}" {!! $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
                                        <span class="text-danger error_account_category_id" style="display:none;">This field is required.</span>
                                    </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">
                                        </div>
                                        @if ($errors->has('unique_register_no'))
                                            <span class="text-danger">{{ $errors->first('unique_register_no') }}</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="form-control" name="house_group_id">
                                                @foreach ($houses as $key => $house)
                                                    <option value="{!! $house->id !!}">{!! $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" value="0" name="opening_balance" class="form-control">
                                        </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="form-control" name="balance_type">
                                                <option value="DEBIT">DEBIT</option>
                                                <option value="CREDIT">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" placeholder="Referred By">
                                        </div>
                                        @if ($errors->has('referred_by'))
                                            <span class="text-danger">{{ $errors->first('referred_by') }}</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" autocomplete="off" readonly style="">
                                        </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="form-control" id="account_gender_id" name="account_gender_id">
                                            <option value=""> -Select- </option>
                                            @foreach($genders as $list)
                                            <option value="{{ $list->id}}">{{$list->name}}</option>
                                            @endforeach
                                        </select>
                                    </div> --}}
                                    <div class="col-md-4">
                                        <label class="form-label">Marital Status</label>
                                        <select class="form-control" id="marital_status" name="marital_status">
                                            <option value=" "> -Select- </option>
                                            @foreach($maritalStatus as $list)
                                            <option value="{{ $list->id}}">{{$list->name}}</option>
                                            @endforeach
                                        </select>
                                    </div>

                                    <div class="col-md-4">
                                        <label class="form-label">Blood Group</label>
                                        <select class="form-control" id="blood_group_id" name="blood_group_id">
                                            <option value=" "> -Select- </option>
                                            @foreach($bloodGroup as $list)
                                            <option value="{{ $list->id}}">{{$list->group}}</option>
                                            @endforeach
                                        </select>
                                    </div>


                                    <div class="col-md-12" style="display: none;">
                                        <label class="form-label">Any known allergies</label>
                                        <textarea name="any_known_allergies" class="form-textarea"></textarea>
                                        @if ($errors->has('any_known_allergies'))
                                        <span class="text-danger">{{ $errors->first('any_known_allergies') }}</span>
                                        @endif
                                        <span class="text-danger error_any_known_allergies" style="display:none;">This field is required.</span>
                                    </div>

                                    @foreach($license_types as $key => $value)
                                        <div class="col-md-6">
                                            <label for="license_number" class="form-label">{{ $value->name }} <span class="text-danger"><b>*</b></span></label>
                                            <input type="text" class="form-control" id="license_number[{{$value->code}}][license_number]" name="license_number[{{$value->code}}][license_number]" aria-describedby="inputGroupPrepend" required>
                                            <input type="hidden" name="license_number[{{$value->code}}][license_type_id]" value="{{ $value->id }}">
                                        </div>
                                    @endforeach

                                    </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).ready(function() {

        // Change the following selector to match your actual checkbox ID
        $('#primary_account').change(function() {
            if ($(this).is(':checked')) {
                $(this).val(1);
            } else {
                $(this).val(0);
            }
        });
    });

    $(function () {
        $('#date_of_birth').datepicker({
            dateFormat: 'dd mm yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });

    var telInput = $('#phone_no , #whatsapp_no');
    telInput.intlTelInput({
        utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js', // Update the URL to the correct one
        initialCountry: '{!! $countryCode  !!}', // Set the new country code
        separateDialCode: true
    });

    // $.switcher('.primary_account');
    // Re-initialize the datepicker
    $( function() {
        $('#valid_from').datepicker();
    });
    $( function() {
        $('#valid_from').datepicker();
    });
    $( function() {
        $('#valid_upto').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);
        $("[name='contact']").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();
        $('.error_account_category_id').hide();
        $('.error_tax_register_category_id').hide();
        $('.error_account_type_id').hide();
        $('.error_license_number').hide();
        $('.error_valid_from').hide();
        $('.error_valid_upto').hide();


        var error = 0;

        if ($('input[name="name"]').val().trim() == '') {
          $('.error_name').show();
          error = 1;
            setTimeout(function () {
                $('.error_name').hide();
            }, 3000);
        }
        if ($('[name="accounting_group_id"]').val() == '' || $('[name="accounting_group_id"]').val() == null) {
            if ($('.account_type_id').find(':selected').attr('data-identifier') != 'student') {
                $('.error_accounting_group_id').show();
                error = 1;
            }
        }
        if ($('[name="tax_register_category_id"]').val() == '' || $('[name="tax_register_category_id"]').val() == null) {
          $('.error_tax_register_category_id').show();
          error = 1;
        }
        if ($('[name="account_type_id"]').val() == '' || $('[name="account_type_id"]').val() == null) {
          $('.error_account_type_id').show();
          error = 1;
        }
        if ($('[name="account_category_id"]').val() == '' || $('[name="account_category_id"]').val() == null) {
          $('.error_account_category_id').show();
          error = 1;
        }
        if ($('[name="country_id"]').val() == '') {
          $('.error_country_id').show();
          error = 1;
        }
        if ($('input[name="phone_no"]').val() == '') {

          $('.error_phone').show();
                setTimeout(function () {
                $('.error_phone').hide();
            }, 3000);
          error = 1;
        }

        if ($('[name="license_number"]').val() != undefined && $('[name="license_number"]').val() == '' ) {
          $('.error_license_number').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) {
                        var redirectBack = "{{ request()->input('redirect_back') }}";
                        var type = "{{ request()->input('type') }}";
                        var callback = "{{ request()->input('callback') }}";
                        console.log(redirectBack);
                        if (redirectBack === 'true') {
                            window.history.back();
                        } else if (type == 'customer' && callback == 'license') {
                            toastr.success(response.message, 'Success.');
                            setTimeout(window.location.href = "{!! route('license-register.create') !!}", 3000);
                        } else if (type == 'customer') {
                            toastr.success(response.message, 'Success.');
                            setTimeout(window.location.href = "{!! route('customer-list.index') !!}", 3000);
                        }

                        else{
                            toastr.success(response.message, 'Success.');
                            setTimeout(window.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;
    })

    $(document).ready(function(){
        // For Student
        var acc_type = $('.account_type_id').find(':selected').attr('data-identifier');
        if (acc_type == 'student') {
            // show
            $('.unique_no').show();
            $('.house_id').show();
            $('.qualification').hide();
            // 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 if(acc_type == 'doctor' || acc_type == 'employee' || acc_type == 'faculty'){
            $('.qualification').show();
        }
        else {
            // hide
            $('.unique_no').hide();
            $('.house_id').hide();
            $('.qualification').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 == 'student') {
            // show
            $('.unique_no').show();
            $('.house_id').show();
            // 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();
            $('[name="any_known_allergies"]').closest('.col-md-12').hide();
            $('.qualification').hide();
        } else if (acc_type == 'patient') {
            // hide
            $('.unique_no').hide();
            $('.house_id').hide();
            $('[name="any_known_allergies"]').closest('.col-md-12').show();
            $('.qualification').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();
        } else if(acc_type == 'doctor' || acc_type == 'employee' || acc_type == 'faculty'){
            $('.qualification').show();
        } else {
            // hide
            $('.unique_no').hide();
            $('.house_id').hide();
            $('.qualification').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();
            $('[name="any_known_allergies"]').closest('.col-md-12').hide();
        }
        // 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;
    })

    $(document).on('change', '.account_type_id', function () {
        var selectedType = $('[name="account_type_id"]').val();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({
            type: "POST",
            url: "{{ url('account-type-groups') }}",
            data: {
                selectedType: selectedType
            },
            success: function (data) {
                if (data.success === true) {
                    var content = '';
                    if (data.name == 'GENERAL') {
                        content = '<option value="">-- Select --</option>' + content;
                    }

                    $.each(data.data, function (index, value) {
                        content += '<option value="' + value.id + '">' + value.name + '</option>';
                    });

                    $('[name="accounting_group_id"]').html(content);
                }
            },
            error: function (data) {
                console.log(data);
            }
        });
    });


    $(document).ready(function () {
        toggleFieldsBasedOnIsPerson();

        $('select[name="account_type_id"]').change(function () {
            toggleFieldsBasedOnIsPerson();
        });

        function toggleFieldsBasedOnIsPerson() {
            var accountTypeId = $('select[name="account_type_id"]').val();

            $.ajax({
                url: "{{ url('get-account-type-person') }}",
                type: 'POST',
                data: {
                    accountTypeId: accountTypeId
                },
                success: function (response) {
                    console.log(response);
                    if (response.isPerson == 1) {
                        $('input[name="date_of_birth"]').closest('.col-md-4').show();
                        $('#marital_status').closest('.col-md-4').show();
                        $('#blood_group_id').closest('.col-md-4').show();
                    } else {
                        $('input[name="date_of_birth"]').closest('.col-md-4').hide();
                        $('#marital_status').closest('.col-md-4').hide();
                        $('#blood_group_id').closest('.col-md-4').hide();
                    }
                },
                error: function (error) {
                    console.error('Error fetching Account Type information:', error);
                }
            });
        }
    });


</script>
@endsection
