{# templates/vendor/orders.html.twig #}
{% extends 'base.html.twig' %}

{% block title %}Commandes - Espace Vendeur{% endblock %}

{% block body %}
<div class="container mx-auto px-4 py-8">
    <h1 class="text-3xl font-bold mb-8">Gestion des commandes</h1>
    
    <!-- Filtres -->
    <div class="bg-white rounded-lg shadow p-4 mb-6">
        <div class="flex flex-wrap gap-4">
            <select x-model="statusFilter" @change="filterOrders" class="border rounded-lg px-3 py-2">
                <option value="all">Tous les statuts</option>
                <option value="pending">En attente</option>
                <option value="confirmed">Confirmée</option>
                <option value="preparing">En préparation</option>
                <option value="shipped">Expédiée</option>
                <option value="delivered">Livrée</option>
                <option value="cancelled">Annulée</option>
            </select>
            
            <input type="text" 
                   placeholder="N° commande" 
                   x-model="searchTerm"
                   @input="filterOrders"
                   class="border rounded-lg px-3 py-2 w-64">
            
            <button @click="resetFilters" class="bg-gray-200 px-4 py-2 rounded-lg hover:bg-gray-300">
                Réinitialiser
            </button>
        </div>
    </div>
    
    <!-- Commandes -->
    <div class="bg-white rounded-lg shadow overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 border-b">
                    <tr>
                        <th class="px-6 py-3 text-left">N° commande</th>
                        <th class="px-6 py-3 text-left">Client</th>
                        <th class="px-6 py-3 text-left">Date</th>
                        <th class="px-6 py-3 text-right">Montant</th>
                        <th class="px-6 py-3 text-left">Statut</th>
                        <th class="px-6 py-3 text-left">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <template x-for="order in filteredOrders" :key="order.id">
                        <tr class="border-b hover:bg-gray-50">
                            <td class="px-6 py-4 font-mono text-sm" x-text="order.orderNumber"></td>
                            <td class="px-6 py-4" x-text="order.customerName"></td>
                            <td class="px-6 py-4" x-text="formatDate(order.createdAt)"></td>
                            <td class="px-6 py-4 text-right font-semibold" x-text="formatPrice(order.total)"></td>
                            <td class="px-6 py-4">
                                <span x-show="order.status === 'pending'" class="px-2 py-1 rounded-full text-xs bg-yellow-100 text-yellow-800">
                                    En attente
                                </span>
                                <span x-show="order.status === 'confirmed'" class="px-2 py-1 rounded-full text-xs bg-blue-100 text-blue-800">
                                    Confirmée
                                </span>
                                <span x-show="order.status === 'preparing'" class="px-2 py-1 rounded-full text-xs bg-purple-100 text-purple-800">
                                    En préparation
                                </span>
                                <span x-show="order.status === 'shipped'" class="px-2 py-1 rounded-full text-xs bg-indigo-100 text-indigo-800">
                                    Expédiée
                                </span>
                                <span x-show="order.status === 'delivered'" class="px-2 py-1 rounded-full text-xs bg-green-100 text-green-800">
                                    Livrée
                                </span>
                                <span x-show="order.status === 'cancelled'" class="px-2 py-1 rounded-full text-xs bg-red-100 text-red-800">
                                    Annulée
                                </span>
                            </td>
                            <td class="px-6 py-4">
                                <button @click="showOrderDetails(order)" 
                                        class="text-primary-600 hover:underline mr-3">
                                    Détails
                                </button>
                                <button x-show="order.status === 'pending'" 
                                        @click="updateStatus(order.id, 'confirmed')"
                                        class="text-green-600 hover:underline mr-3">
                                    Confirmer
                                </button>
                                <button x-show="order.status === 'confirmed'" 
                                        @click="updateStatus(order.id, 'preparing')"
                                        class="text-blue-600 hover:underline mr-3">
                                    Préparer
                                </button>
                                <button x-show="order.status === 'preparing'" 
                                        @click="updateStatus(order.id, 'shipped')"
                                        class="text-purple-600 hover:underline mr-3">
                                    Expédier
                                </button>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
        
        <div x-show="filteredOrders.length === 0" class="text-center py-8 text-gray-500">
            Aucune commande trouvée
        </div>
    </div>
    
    <!-- Modal Détails Commande -->
    <div x-show="selectedOrder" 
         x-cloak
         class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
         @click.away="selectedOrder = null">
        <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-2xl font-bold">Commande <span x-text="selectedOrder?.orderNumber"></span></h2>
                    <button @click="selectedOrder = null" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                
                <!-- Informations client -->
                <div class="mb-6">
                    <h3 class="font-semibold text-lg mb-2">Client</h3>
                    <p x-text="selectedOrder?.customerName"></p>
                    <p x-text="selectedOrder?.customerEmail"></p>
                    <p x-text="selectedOrder?.customerPhone"></p>
                </div>
                
                <!-- Adresse de livraison -->
                <div class="mb-6">
                    <h3 class="font-semibold text-lg mb-2">Adresse de livraison</h3>
                    <p x-text="selectedOrder?.shippingAddress?.address"></p>
                    <p x-text="selectedOrder?.shippingAddress?.postal_code + ' ' + selectedOrder?.shippingAddress?.city"></p>
                    <p x-text="selectedOrder?.shippingAddress?.country"></p>
                </div>
                
                <!-- Produits -->
                <div class="mb-6">
                    <h3 class="font-semibold text-lg mb-2">Produits</h3>
                    <table class="w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-4 py-2 text-left">Produit</th>
                                <th class="px-4 py-2 text-center">Qté</th>
                                <th class="px-4 py-2 text-right">Prix</th>
                                <th class="px-4 py-2 text-right">Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <template x-for="item in selectedOrder?.items" :key="item.id">
                                <tr class="border-b">
                                    <td class="px-4 py-2" x-text="item.productName"></td>
                                    <td class="px-4 py-2 text-center" x-text="item.quantity"></td>
                                    <td class="px-4 py-2 text-right" x-text="formatPrice(item.price)"></td>
                                    <td class="px-4 py-2 text-right" x-text="formatPrice(item.price * item.quantity)"></td>
                                </tr>
                            </template>
                        </tbody>
                    </table>
                </div>
                
                <!-- Totaux -->
                <div class="border-t pt-4">
                    <div class="flex justify-between mb-2">
                        <span>Sous-total</span>
                        <span x-text="formatPrice(selectedOrder?.subtotal)"></span>
                    </div>
                    <div class="flex justify-between mb-2">
                        <span>Livraison</span>
                        <span x-text="formatPrice(selectedOrder?.shippingCost)"></span>
                    </div>
                    <div class="flex justify-between mb-2">
                        <span>TVA (20%)</span>
                        <span x-text="formatPrice(selectedOrder?.tax)"></span>
                    </div>
                    <div class="flex justify-between font-bold text-lg mt-3 pt-3 border-t">
                        <span>Total</span>
                        <span class="text-primary-600" x-text="formatPrice(selectedOrder?.total)"></span>
                    </div>
                </div>
                
                <!-- Actions -->
                <div class="mt-6 flex justify-end space-x-3">
                    <button @click="selectedOrder = null" class="px-4 py-2 border rounded-lg hover:bg-gray-50">
                        Fermer
                    </button>
                    <button x-show="selectedOrder?.status === 'pending'"
                            @click="updateStatus(selectedOrder.id, 'confirmed'); selectedOrder = null"
                            class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">
                        Confirmer la commande
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function vendorOrders() {
        return {
            orders: [],
            filteredOrders: [],
            statusFilter: 'all',
            searchTerm: '',
            selectedOrder: null,
            
            async init() {
                await this.loadOrders();
            },
            
            async loadOrders() {
                try {
                    const response = await fetch('/api/vendor/orders', {
                        headers: { 'Accept': 'application/json' }
                    });
                    if (response.ok) {
                        this.orders = await response.json();
                        this.filterOrders();
                    }
                } catch (error) {
                    console.error('Error loading orders:', error);
                }
            },
            
            filterOrders() {
                this.filteredOrders = this.orders.filter(order => {
                    const matchesStatus = this.statusFilter === 'all' || order.status === this.statusFilter;
                    const matchesSearch = !this.searchTerm || 
                        order.orderNumber.toLowerCase().includes(this.searchTerm.toLowerCase()) ||
                        order.customerName.toLowerCase().includes(this.searchTerm.toLowerCase());
                    return matchesStatus && matchesSearch;
                });
            },
            
            resetFilters() {
                this.statusFilter = 'all';
                this.searchTerm = '';
                this.filterOrders();
            },
            
            async updateStatus(orderId, newStatus) {
                try {
                    const response = await fetch(`/api/vendor/orders/${orderId}/status`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ status: newStatus })
                    });
                    
                    if (response.ok) {
                        await this.loadOrders();
                        this.showNotification('Statut mis à jour', 'success');
                    }
                } catch (error) {
                    console.error('Error updating status:', error);
                    this.showNotification('Erreur lors de la mise à jour', 'error');
                }
            },
            
            async showOrderDetails(order) {
                try {
                    const response = await fetch(`/api/vendor/orders/${order.id}`);
                    if (response.ok) {
                        this.selectedOrder = await response.json();
                    }
                } catch (error) {
                    console.error('Error loading order details:', error);
                }
            },
            
            formatPrice(price) {
                return new Intl.NumberFormat('fr-FR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(price);
            },
            
            formatDate(date) {
                return new Date(date).toLocaleDateString('fr-FR');
            },
            
            showNotification(message, type) {
                if (window.showNotification) window.showNotification(message, type);
                else alert(message);
            }
        }
    }
</script>
{% endblock %}