<div>
    <input type="text" id="employee-search" value="{{ $employee_name ?? '' }}" class="form-control"
    placeholder="Search by Employee Code or Mobile" {{$required ?? ""}}>
    <input type="hidden" id="employee-search-value" name="employee_code" value="{{ $employee_code ?? '' }}">
</div>

@push('scripts')
<script>
$(document).ready(function() {
    $("#employee-search").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "{{ route('employees.search') }}",
                data: {
                    query: request.term
                },
                success: function(data) {
                    response($.map(data, function(employee) {
                        if (/^0/.test(request.term)) { // Check if mobile number starts with 0

                            return {
                                label: `${employee.first_name} ${employee.last_name} (${employee.mobile_number})`,
                                value: employee.employee_code
                            };
                        } else { // Otherwise, assume it's an ID starting with 1-9

                            return {
                                label: `${employee.first_name} ${employee.last_name} (${employee.employee_code})`,
                                value: employee.employee_code
                            };
                        }
                    }));
                }
            });
        },
        minLength: 3,
        select: function(event, ui) {
            $('#employee-search').val(ui.item.label);
            $('#employee-search-value').val(ui.item.value);
            return false;
        },
        focus: function(event, ui) {
            $('#employee-search').val(ui.item.label);
            return false;
        }
    });

    $("#employee-search").on('input', function() {
        if ($(this).val() === '') {
            $('#employee-search-value').val('');
        }
    });
});
</script>
@endpush
