<style type="text/css">
    .select2-container {
        z-index: 1100;
    }
</style>
<form class="row g-3 auto-width consultant" action="{{ route('ipd-admission-consultants.store', $ipd_id) }}" method="post" id="add_consultant">
    @csrf
    <div class="col-md-12">
        <div>
            <label class="form-label">Consultant Doctor <span class="text-danger"><b>*</b></span></label>
        </div>
        <div class="input-group autocomplete">
            <select class="form-control doctor-select multi-select-consultant" id="doctor_id" name="doctor_id[]" multiple="multiple">
            </select>
        </div>
        <span class="text-danger error_doctor_id" style="display:none;">This field is required.</span>
    </div>
</form>

<script type="text/javascript">
    $('.multi-select-consultant').select2({
        theme: 'bootstrap4',
        placeholder: "Search Consultant",
    });

    $(".doctor-select").select2({
        ajax: {
            url: '{{ route('billings-search-doctors') }}',
            type: 'POST',
            dataType: 'json',
            data: function (params) {
                return {
                    search_text: params.term
                };
            },
            processResults: function (data) {
                if (data.error) {
                    $('[name="doctor_id"]').val('');
                    return { results: [] };
                }

                return {
                    results: $.map(data.result, function (item) {
                        var age = item.date_of_birth != null ? ', ' + getAge(item.date_of_birth) + ' yrs' : '';
                        var gender = item.gender != null ? ', ' + item.gender : '';
                        var phone_no = item.phone_no != null ? ', ' + item.phone_no : '';

                        return {
                            id: item.id,
                            text: item.name + gender + age + phone_no
                        };
                    })
                };
            }
        },
        minimumInputLength: 2,
        templateSelection: function (selectedData) {
            return selectedData.text;
        }
    });
</script>