{% extends 'base.html.twig' %}

{% block title %}Paiement - Marketplace{% endblock %}

{% block body %}
<div class="container mx-auto px-4 py-8">
    <h1 class="text-3xl font-bold mb-8">Finaliser ma commande</h1>
    
    <div class="flex flex-col lg:flex-row gap-8">
        <!-- Checkout Form -->
        <div class="lg:w-2/3">
            <form method="POST" action="{{ path('checkout_process') }}" data-controller="checkout">
                <!-- Shipping Address -->
                <div class="bg-white rounded-lg shadow mb-6">
                    <div class="px-6 py-4 border-b">
                        <h2 class="text-xl font-semibold">Adresse de livraison</h2>
                    </div>
                    <div class="p-6">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div class="md:col-span-2">
                                <label class="block text-sm font-medium mb-1">Nom complet *</label>
                                <input type="text" name="shipping[full_name]" value="{{ app.user.fullName }}" required
                                       class="w-full border rounded-lg px-3 py-2">
                            </div>
                            <div class="md:col-span-2">
                                <label class="block text-sm font-medium mb-1">Adresse *</label>
                                <input type="text" name="shipping[address]" required
                                       class="w-full border rounded-lg px-3 py-2">
                            </div>
                            <div>
                                <label class="block text-sm font-medium mb-1">Code postal *</label>
                                <input type="text" name="shipping[postal_code]" required
                                       data-checkout-target="postalCode"
                                       data-action="input->checkout#estimateShipping"
                                       class="w-full border rounded-lg px-3 py-2">
                            </div>
                            <div>
                                <label class="block text-sm font-medium mb-1">Ville *</label>
                                <input type="text" name="shipping[city]" required
                                       class="w-full border rounded-lg px-3 py-2">
                            </div>
                            <div>
                                <label class="block text-sm font-medium mb-1">Pays *</label>
                                <select name="shipping[country]" required
                                        data-checkout-target="country"
                                        data-action="change->checkout#estimateShipping"
                                        class="w-full border rounded-lg px-3 py-2">
                                    <option value="FR">France</option>
                                    <option value="BE">Belgique</option>
                                    <option value="CH">Suisse</option>
                                    <option value="LU">Luxembourg</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium mb-1">Téléphone</label>
                                <input type="tel" name="shipping[phone]" value="{{ app.user.phone }}"
                                       class="w-full border rounded-lg px-3 py-2">
                            </div>
                        </div>
                        
                        <div class="mt-4">
                            <label class="flex items-center">
                                <input type="checkbox" name="same_as_shipping" checked
                                       data-action="change->checkout#toggleBilling"
                                       class="mr-2">
                                <span class="text-sm">Utiliser la même adresse pour la facturation</span>
                            </label>
                        </div>
                    </div>
                </div>
                
                <!-- Billing Address -->
                <div class="bg-white rounded-lg shadow mb-6" data-checkout-target="billingAddress" style="display: none;">
                    <div class="px-6 py-4 border-b">
                        <h2 class="text-xl font-semibold">Adresse de facturation</h2>
                    </div>
                    <div class="p-6">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div class="md:col-span-2">
                                <input type="text" name="billing[full_name]" placeholder="Nom complet"
                                       class="w-full border rounded-lg px-3 py-2">
                            </div>
                            <div class="md:col-span-2">
                                <input type="text" name="billing[address]" placeholder="Adresse"
                                       class="w-full border rounded-lg px-3 py-2">
                            </div>
                            <div>
                                <input type="text" name="billing[postal_code]" placeholder="Code postal"
                                       class="w-full border rounded-lg px-3 py-2">
                            </div>
                            <div>
                                <input type="text" name="billing[city]" placeholder="Ville"
                                       class="w-full border rounded-lg px-3 py-2">
                            </div>
                            <div>
                                <select name="billing[country]" class="w-full border rounded-lg px-3 py-2">
                                    <option value="FR">France</option>
                                    <option value="BE">Belgique</option>
                                    <option value="CH">Suisse</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Shipping Method -->
                <div class="bg-white rounded-lg shadow mb-6">
                    <div class="px-6 py-4 border-b">
                        <h2 class="text-xl font-semibold">Mode de livraison</h2>
                    </div>
                    <div class="p-6">
                        <div class="space-y-3" data-checkout-target="shippingMethods">
                            <div class="text-center py-8 text-gray-500">
                                <i class="fas fa-spinner fa-spin text-2xl"></i>
                                <p class="mt-2">Chargement des modes de livraison...</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Payment Method -->
                <div class="bg-white rounded-lg shadow mb-6">
                    <div class="px-6 py-4 border-b">
                        <h2 class="text-xl font-semibold">Mode de paiement</h2>
                    </div>
                    <div class="p-6">
                        <div class="space-y-3">
                            <label class="flex items-center p-4 border rounded-lg cursor-pointer hover:bg-gray-50">
                                <input type="radio" name="payment_method" value="card" checked
                                       class="mr-3">
                                <div>
                                    <div class="font-semibold">Carte bancaire</div>
                                    <div class="text-sm text-gray-500">Paiement sécurisé par carte bancaire</div>
                                </div>
                            </label>
                            
                            <label class="flex items-center p-4 border rounded-lg cursor-pointer hover:bg-gray-50">
                                <input type="radio" name="payment_method" value="paypal"
                                       class="mr-3">
                                <div>
                                    <div class="font-semibold">PayPal</div>
                                    <div class="text-sm text-gray-500">Paiement via votre compte PayPal</div>
                                </div>
                            </label>
                        </div>
                    </div>
                </div>
                
                <!-- Order Notes -->
                <div class="bg-white rounded-lg shadow mb-6">
                    <div class="px-6 py-4 border-b">
                        <h2 class="text-xl font-semibold">Notes de commande</h2>
                    </div>
                    <div class="p-6">
                        <textarea name="notes" rows="3" placeholder="Instructions particulières..."
                                  class="w-full border rounded-lg px-3 py-2"></textarea>
                    </div>
                </div>
                
                <button type="submit"
                        class="w-full bg-primary-600 text-white py-3 rounded-lg text-lg font-semibold hover:bg-primary-700 transition">
                    Confirmer et payer
                </button>
            </form>
        </div>
        
        <!-- Order Summary -->
        <div class="lg:w-1/3">
            <div class="bg-white rounded-lg shadow p-6 sticky top-24">
                <h2 class="text-xl font-bold mb-4">Récapitulatif</h2>
                
                <div class="space-y-3 mb-4">
                    {% for item in cart.items %}
                        <div class="flex justify-between text-sm">
                            <span>{{ item.quantity }}x {{ item.product.name }}</span>
                            <span>{{ (item.price * item.quantity)|number_format(2, ',', ' ') }} €</span>
                        </div>
                    {% endfor %}
                    
                    <div class="border-t pt-3 mt-3">
                        <div class="flex justify-between">
                            <span>Sous-total</span>
                            <span>{{ cart.subtotal|number_format(2, ',', ' ') }} €</span>
                        </div>
                        <div class="flex justify-between mt-2" data-checkout-target="shippingCost">
                            <span>Livraison</span>
                            <span>0,00 €</span>
                        </div>
                        <div class="flex justify-between mt-2">
                            <span>TVA (20%)</span>
                            <span>{{ cart.tax|number_format(2, ',', ' ') }} €</span>
                        </div>
                        <div class="border-t pt-3 mt-3">
                            <div class="flex justify-between font-bold text-lg">
                                <span>Total</span>
                                <span data-checkout-target="total" class="text-primary-600">{{ cart.total|number_format(2, ',', ' ') }} €</span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="text-center text-xs text-gray-500 mt-4">
                    <i class="fas fa-lock mr-1"></i> Transactions sécurisées
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block javascripts %}
{{ parent() }}
<script>
    application.register('checkout', class extends Controller {
        static targets = ['country', 'postalCode', 'shippingMethods', 'shippingCost', 'total', 'billingAddress']
        
        async estimateShipping() {
            const country = this.countryTarget.value
            const postalCode = this.postalCodeTarget.value
            
            if (!country || !postalCode) return
            
            const response = await fetch('/api/shipping/methods', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ country, postal_code: postalCode })
            })
            
            const data = await response.json()
            this.renderShippingMethods(data.methods)
            this.updateShippingCost(data.selected_method?.price || 0)
        }
        
        renderShippingMethods(methods) {
            if (!methods.length) {
                this.shippingMethodsTarget.innerHTML = '<div class="text-center py-4 text-red-500">Aucun mode de livraison disponible pour cette adresse</div>'
                return
            }
            
            this.shippingMethodsTarget.innerHTML = methods.map(method => `
                <label class="flex items-center justify-between p-4 border rounded-lg cursor-pointer hover:bg-gray-50">
                    <div class="flex items-center">
                        <input type="radio" name="shipping_method" value="${method.id}" class="mr-3" data-price="${method.price}">
                        <div>
                            <div class="font-semibold">${method.name}</div>
                            <div class="text-sm text-gray-500">Livraison estimée: ${method.estimated_days_min}-${method.estimated_days_max} jours</div>
                        </div>
                    </div>
                    <div class="font-semibold">${method.price.toFixed(2)} €</div>
                </label>
            `).join('')
            
            // Add event listeners
            this.shippingMethodsTarget.querySelectorAll('input[name="shipping_method"]').forEach(radio => {
                radio.addEventListener('change', (e) => {
                    this.updateShippingCost(parseFloat(e.target.dataset.price))
                })
            })
            
            // Select first method
            const firstRadio = this.shippingMethodsTarget.querySelector('input[name="shipping_method"]')
            if (firstRadio) {
                firstRadio.checked = true
                this.updateShippingCost(parseFloat(firstRadio.dataset.price))
            }
        }
        
        updateShippingCost(cost) {
            this.shippingCostTarget.innerHTML = cost.toFixed(2) + ' €'
            const totalElement = this.totalTarget
            const currentTotal = parseFloat(totalElement.textContent.replace(' €', '').replace(',', '.'))
            const subtotal = {{ cart.subtotal }} + {{ cart.tax }}
            const newTotal = subtotal + cost
            totalElement.textContent = newTotal.toFixed(2) + ' €'
        }
        
        toggleBilling(event) {
            this.billingAddressTarget.style.display = event.target.checked ? 'none' : 'block'
        }
    })
</script>
{% endblock %}