{{ Form::open(['route' => 'Admin.Shop.Offers.store', 'id' => 'offer-form', 'autocomplete' => 'off']) }}
<input type="hidden" name="id" value="{{ $offer['id'] ?? false }}">

@if (($offer['id'] ?? false) && ($offer['article_id'] ?? false))
    <div class="d-flex justify-content-end mb-3">
        <a href="{{ route('Shop.Articles.show', ['id' => $offer['article_id']]) }}" class="btn btn-outline-primary" target="_blank" rel="noopener">
            Voir la page publique de l'article
            <i class="fa fa-external-link"></i>
        </a>
    </div>
@endif

<div class="row mb-3">
    <div class="col-12">
        <div class="row mb-3">
            <div class="col-12">
                <div class="d-flex align-items-end">
                    <div class="flex-grow-1">
                        @include('components.form.select', [
                            'name' => 'article_id',
                            'id_name' => 'article_id',
                            'list' => $articles ?? null,
                            'value' => $offer['article_id'] ?? null,
                            'with_empty' => '',
                            'class' => 'select2 select_article',
                            'label' => 'Article',
                            'required' => true,
                        ])
                    </div>
                    <a id="edit-article-link" href="#" class="btn btn-sm btn-outline-secondary ml-2 mb-1" title="Modifier l'article" style="display:none;">
                        <i class="fa fa-external-link"></i>
                    </a>
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <div class="col-4">
                <div class="d-flex align-items-end">
                    <div class="flex-grow-1">
                        @include('components.form.select', [
                            'name' => 'variation_id',
                            'id_name' => 'variation_id',
                            'list' => $variations ?? null,
                            'value' => $offer['variation_id'] ?? null,
                            'with_empty' => '',
                            'class' => 'select2 select_variation',
                            'label' => __('shop.packages.name'),
                            'required' => true,
                        ])
                    </div>
                    <a id="edit-variation-link" href="#" class="btn btn-sm btn-outline-secondary ml-2 mb-1" title="Modifier la déclinaison" style="display:none;">
                        <i class="fa fa-external-link"></i>
                    </a>
                </div>
            </div>
            <div class="col-4">
                <div class="d-flex align-items-end">
                    <div class="flex-grow-1">
                        @include('components.form.select', [
                            'name' => 'tariff_id',
                            'id_name' => 'tariff_id',
                            'list' => $tariffs ?? null,
                            'value' => $offer['tariff_id'] ?? null,
                            'with_empty' => '',
                            'class' => 'select2 select_tariffs',
                            'label' => 'Tarif',
                            'required' => true,
                        ])
                    </div>
                    <a id="edit-tariff-link" href="#" class="btn btn-sm btn-outline-secondary ml-2 mb-1" title="Modifier le tarif" style="display:none;">
                        <i class="fa fa-external-link"></i>
                    </a>
                </div>
            </div>
            <div class="col-2">
                @include('components.form.input', [
                    'name' => 'weight',
                    'value' => $offer['weight'] ?? null,
                    'label' => 'Poids en g',
                    'required' => true,
                ])
            </div>
            <div class="col-2">
                <input type="hidden" name="status_id" value="0">
                @include('components.form.toggle', [
                    'name' => 'status_id',
                    'value' => $offer['status_id'] ?? 0,
                    'label' => 'Actif',
                    'size' => 'md',
                ])
            </div>
        </div>

        @component('components.card', ['title' => 'Disponibilité', 'class' => 'mt-5'])
            <div class="row mb-3 mt-3">
                <div class="col-4">
                    @include('components.form.inputs.money', [
                        'name' => 'stock_current',
                        'value' => $offer['stock_current'] ?? 0,
                        'label' => 'Appro immédiate',
                    ])
                </div>
                <div class="col-4">
                    @include('components.form.inputs.money', [
                        'name' => 'stock_delayed',
                        'value' => $offer['stock_delayed'] ?? 0,
                        'label' => 'Appro sur delai',
                    ])
                </div>
                <div class="col-4">
                    @include('components.form.input', [
                        'name' => 'delay_type',
                        'value' => $offer['delay_type'] ?? null,
                        'label' => 'Délai type',
                    ])
                </div>
            </div>
            <div class="row mb-3">
                <div class="col-6">
                    @include('components.form.toggle', [
                        'name' => 'stock_ondemand',
                        'value' => $offer['stock_ondemand'] ?? 0,
                        'label' => 'Appro sur demande',
                        'size' => 'md',
                    ])
                </div>
                <div class="col-6">
                    @include('components.form.inputs.money', [
                        'name' => 'minimum_ondemand',
                        'value' => $offer['minimum_ondemand'] ?? 0,
                        'label' => 'Minimum de quantité',
                    ])
                </div>
            </div>
        @endcomponent
    </div>

