{# templates/vendor/shipping/methods.html.twig #}
{% extends 'base.html.twig' %}

{% block title %}Gestion des livraisons - Espace Vendeur{% endblock %}

{% block body %}
<div class="container mx-auto px-4 py-8">
    <h1 class="text-3xl font-bold mb-6">Gestion des livraisons</h1>
    
    <div class="bg-white rounded-lg shadow overflow-hidden">
        <div class="px-6 py-4 border-b bg-gray-50">
            <h2 class="text-xl font-semibold">Configurer vos tarifs de livraison</h2>
            <p class="text-gray-600 text-sm">Personnalisez les frais de port pour chaque méthode de livraison</p>
        </div>
        
        <div class="divide-y">
            {% for method in methods %}
                <div class="p-6" x-data="shippingRate({{ method.id }}, {{ vendorRates[method.id]|default({})|json_encode|raw }})">
                    <div class="flex items-start justify-between">
                        <div class="flex-1">
                            <div class="flex items-center">
                                {% if method.logo %}
                                    <img src="{{ asset('uploads/shipping/' ~ method.logo) }}" alt="{{ method.name }}" class="w-12 h-12 object-contain mr-4">
                                {% else %}
                                    <div class="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center mr-4">
                                        <i class="fas fa-truck text-gray-500 text-xl"></i>
                                    </div>
                                {% endif %}
                                <div>
                                    <h3 class="font-semibold text-lg">{{ method.name }}</h3>
                                    <p class="text-sm text-gray-500">{{ method.description }}</p>
                                    <p class="text-xs text-gray-400 mt-1">
                                        Livraison estimée : {{ method.estimatedDaysMin }}-{{ method.estimatedDaysMax }} jours
                                    </p>
                                </div>
                            </div>
                        </div>
                        <div class="text-right">
                            <span class="text-sm text-gray-500">Tarif par défaut</span>
                            <p class="font-semibold">{{ method.basePrice|number_format(2, ',', ' ') }} €</p>
                        </div>
                    </div>
                    
                    <div class="mt-4 pt-4 border-t">
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Prix fixe (€)
                                </label>
                                <input type="number" 
                                       x-model="fixedPrice"
                                       step="0.01"
                                       placeholder="Laisser vide pour utiliser le tarif par défaut"
                                       class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary-500">
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Prix au kilo (€/kg)
                                </label>
                                <input type="number" 
                                       x-model="pricePerKg"
                                       step="0.01"
                                       placeholder="Laisser vide pour utiliser le tarif par défaut"
                                       class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary-500">
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Livraison gratuite à partir de (€)
                                </label>
                                <input type="number" 
                                       x-model="freeShippingThreshold"
                                       step="0.01"
                                       placeholder="Laisser vide pour désactiver"
                                       class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary-500">
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">
                                    Jours de livraison estimés
                                </label>
                                <input type="number" 
                                       x-model="estimatedDays"
                                       step="1"
                                       placeholder="Laisser vide pour utiliser la valeur par défaut"
                                       class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary-500">
                            </div>
                        </div>
                        
                        <div class="mt-4 flex justify-end">
                            <button @click="saveRates()" 
                                    :disabled="isSaving"
                                    class="bg-primary-600 text-white px-4 py-2 rounded-lg hover:bg-primary-700 transition disabled:opacity-50">
                                <i class="fas fa-save mr-2"></i>
                                <span x-show="!isSaving">Enregistrer les modifications</span>
                                <span x-show="isSaving" x-cloak><i class="fas fa-spinner fa-spin mr-2"></i>Enregistrement...</span>
                            </button>
                        </div>
                        
                        <div x-show="showSuccess" 
                             x-cloak
                             class="mt-3 p-3 bg-green-50 text-green-700 rounded-lg text-sm">
                            <i class="fas fa-check-circle mr-2"></i> Tarifs mis à jour avec succès !
                        </div>
                        
                        <div x-show="showError" 
                             x-cloak
                             class="mt-3 p-3 bg-red-50 text-red-700 rounded-lg text-sm">
                            <i class="fas fa-exclamation-circle mr-2"></i> <span x-text="errorMessage"></span>
                        </div>
                    </div>
                </div>
            {% else %}
                <div class="p-12 text-center text-gray-500">
                    <i class="fas fa-truck text-4xl mb-3"></i>
                    <p>Aucune méthode de livraison disponible</p>
                </div>
            {% endfor %}
        </div>
    </div>
</div>

<script>
    function shippingRate(methodId, currentRates) {
        return {
            methodId: methodId,
            fixedPrice: currentRates.fixed_price || '',
            pricePerKg: currentRates.price_per_kg || '',
            freeShippingThreshold: currentRates.free_shipping_threshold || '',
            estimatedDays: currentRates.estimated_days || '',
            isSaving: false,
            showSuccess: false,
            showError: false,
            errorMessage: '',
            successTimeout: null,
            errorTimeout: null,
            
            async saveRates() {
                this.isSaving = true;
                this.showSuccess = false;
                this.showError = false;
                
                const data = {};
                
                if (this.fixedPrice !== '' && this.fixedPrice !== null) {
                    data.fixed_price = parseFloat(this.fixedPrice);
                }
                
                if (this.pricePerKg !== '' && this.pricePerKg !== null) {
                    data.price_per_kg = parseFloat(this.pricePerKg);
                }
                
                if (this.freeShippingThreshold !== '' && this.freeShippingThreshold !== null) {
                    data.free_shipping_threshold = parseFloat(this.freeShippingThreshold);
                }
                
                if (this.estimatedDays !== '' && this.estimatedDays !== null) {
                    data.estimated_days = parseInt(this.estimatedDays);
                }
                
                try {
                    const response = await fetch(`/vendor/shipping/rates/${this.methodId}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify(data)
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        this.showSuccess = true;
                        if (this.successTimeout) clearTimeout(this.successTimeout);
                        this.successTimeout = setTimeout(() => {
                            this.showSuccess = false;
                        }, 3000);
                    } else {
                        this.showError = true;
                        this.errorMessage = result.error || 'Erreur lors de l\'enregistrement';
                        if (this.errorTimeout) clearTimeout(this.errorTimeout);
                        this.errorTimeout = setTimeout(() => {
                            this.showError = false;
                        }, 5000);
                    }
                } catch (error) {
                    this.showError = true;
                    this.errorMessage = 'Erreur de connexion';
                    if (this.errorTimeout) clearTimeout(this.errorTimeout);
                    this.errorTimeout = setTimeout(() => {
                        this.showError = false;
                    }, 5000);
                } finally {
                    this.isSaving = false;
                }
            }
        }
    }
</script>

<style>
    [x-cloak] { display: none !important; }
</style>
{% endblock %}