<style type="text/css">
    table {
      font-family: arial, sans-serif;
      border-collapse: collapse;
      width: 50%;
    }

    td, th {
      border: 1px solid #dddddd;
      text-align: left;
      padding: 10px;
    }

    .select2-selection__choice {
        display: none;
    }
</style>
<form class="row g-3 auto-width form" method="post" id="form_data" action="{{ route('product-test-packages.store') }}">
    @csrf
    @method('post')
    <div class="col-md-12" id="test_items">
        <label for="name" class="form-label">Test Name <span class="text-danger"><b>*</b></span></label>

        <div class="input-group">
            <select id="test_item_id" class="multi-select-tests test_item_id" multiple name="test_item_id[]">
                @foreach ($tests as $test)
                    <option value="{{ $test->id }}">{{ $test->name }}</option>
                @endforeach
            </select>
            <input type="hidden" name="product_id">
        </div>
        <span class="text-danger error_test_name" style="display:none;">This field is required.</span>
    </div>

    <table id="selectedTable">
        <thead>
            <tr>
                <th style="width: 15%;">Sl No</th>
                <th>Test Items</th>
                <th style="width: 15%;">Remove</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td style="text-align: center;" colspan="4">Items not selected</td>
            </tr>
        </tbody>
    </table>
</form>

<script type="text/javascript">
$('.multi-select-tests').select2({
    theme: 'bootstrap4',
    dropdownParent: $("#test_items"),
    placeholder: "Select Test Items",
    width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
    allowClear: Boolean($(this).data('allow-clear')),
});
</script>

<script>
$(document).ready(function() {
    $("#test_item_id").on("change", function() {
        var selectedOptions = $("#test_item_id option:selected").toArray();
        var tableBody = $("#selectedTable tbody").empty();

        var ids = [];
        selectedOptions.forEach(function(option, index) {
            var optionValue = $(option).val();
            var optionText = $(option).text();
            ids.push(optionValue);
        });
        
        url = "{{ route('selected-test-packages') }}" 

        $.ajax({
            url:url,
            type:'GET',
            data:{id:ids},
            success: function(response){
                $("#selectedTable tbody").append(response);
            },
        });

        $(document).on("click", '.remove-btn', function() {
            var optionValue = $(this).data("value");
            $("#test_item_id option[value='" + optionValue + "']").prop("selected", false);
            $(this).closest("tr").remove();
        });
    });
});
</script>