</div>

{{ form::close() }}
<x-save />

@include('load.layout.chevron')
@include('load.form.save')
@include('load.form.select2')

@push('js')
    {!! JsValidator::formRequest('App\Http\Requests\Admin\Shop\StoreOfferPost', '#offer-form') !!}

    <script>
        initChevron();
        initSaveForm('#offer-form');
        initSelect2();
        $('#status_id').bootstrapToggle();

        // Article visibility badges in select2
        var articleVisibilities = {!! json_encode($article_visibilities ?? (object)[]) !!};

        function formatArticle(item) {
            if (!item.id) return item.text;
            var visible = articleVisibilities[item.id];
            var badge = (visible == 1)
                ? '<span class="badge badge-success" style="font-size:0.75em;margin-left:4px;">Visible</span>'
                : '<span class="badge badge-warning" style="font-size:0.75em;margin-left:4px;">Invisible</span>';
            return $('<span style="display:flex;justify-content:space-between;align-items:center;width:100%;">' + item.text + badge + '</span>');
        }

        $('#article_id').select2('destroy').select2({
            placeholder: "{{ __('select_a_value') }}",
            allowClear: false,
            width: { value: '100%' },
            templateResult: formatArticle,
            templateSelection: formatArticle
        });

        // Tariff status badges in select2
        var tariffStatuses = {!! json_encode($tariff_statuses ?? (object)[]) !!};
        var tariffStatusLabels = {!! json_encode($tariff_status_labels ?? []) !!};
        var tariffStatusColors = {0: '#28a745', 1: '#ffc107', 2: '#6c757d', 3: '#dc3545'};
        var tariffPLCounts = {!! json_encode($tariff_pricelist_counts ?? (object)[]) !!};

        function formatTariff(item) {
            if (!item.id) return item.text;
            var statusId = tariffStatuses[item.id];
            var color = tariffStatusColors[statusId] || '#6c757d';
            var label = tariffStatusLabels[statusId] || '';
            var plCount = tariffPLCounts[item.id] || 0;
            var warning = plCount == 0 ? '<span style="margin-left:4px;cursor:help;" title="Aucune liste de prix"><i class="fas fa-exclamation-triangle text-danger" style="font-size:1.4em;vertical-align:-2px;"></i></span>' : '';
            return $('<span style="display:flex;justify-content:space-between;align-items:center;width:100%;">' + item.text + '<span>' + warning + '<span class="badge" style="background:' + color + ';color:#fff;font-size:0.75em;margin-left:4px;">' + label + '</span></span></span>');
        }

        $('#tariff_id').select2('destroy').select2({
            placeholder: "{{ __('select_a_value') }}",
            allowClear: false,
            width: { value: '100%' },
            templateResult: formatTariff,
            templateSelection: formatTariff
        });

        function updateEditLink(selectId, linkId, routeTemplate) {
            var val = $('#' + selectId).val();
            var $link = $('#' + linkId);
            if (val) {
                $link.attr('href', routeTemplate.replace('__ID__', val)).show();
            } else {
                $link.hide();
            }
        }

        var articleRoute = '{{ route('Admin.Shop.Articles.edit', ['id' => '__ID__']) }}';
        var variationRoute = '{{ route('Admin.Shop.Variations.edit', ['id' => '__ID__']) }}';
        var tariffRoute = '{{ route('Admin.Shop.Tariffs.edit', ['id' => '__ID__']) }}';

        // Init on page load
        updateEditLink('article_id', 'edit-article-link', articleRoute);
        updateEditLink('variation_id', 'edit-variation-link', variationRoute);
        updateEditLink('tariff_id', 'edit-tariff-link', tariffRoute);

        // Update on change
        $('#article_id').on('change', function() {
            updateEditLink('article_id', 'edit-article-link', articleRoute);
        });
        $('#variation_id').on('change', function() {
            updateEditLink('variation_id', 'edit-variation-link', variationRoute);
        });
        $('#tariff_id').on('change', function() {
            updateEditLink('tariff_id', 'edit-tariff-link', tariffRoute);
        });
    </script>
@endpush
