@extends('themes.classic.layouts.app')

@section('title', 'Commander - '.($site_name ?? 'Mon Site'))

@section('content')
<div class="max-w-2xl mx-auto px-6 py-16">
    <h1 class="text-3xl font-bold text-slate-900 mb-8">Finaliser la commande</h1>

    <div class="mb-8 p-6 bg-slate-50 rounded-2xl">
        <h3 class="font-semibold text-slate-800 mb-4">Récapitulatif</h3>
        @foreach($items as $item)
        <div class="flex justify-between py-2">
            <span>{{ $item['product']->name }} × {{ $item['qty'] }}</span>
            <span class="font-medium">{{ number_format($item['product']->price * $item['qty'], 2, ',', ' ') }} €</span>
        </div>
        @endforeach
        <div class="flex justify-between pt-4 mt-4 border-t border-slate-200">
            <span>Sous-total</span>
            <span>{{ number_format($subtotal, 2, ',', ' ') }} €</span>
        </div>
        @if(($discount ?? 0) > 0)
        <div class="flex justify-between py-2 text-emerald-600">
            <span>Réduction @if($appliedCoupon ?? null)({{ $appliedCoupon['code'] }})@endif</span>
            <span class="font-medium">−{{ number_format($discount ?? 0, 2, ',', ' ') }} €</span>
        </div>
        <div class="flex justify-between py-2 font-medium">
            <span>Sous-total après réduction</span>
            <span>{{ number_format($subtotalAfterDiscount ?? $subtotal, 2, ',', ' ') }} €</span>
        </div>
        @endif
        <p class="text-sm text-slate-500 mt-2">Les frais de livraison seront calculés selon votre choix ci-dessous.</p>
    </div>

    <form method="POST" action="{{ route('ecommerce.place-order') }}" id="checkout-form" class="space-y-6">
        @csrf

        <div class="space-y-4">
            <label class="block text-sm font-medium text-slate-700">Coordonnées *</label>
            <input type="text" name="customer_name" value="{{ old('customer_name') }}" required placeholder="Nom complet" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-primary-500">
            <input type="email" name="customer_email" value="{{ old('customer_email') }}" required placeholder="Email" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-primary-500">
            <input type="tel" name="customer_phone" value="{{ old('customer_phone') }}" placeholder="Téléphone" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-primary-500">
        </div>

        <div>
            <label class="block text-sm font-medium text-slate-700 mb-2">Adresse de livraison *</label>
            <textarea name="customer_address" rows="2" required placeholder="Adresse complète" class="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-primary-500">{{ old('customer_address') }}</textarea>
            <div class="grid grid-cols-2 gap-4 mt-2">
                <input type="text" name="customer_postal_code" value="{{ old('customer_postal_code') }}" placeholder="Code postal" class="px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-primary-500">
                <input type="text" name="customer_city" value="{{ old('customer_city') }}" placeholder="Ville" class="px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-primary-500">
            </div>
            <input type="hidden" name="customer_country" value="FR">
        </div>

        <div>
            <label class="block text-sm font-medium text-slate-700 mb-2">Mode de livraison *</label>
            <div class="space-y-3">
                @foreach($shippingMethods as $sm)
                <label class="flex items-start gap-3 p-4 border border-slate-200 rounded-xl cursor-pointer hover:border-primary-300 has-[:checked]:border-primary-500 has-[:checked]:bg-primary-50/30">
                    <input type="radio" name="shipping_method_id" value="{{ $sm->id }}" required
                        data-price="{{ $sm->calculateCost($subtotalAfterDiscount ?? $subtotal, $totalWeight ?? 0) }}"
                        data-mondial="{{ $sm->isMondialRelay() ? '1' : '0' }}"
                        class="mt-1 rounded border-slate-300 text-primary-500 focus:ring-primary-500">
                    <div class="flex-1">
                        <span class="font-medium">{{ $sm->name }}</span>
                        @php $cost = $sm->calculateCost($subtotalAfterDiscount ?? $subtotal, $totalWeight ?? 0); @endphp
                        <span class="text-primary-600 font-semibold ml-2">
                            @if($cost == 0)Gratuit@else{{ number_format($cost, 2, ',', ' ') }} €@endif
                        </span>
                        @if($sm->free_from && ($subtotalAfterDiscount ?? $subtotal) < $sm->free_from)
                        <p class="text-xs text-slate-500 mt-0.5">Gratuit à partir de {{ number_format($sm->free_from, 2, ',', ' ') }} €</p>
                        @endif
                        @if($sm->isMondialRelay())
                        <p class="text-xs text-emerald-600 mt-1">→ Choisissez votre point relais ci-dessous</p>
                        @else
                        <p class="text-xs text-slate-500 mt-1">Livraison à l'adresse indiquée</p>
                        @endif
                    </div>
                </label>
                @endforeach
            </div>
        </div>

        <div id="mondial-relay-block" class="hidden p-4 bg-slate-50 border border-slate-200 rounded-xl">
            <p class="text-sm font-medium text-slate-800 mb-3">Choisissez votre point relais Mondial Relay</p>
            <p class="text-xs text-slate-500 mb-3">Entrez votre code postal pour trouver les points relais à proximité.</p>
            <div id="mondial-relay-widget" class="min-h-[300px]"></div>
            <input type="hidden" name="shipping_relay_id" id="shipping_relay_id" value="">
            <input type="hidden" name="shipping_relay_label" id="shipping_relay_label" value="">
            <div id="mondial-relay-selected" class="mt-3 p-3 bg-emerald-50 border border-emerald-200 rounded-lg text-sm text-emerald-800 hidden"></div>
        </div>

        <div>
            <label class="block text-sm font-medium text-slate-700 mb-1">Notes</label>
            <textarea name="notes" rows="2" placeholder="Instructions spéciales..." class="w-full px-4 py-2.5 border border-slate-200 rounded-xl focus:ring-2 focus:ring-primary-500">{{ old('notes') }}</textarea>
        </div>

        <div class="p-4 bg-slate-100 rounded-xl">
            <div class="flex justify-between text-lg font-bold">
                <span>Total estimé</span>
                <span id="total-display">{{ number_format($subtotalAfterDiscount ?? $subtotal, 2, ',', ' ') }} €</span>
            </div>
        </div>

        @if($stripeConfigured)
        <p class="text-sm text-slate-500">Paiement sécurisé par Stripe (carte bancaire).</p>
        @else
        <p class="text-sm text-slate-500">Mode démo : la commande sera enregistrée sans paiement en ligne.</p>
        @endif

        @include('partials.captcha-widget', ['context' => 'checkout'])

        <button type="submit" class="w-full py-4 bg-primary-500 text-white rounded-xl font-semibold hover:bg-primary-600 transition">Confirmer et payer</button>
    </form>

    <p class="mt-6"><a href="{{ route('ecommerce.cart') }}" class="text-slate-500 hover:text-slate-900">← Retour au panier</a></p>
