<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">
    @csrf
    @method('post')
    <div class="col-md-12" id="test_items">
        <label for="product_id" class="form-label">Product Name <span class="text-danger"><b>*</b></span></label>

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

    <table id="selectedTable">
        {{-- <thead>
            <tr>
                <th style="width: 15%;">Sl No</th>
                <th>module </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 Modules",
    width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
    allowClear: Boolean($(this).data('allow-clear')),
});
</script>

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

        var ids = [];
        selectedOptions.forEach(function(option, index) {
            var optionValue = $(option).val();
            var optionText = $(option).text();
            ids.push(optionValue);
        });

        url = "{{ route('plan-product-mapping.selected') }}"

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

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