<form action="{{ route('admin.access.employees.update-role', $user->id) }}" method="post">
    @csrf
    <div class="form-group">
        <label>@lang('Role')</label>
        <select class="form-control select2-multiple" style="width: 100%" name="roles[]" required multiple>
            @foreach ($roles as $role)
                <option value="{{ $role->id }}"
                    {{ isset($user) && in_array($role->id, $userRoles) ? 'selected' : '' }}>{{ $role->name }}
                </option>
            @endforeach
        </select>
    </div>

    <div class="form-group">
        <button type="submit" class="btn btn--primary w-100">@lang('Submit')</button>
    </div>
</form>

<script>
    $(document).ready(function() {
        $('.select2-multiple').select2({
            placeholder: 'Select an option',
            allowClear: true,
            width: '100%'
        });

        $('#userRole').select2({
            ajax: {
                url: '{{ route('admin.users.referedPerson.suggestions') }}',
                type: 'GET',
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        search: params.term
                    };
                },
                processResults: function(data) {
                    return {
                        results: data
                    };
                },
                cache: true
            },
            placeholder: 'Search for a user',
            minimumInputLength: 2,
            templateResult: formatResult,
            templateSelection: formatSelection
        });

        function formatResult(data) {
            if (data.loading) return data.text;
            return data.text;
        }

        function formatSelection(data) {
            return data.text;
        }

        $(document).on('select2:open', function() {
            $('.select2-dropdown').on('click', function(e) {
                e.stopPropagation();
            });
        });
    });
</script>
