@extends('layouts.app')
@section('title','Employees')
@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> Employees</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 Employees</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('employee.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('employee.update', $data->id)}}" method="post" enctype='multipart/form-data' id="update_employee">
                        @csrf
                        @method('patch')
                        <!-- 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">Employee Details</h5>
                                    <hr class="mb-0">
                                    <div class="col-md-12">
                                        <div>
                                            <label for="name" class="form-label">Employee Name  <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="title" name="title_id" style="width:70px;">
                                                <option value="">Title</option>
                                                @foreach($title as $list)
                                                <option value="{{ $list->id }}" {{ $list->id == $data->title_id ? 'selected':'' }}>{{ $list->name }}</option>
                                                @endforeach
                                            </select>
                                            <input type="text" name="name" class="form-control"  placeholder="Employee Name" value="{{$data->name}}">
                                        </div>
                                        @if ($errors->has('name'))
                                            <span class="text-danger">{{ $errors->first('name') }}</span>
                                        @endif
                                        <span class="text-danger error_title_id" style="display:none;">This field is required.</span>
                                        <span class="text-danger error_name" style="display:none;">This field is required.</span>
                                    </div>
                                    <!-- Email-->
                                    <div class="col-md-6">
                                        <label class="form-label">Email </label>
                                        <input type="email" class="form-control" placeholder="Email" id="email"  name="email" placeholder="Email" value="{{$data->email}}">
                                        @if ($errors->has('email'))
                                        <span class="text-danger">{{ $errors->first('email') }}</span>
                                        @endif
                                        <span class="text-danger error_email" style="display:none;">This field is required.</span>
                                    </div>

                                    <!-- Designation-->
                                    <div class="col-md-6">
                                        <div>
                                            <label for="designation_id" class="form-label">Designation </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control designation_id" name="designation_id">
                                                <option value="">-- Select --</option>
                                                @foreach($designation as $list)
                                                <option value="{{ $list->id }}" {{ $list->id == $data->designation_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_account_type" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div> --}}
                                        </div>
                                        @if ($errors->has('designation_id'))
                                            <span class="text-danger">{{ $errors->first('designation_id') }}</span>
                                        @endif
                                        <span class="text-danger error_designation_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <!-- department-->
                                    <div class="col-md-6">
                                        <div>
                                            <label for="department_id" class="form-label">Department </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control department_id" name="department_id">
                                                <option value="">-- Select --</option>
                                                @foreach($department as $list)
                                                <option value="{{ $list->id }}" {{ $list->id == $data->department_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_account_type" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div> --}}
                                        </div>
                                        @if ($errors->has('department_id'))
                                            <span class="text-danger">{{ $errors->first('department_id') }}</span>
                                        @endif
                                        <span class="text-danger error_department_id" style="display:none;">This field is required.</span>
                                    </div>

                                    <!-- gender-->
                                    <div class="col-md-6">
                                        <div>
                                            <label for="gender_id" class="form-label">Gender <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control gender_id" name="gender_id">
                                                <option value="">-- Select --</option>
                                                @foreach($gender as $list)
                                                <option value="{{ $list->id }}" {{ $list->id == $data->gender_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_account_type" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div> --}}
                                        </div>
                                        @if ($errors->has('gender_id'))
                                            <span class="text-danger">{{ $errors->first('gender_id') }}</span>
                                        @endif
                                        <span class="text-danger error_gender_id" style="display:none;">This field is required.</span>
                                    </div>

                                    <!-- language-->
                                    <div class="col-md-6">
                                        <div>
                                            <label for="language_id" class="form-label">Language </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control language_id" name="language_id">
                                                <option value="">-- Select --</option>
                                                @foreach($language as $list)
                                                <option value="{{ $list->id }}" {{ $list->id == $data->language_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_account_type" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div> --}}
                                        </div>
                                        @if ($errors->has('language_id'))
                                            <span class="text-danger">{{ $errors->first('language_id') }}</span>
                                        @endif
                                        <span class="text-danger error_language_id" style="display:none;">This field is required.</span>
                                    </div>
                                     <!-- phone_no-->
                                     <div class="col-md-6 phone_no_col">
                                        <label class="form-label">Mobile NO</label>
                                        <input type="tel" class="form-control" placeholder="Mobile Number" id="phone_no" value="{{$data->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-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}}" {!! isset($account->first_account_address->country_id)  && $account->first_account_address->country_id == $list->id ? 'selected' : '' !!}>{{$list->name}}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">State</label>
                                        <input type="hidden" value="{{ $account->first_account_address->state_id ?? '' }}" id="stateid">
                                        <select class="form-control" name="state_id" id="states">
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">City</label>
                                        <input type="hidden" value="{{ $account->first_account_address->city_id ?? '' }}" name="cityid">
                                        <select class="form-control" name="city_id" id="cities">
                                        </select>
                                    </div>

                                      <!-- about-->
                                      <div class="col-md-12">
                                        <div>
                                            <label for="about" class="form-label">About </label>
                                        </div>
                                        <div class="input-group">
                                            <textarea class="form-textarea" placeholder="About" name="about" rows="4" cols="4">{{$data->about}}</textarea>
                                        </div>
                                        @if ($errors->has('about'))
                                            <span class="text-danger">{{ $errors->first('about') }}</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 Employee 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">
                                    <!--Marital Status -->
                                    <div class="col-md-6">
                                        <label class="form-label">Marital Status</label>
                                        <select class="form-control" id="marital_status_id" name="marital_status_id">
                                            <option value=" ">--Select-- </option>
                                            @foreach($maritalStatus as $list)
                                            <option value="{{ $list->id }}" {{ $list->id == $data->marital_status_id ? 'selected':'' }}>{{ $list->name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <!-- Hourly Rate -->
                                    <div class="col-md-6">
                                        <label class="form-label">Hourly Rate</label>
                                        <div class="input-group">
                                            <div class="input-group-prepend">
                                              <span style="height:40px" class="input-group-text" id="basic-addon1">$</span>
                                            </div>
                                            <input type="number" class="form-control" placeholder="Hourly Rate" name="hourly_rate" value="{{$data->hourly_rate}}">
                                            <span class="input-group-text">.00</span>
                                        </div>
                                    </div>
                                    <!-- -->
                                    <!-- Login Allowed -->
                                    <div class="col-md-6">
                                        <label class="form-label mb-2">Login Allowed</label>
                                        <div class="form-group">
                                            <label>
                                              <input type="radio" name="login_allowed" value="yes"> Yes
                                            </label>
                                            <label class="ml-3">
                                              <input type="radio" name="login_allowed" value="no"> No
                                            </label>
                                          </div>
                                    </div>
                                    <!-- Receive email notifications -->
                                    <div class="col-md-6">
                                        <label class="form-label mb-2">Receive email notifications</label>
                                        <div class="form-group">
                                            <label>
                                              <input type="radio" name="recieve_email_notifications" value="yes"> Yes
                                            </label>
                                            <label class="ml-3">
                                              <input type="radio" name="recieve_email_notifications" value="no"> No
                                            </label>
                                        </div>
                                    </div>
                                      <!-- Skills -->
                                      <div class="col-md-12">
                                        <label class="form-label">Skills</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" placeholder="Skills" name="skills" value="{{$data->skills}}">
                                        </div>
                                    </div>
                                    <!-- Probation End Date-->
                                    <div class="col-md-6">
                                        <div>
                                            <label for="probation_end_date" class="form-label"> Probation End Date </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="" name="probation_end_date" class="form-control" id="probation_end_date" placeholder="Probation End Date" autocomplete="off" readonly style="cursor: pointer;" value="{{$data->probation_end_date}}">
                                        </div>
                                        @if ($errors->has('probation_end_date'))
                                            <span class="text-danger">{{ $errors->first('probation_end_date') }}</span>
                                        @endif
                                    </div>
                                    <!-- Notice Period Start Date-->
                                    <div class="col-md-6">
                                        <div>
                                            <label for="notice_period_start_date" class="form-label"> Notice Period Start Date </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="" name="notice_period_start_date" class="form-control" id="notice_period_start_date" placeholder="Notice Period Start Date" autocomplete="off" readonly style="cursor: pointer;" value="{{$data->notice_period_start_date}}">
                                        </div>
                                        @if ($errors->has('notice_period_start_date'))
                                            <span class="text-danger">{{ $errors->first('notice_period_start_date') }}</span>
                                        @endif
                                    </div>
                                    <!-- Notice Period End Date-->
                                    <div class="col-md-6">
                                        <div>
                                            <label for="notice_period_end_date" class="form-label"> Notice Period End Date </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="" name="notice_period_end_date" class="form-control" id="notice_period_end_date" placeholder="Notice Period End Date" autocomplete="off" readonly style="cursor: pointer;" value="{{$data->notice_period_end_date}}">
                                        </div>
                                        @if ($errors->has('notice_period_end_date'))
                                            <span class="text-danger">{{ $errors->first('notice_period_end_date') }}</span>
                                        @endif
                                    </div>
                                      


                                    <!-- joining date-->
                                    <div class="col-md-6"><div>
                                        <label for="joining_date" class="form-label"> Joining Date </label>
                                    </div>
                                    <div class="input-group">
                                        <input type="text" name="joining_date" class="form-control" id="joining_date" placeholder="Joining Date" autocomplete="off" readonly style="cursor: pointer;" value="{{$data->joining_date}}">
                                    </div>
                                    @if ($errors->has('joining_date'))
                                        <span class="text-danger">{{ $errors->first('joining_date') }}</span>
                                    @endif
                                    </div>

                                    <!-- Date Of Birth-->
                                    <div class="col-md-6">
                                    <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" placeholder="Date Of Birth" readonly style="cursor: pointer;" value="{{$data->date_of_birth}}">
                                    </div>
                                    @if ($errors->has('date_of_birth'))
                                        <span class="text-danger">{{ $errors->first('date_of_birth') }}</span>
                                    @endif
                                    </div>

                                    <!-- Employment Type-->
                                      <div class="col-md-6">
                                        <div>
                                            <label for="employee_type_id" class="form-label">Employee Type </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control employee_type_id" name="employee_type_id">
                                                <option value="">-- Select --</option>
                                                @foreach($employeeType as $list)
                                                <option value="{{ $list->id }}" {{ $list->id == $data->employee_type_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_account_type" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                            </div> --}}
                                        </div>
                                        @if ($errors->has('employee_type_id'))
                                            <span class="text-danger">{{ $errors->first('employee_type_id') }}</span>
                                        @endif
                                    </div>


                                    <!-- report To-->
                                    <div class="col-md-6">
                                        <div>
                                            <label for="reporting_to" class="form-label">Reporting To </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control reporting_to" name="reporting_to">
                                                <option value="">-- Select --</option>
                                                @foreach($reportTo as $list)
                                                <option value="{{ $list->id }}" {{ $list->id == $data->reporting_to ? 'selected':'' }}>{{ $list->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('reporting_to'))
                                            <span class="text-danger">{{ $errors->first('reporting_to') }}</span>
                                        @endif
                                        <span class="text-danger error_reporting_to" style="display:none;">This field is required.</span>
                                    </div>

                                      <!-- address-->
                                    <div class="col-md-6">
                                        <div>
                                            <label for="address" class="form-label">Employee Address </label>
                                        </div>
                                        <div class="input-group">
                                            <textarea class="form-textarea" name="address" rows="1">{{ $data->address }}</textarea>
                                        </div>
                                        @if ($errors->has('address'))
                                            <span class="text-danger">{{ $errors->first('address') }}</span>
                                        @endif
                                        <span class="text-danger error_address" style="display:none;">This field is required.</span>
                                    </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>
    $( function() {
        $('#date_of_birth').datepicker();
    });
    $( function() {
        $('#joining_date').datepicker();
    });
    $( function() {
        $('#probation_end_date').datepicker();
    });
    $( function() {
        $('#notice_period_start_date').datepicker();
    });
    $( function() {
        $('#notice_period_end_date').datepicker();
    });

    var telInput = $('#phone_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
    });

    $("#phone_no").on('input', function() {
        const onlyNumbers = allNumeric($(this).val());
        $("#phone_no").val(onlyNumbers);
    });
    function allNumeric(inputtxt) {
        onlyNumbers = inputtxt.replace(/[^0-9]/g, '');
        if (onlyNumbers.length > 16) {
            onlyNumbers = onlyNumbers.substring(0, 16);
        }
        return onlyNumbers;
    }
    $("[name='opening_balance']").on('input', function() {
        const onlyNumbers = allNumericDecimal($(this).val());
        $("[name='opening_balance']").val(onlyNumbers);
    });
    function allNumericDecimal(inputtxt) {
        onlyNumbers = inputtxt.replace(/[^0-9.]/g, '');
        return onlyNumbers;
    }

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

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

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

        $('.error_name').hide();
        $('.error_email').hide();
        $('.error_phone').hide();
        $('.error_designation_id').hide();
        $('.error_department_id').hide();
        $('.error_gender_id').hide();
        $('.error_reporting_to').hide();
        $('.error_language_id').hide();
        $('.error_title_id').hide();

        var error = 0;

        if ($('input[name="name"]').val().trim() == '') {
          $('.error_name').show();
          error = 1;
        }
        if ($('[name="email"]').val() == '' || $('[name="email"]').val() == null) {
          $('.error_email').show();
          error = 1;
        }
        if ($('[name="designation_id"]').val() == '' || $('[name="designation_id"]').val() == null) {
          $('.error_designation_id').show();
          error = 1;
        }
        if ($('[name="department_id"]').val() == '' || $('[name="department_id"]').val() == null) {
          $('.error_department_id').show();
          error = 1;
        }
        if ($('[name="gender_id"]').val() == '' || $('[name="gender_id"]').val() == null) {
          $('.error_gender_id').show();
          error = 1;
        }
        if ($('[name="reporting_to"]').val() == '' || $('[name="reporting_to"]').val() == null) {
          $('.error_reporting_to').show();
          error = 1;
        }
        if ($('[name="language_id"]').val() == '' || $('[name="language_id"]').val() == null) {
          $('.error_language_id').show();
          error = 1;
        }
        if ($('[name="title_id"]').val() == '' || $('[name="title_id"]').val() == null) {
          $('.error_title_id').show();
          error = 1;
        }
        if ($('[name="country_id"]').val() == '') {
          $('.error_country_id').show();
          error = 1;
        }
        if ($('input[name="phone_no"]').val() == '') {

          $('.error_phone').show();
          error = 1;
        }


        if (error == 0) {

            let formdata = new FormData($('#update_employee')[0]);

            $.ajax({
                url: "{{ route('employee.update', $data->id) }}",
                data: formdata,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function(response) {
                    if (response.success === true) {
                        toastr.success(response.message, 'Success.');
                        window.location.href = "{{ route('employee.index') }}";
                    } 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();
            // hide
            $('input[name="opening_balance"]').closest('.col-md-6').hide();
            $('select[name="balance_type"]').closest('.col-md-6').hide();
            $('select[name="settlement_type"]').closest('.col-md-6').hide();
            $('select[name="tax_register_category_id"]').closest('.col-md-6').hide();
            $('select[name="accounting_group_id"]').closest('.col-md-12').hide();
        } else {
            // hide
            $('.unique_no').hide();
            $('.house_id').hide();
            // show
            $('input[name="opening_balance"]').closest('.col-md-6').show();
            $('select[name="balance_type"]').closest('.col-md-6').show();
            $('select[name="settlement_type"]').closest('.col-md-6').show();
            $('select[name="tax_register_category_id"]').closest('.col-md-6').show();
            $('select[name="accounting_group_id"]').closest('.col-md-12').show();
        }
        // End

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

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

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

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

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

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

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

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

        console.log('sss');
        $.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', '.save_button', function(event) {
            event.preventDefault();
            var error = 0;
            if ($('#commonModal').find('form').hasClass('designation')) {
                $('.error_name').hide();
                if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
                    $('.error_name').show();
                    error = 1;
                }

                if (error == 0) {
                    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.');
                                    $('[name="opd_schedule_types_id"]').append(
                                        `<option value="${response.data.id}" selected>${response.data.name}</option>`
                                        );
                                    $('[name="opd_schedule_types_id"]').trigger('change');

                                    // hide modal
                                    $('#commonModal').modal('hide');
                                    $('#commonModal').find('.modal-body').html('');
                                    setTimeout(function() {
                                        //  alert('test');
                                        $('#create').trigger('click');
                                    }, 1000);
                                } 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('orgazination_department')) {
                $('.error_name').hide();
                if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
                    $('.error_name').show();
                    error = 1;
                }

                if (error == 0) {
                    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.');
                                    $('[name="organization_department_id"]').append(
                                        `<option value="${response.data.id}" selected>${response.data.name}</option>`
                                        );
                                    $('[name="organization_department_id"]').trigger('change');
                                    // hide modal
                                    $('#commonModal').modal('hide');
                                    $('#commonModal').find('.modal-body').html('');
                                    setTimeout(function() {
                                        //  alert('test');
                                        $('#create').trigger('click');
                                    }, 1000);
                                } 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('');
                        });
                }

            }

        })
</script>
@endsection