</div>

@push('scripts')
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" crossorigin="">
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" crossorigin=""></script>
<script src="https://widget.mondialrelay.com/parcelshop-picker/jquery.plugin.mondialrelay.parcelshoppicker.min.js"></script>
<script>
document.querySelectorAll('input[name="shipping_method_id"]').forEach(r => {
    r.addEventListener('change', function() {
        const mondial = this.dataset.mondial === '1';
        const block = document.getElementById('mondial-relay-block');
        block.classList.toggle('hidden', !mondial);
        if (mondial && typeof jQuery !== 'undefined' && jQuery('#mondial-relay-widget').data('MR_ParcelShopPicker')) {
            jQuery('#mondial-relay-widget').trigger('MR_RebindMap');
        }
        updateTotal();
    });
});
function updateTotal() {
    const r = document.querySelector('input[name="shipping_method_id"]:checked');
    const sub = {{ $subtotalAfterDiscount ?? $subtotal }};
    const ship = r ? parseFloat(r.dataset.price || 0) : 0;
    document.getElementById('total-display').textContent = (sub + ship).toFixed(2).replace('.', ',') + ' €';
}
jQuery(document).ready(function() {
    const enseigne = "{{ addslashes($mondialRelayEnseigne ?? 'BDTEST') }}";
    if (enseigne && jQuery('#mondial-relay-widget').length) {
        jQuery('#mondial-relay-widget').MR_ParcelShopPicker({
            Target: '#shipping_relay_id',
            TargetDisplayInfoPR: '#shipping_relay_label',
            Brand: enseigne.padEnd(8, ' '),
            Country: 'FR',
            PostCode: document.querySelector('input[name="customer_postal_code"]')?.value || '',
            Responsive: true,
            ShowResultsOnMap: true,
            Theme: 'mondialrelay',
            OnParcelShopSelected: function(data) {
                const label = (data.Nom || '') + ', ' + (data.Adresse1 || '') + (data.Adresse2 ? ' ' + data.Adresse2 : '') + ', ' + (data.CP || '') + ' ' + (data.Ville || '');
                document.getElementById('shipping_relay_label').value = label;
                document.getElementById('mondial-relay-selected').classList.remove('hidden');
                document.getElementById('mondial-relay-selected').innerHTML = '<strong>Point relais sélectionné :</strong> ' + label;
            }
        });
    }
});
</script>
@endpush
@endsection
