@if ($delivery_types ?? false)
    <table class="">
        <thead>
            <tr>
                <th colspan="3">
                    Choix du transporteur
                </th>
            </tr>
        </thead>
        @php
            $deliveryTypes = collect($delivery_types);
            $preselectedDeliveryTypeId = old('delivery_type_id');

            if ($preselectedDeliveryTypeId === null || $preselectedDeliveryTypeId === '') {
                $preselectedDeliveryTypeId = $deliveryTypes->keys()->first();
            }

            $deliveryTypes = $deliveryTypes->all();
        @endphp

        @foreach ($deliveryTypes as $delivery_type_id => $delivery_type)
            <tr>
                <td>
                    @include('components.form.radios.icheck', [
                        'name' => 'delivery_type_id',
                        'val' => $delivery_type_id,
                        'id' => 'delivery_type_' . $delivery_type_id,
                        'class' => 'delivery_type',
                        'value' => $preselectedDeliveryTypeId,
                    ])
                </td>
                <td>
                    {{ $delivery_type['name'] }}
                </td>
                <td class="text-right">
                    {{ $delivery_type['price'] }} €
                </td>
            </tr>
        @endforeach
    </table>
@endif

@push('js')
    <script>
        function handleDeliveryTypes() {
            var $deliveryTypeInputs = $('input.delivery_type');

            $deliveryTypeInputs.change(function() {
                var deliveryTypeId = $(this).val();
                var deliveryId = $('input[name=delivery_id]:checked').val()
                refreshBasketTotal(deliveryId, deliveryTypeId);
            });

            var $preselected = $deliveryTypeInputs.filter(':checked').first();

            if ($preselected.length) {
                $preselected.trigger('change');
            }
        }
        handleDeliveryTypes();
    </script>
@endpush
