{% extends 'base.html.twig' %}

{% block title %}Tableau de bord vendeur - Marketplace{% endblock %}

{% block body %}
<div class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8">
        <!-- Header -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold">Tableau de bord vendeur</h1>
            <p class="text-gray-600">Bienvenue {{ vendor.storeName }}</p>
        </div>
        
        <!-- Stats Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm">Chiffre d'affaires</p>
                        <p class="text-2xl font-bold text-primary-600">{{ stats.totalEarnings|default(0)|number_format(2, ',', ' ') }} €</p>
                        <p class="text-xs text-gray-400 mt-1">Ce mois</p>
                    </div>
                    <div class="bg-green-100 p-3 rounded-full">
                        <i class="fas fa-euro-sign text-green-600 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm">Commandes</p>
                        <p class="text-2xl font-bold">{{ stats.totalOrders|default(0) }}</p>
                        <p class="text-xs text-gray-400 mt-1">+{{ stats.orderGrowth|default(0) }}% vs mois dernier</p>
                    </div>
                    <div class="bg-blue-100 p-3 rounded-full">
                        <i class="fas fa-shopping-bag text-blue-600 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm">Produits actifs</p>
                        <p class="text-2xl font-bold">{{ stats.totalProducts|default(0) }}</p>
                        <p class="text-xs text-gray-400 mt-1">{{ stats.lowStock|default(0) }} en stock faible</p>
                    </div>
                    <div class="bg-purple-100 p-3 rounded-full">
                        <i class="fas fa-box text-purple-600 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm">Note moyenne</p>
                        <p class="text-2xl font-bold">{{ stats.averageRating|default(0)|number_format(1, ',', ' ') }}/5</p>
                        <p class="text-xs text-gray-400 mt-1">{{ stats.totalReviews|default(0) }} avis</p>
                    </div>
                    <div class="bg-yellow-100 p-3 rounded-full">
                        <i class="fas fa-star text-yellow-600 text-xl"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Charts and Analytics -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
            <!-- Sales Chart -->
            <div class="lg:col-span-2 bg-white rounded-lg shadow p-6">
                <h3 class="font-semibold text-lg mb-4">Ventes des 30 derniers jours</h3>
                <canvas id="salesChart" 
                        data-labels="{{ salesChart.labels|default([])|json_encode|e('html_attr') }}"
                        data-sales="{{ salesChart.sales|default([])|json_encode|e('html_attr') }}"
                        data-orders="{{ salesChart.orders|default([])|json_encode|e('html_attr') }}"
                        height="250"></canvas>
            </div>
            
            <!-- Quick Actions -->
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="font-semibold text-lg mb-4">Actions rapides</h3>
                <div class="space-y-3">
                    <a href="{{ path('vendor_product_new') }}" class="block w-full bg-primary-600 text-white text-center py-2 rounded-lg hover:bg-primary-700">
                        <i class="fas fa-plus mr-2"></i> Ajouter un produit
                    </a>
                    <a href="{{ path('vendor_products') }}" class="block w-full bg-purple-600 text-white text-center py-2 rounded-lg hover:bg-purple-700">
                        <i class="fas fa-box mr-2"></i> Gérer les produits
                    </a>
                    <a href="{{ path('vendor_orders') }}" class="block w-full bg-orange-600 text-white text-center py-2 rounded-lg hover:bg-orange-700">
                        <i class="fas fa-truck mr-2"></i> Gérer les commandes
                    </a>
                    <a href="{{ path('vendor_delivery_drivers') }}" class="block w-full bg-teal-600 text-white text-center py-2 rounded-lg hover:bg-teal-700">
                        <i class="fas fa-users mr-2"></i> Gérer les livreurs
                    </a>
                    <a href="{{ path('vendor_delivery_map') }}" class="block w-full bg-indigo-600 text-white text-center py-2 rounded-lg hover:bg-indigo-700">
                        <i class="fas fa-map-marked-alt mr-2"></i> Suivi des livreurs
                    </a>
                    <a href="{{ path('vendor_payouts') }}" class="block w-full bg-green-600 text-white text-center py-2 rounded-lg hover:bg-green-700">
                        <i class="fas fa-euro-sign mr-2"></i> Demander paiement
                    </a>
                    <a href="{{ path('vendor_shipping_methods') }}" class="block w-full bg-gray-600 text-white text-center py-2 rounded-lg hover:bg-gray-700">
                        <i class="fas fa-shipping-fast mr-2"></i> Gérer les livraisons
                    </a>
                </div>
            </div>
        </div>
        
        <!-- Recent Orders -->
        <div class="bg-white rounded-lg shadow overflow-hidden mb-8">
            <div class="px-6 py-4 border-b flex justify-between items-center">
                <h3 class="font-semibold text-lg">Commandes récentes</h3>
                <a href="{{ path('vendor_orders') }}" class="text-primary-600 hover:underline">Voir toutes</a>
            </div>
            
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-gray-50">
                        <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">Livreur</th>
                            <th class="px-6 py-3 text-left">Livraison</th>
                            <th class="px-6 py-3"></th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for order in recentOrders %}
                            <tr class="border-b hover:bg-gray-50">
                                <td class="px-6 py-4 font-mono text-sm">{{ order.orderNumber }}</td>
                                <td class="px-6 py-4">{{ order.user.fullName }}</td>
                                <td class="px-6 py-4">{{ order.createdAt|date('d/m/Y H:i') }}</td>
                                <td class="px-6 py-4 text-right font-semibold">{{ order.total|number_format(2, ',', ' ') }} €</td>
                                <td class="px-6 py-4">
                                    <span class="px-2 py-1 rounded-full text-xs 
                                        {% if order.status == 'pending' %}bg-yellow-100 text-yellow-800
                                        {% elseif order.status == 'confirmed' %}bg-blue-100 text-blue-800
                                        {% elseif order.status == 'preparing' %}bg-purple-100 text-purple-800
                                        {% elseif order.status == 'shipped' %}bg-indigo-100 text-indigo-800
                                        {% elseif order.status == 'delivered' %}bg-green-100 text-green-800
                                        {% elseif order.status == 'cancelled' %}bg-red-100 text-red-800
                                        {% endif %}">
                                        {{ order.status|trans }}
                                    </span>
                                </td>
                                <td class="px-6 py-4">
                                    {% if order.deliveryAssignment and order.deliveryAssignment.driver %}
                                        <div class="flex items-center">
                                            <div class="w-6 h-6 bg-gray-200 rounded-full flex items-center justify-center mr-2">
                                                <i class="fas fa-motorcycle text-xs text-gray-600"></i>
                                            </div>
                                            <span class="text-sm">{{ order.deliveryAssignment.driver.fullName }}</span>
                                        </div>
                                        <div class="text-xs text-gray-500 mt-1">
                                            Statut: {{ order.deliveryAssignment.status|trans }}
                                        </div>
                                    {% else %}
                                        <span class="text-gray-400 text-sm">Non assignée</span>
                                        <div class="mt-1">
                                            <button onclick="openAssignModal({{ order.id }})" 
                                                    class="text-primary-600 text-xs hover:underline">
                                                <i class="fas fa-plus mr-1"></i> Assigner
                                            </button>
                                        </div>
                                    {% endif %}
                                </td>
                                <td class="px-6 py-4">
                                    {% if order.shippingMethod %}
                                        <span class="text-sm">{{ order.shippingMethod.name }}</span>
                                        {% if order.shipment and order.shipment.trackingNumber %}
                                            <br><span class="text-xs text-gray-500">Suivi: {{ order.shipment.trackingNumber }}</span>
                                        {% endif %}
                                    {% else %}
                                        <span class="text-gray-400">-</span>
                                    {% endif %}
                                </td>
                                <td class="px-6 py-4">
                                    <a href="{{ path('vendor_order_show', {id: order.id}) }}" class="text-primary-600 hover:underline">
                                        Détails
                                    </a>
                                </td>
                            </tr>
                        {% else %}
                            <tr>
                                <td colspan="8" class="px-6 py-8 text-center text-gray-500">
                                    Aucune commande pour le moment
                                </td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Delivery Drivers Summary -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- Livreurs actifs -->
            <div class="bg-white rounded-lg shadow overflow-hidden">
                <div class="px-6 py-4 border-b flex justify-between items-center">
                    <h3 class="font-semibold text-lg">Livreurs actifs</h3>
                    <a href="{{ path('vendor_delivery_drivers') }}" class="text-primary-600 hover:underline">Gérer</a>
                </div>
                <div class="divide-y">
                    {% for driver in activeDrivers|default([]) %}
                        <div class="p-4 flex items-center justify-between">
                            <div class="flex items-center">
                                <div class="w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center mr-3">
                                    <i class="fas fa-motorcycle text-gray-500"></i>
                                </div>
                                <div>
                                    <div class="font-medium">{{ driver.fullName }}</div>
                                    <div class="text-xs text-gray-500">
                                        {{ driver.vehicleType|default('Véhicule non spécifié') }}
                                    </div>
                                </div>
                            </div>
                            <div class="text-right">
                                <div class="flex items-center">
                                    <span class="w-2 h-2 rounded-full {{ driver.isAvailable ? 'bg-green-500' : 'bg-gray-400' }} mr-2"></span>
                                    <span class="text-sm">{{ driver.isAvailable ? 'Disponible' : 'Indisponible' }}</span>
                                </div>
                                <div class="text-xs text-gray-400">
                                    {{ driver.completedDeliveriesToday }}/{{ driver.maxDeliveriesPerDay }} livraisons
                                </div>
                            </div>
                        </div>
                    {% else %}
                        <div class="p-6 text-center text-gray-500">
                            <i class="fas fa-truck fa-2x mb-2"></i>
                            <p>Aucun livreur actif</p>
                            <a href="{{ path('vendor_delivery_drivers') }}" class="text-primary-600 text-sm hover:underline">
                                Ajouter un livreur →
                            </a>
                        </div>
                    {% endfor %}
                </div>
            </div>
            
            <!-- Livraisons en cours -->
            <div class="bg-white rounded-lg shadow overflow-hidden">
                <div class="px-6 py-4 border-b flex justify-between items-center">
                    <h3 class="font-semibold text-lg">Livraisons en cours</h3>
                    <a href="{{ path('vendor_delivery_map') }}" class="text-primary-600 hover:underline">Voir la carte</a>
                </div>
                <div class="divide-y">
                    {% for assignment in activeDeliveries|default([]) %}
                        <div class="p-4">
                            <div class="flex justify-between items-start">
                                <div>
                                    <div class="font-mono text-sm font-semibold">{{ assignment.order.orderNumber }}</div>
                                    <div class="text-sm text-gray-600">{{ assignment.order.user.fullName }}</div>
                                </div>
                                <span class="px-2 py-1 rounded-full text-xs 
                                    {% if assignment.status == 'assigned' %}bg-blue-100 text-blue-800
                                    {% elseif assignment.status == 'picked_up' %}bg-purple-100 text-purple-800
                                    {% elseif assignment.status == 'in_transit' %}bg-indigo-100 text-indigo-800
                                    {% elseif assignment.status == 'delivered' %}bg-green-100 text-green-800
                                    {% endif %}">
                                    {{ assignment.status|trans }}
                                </span>
                            </div>
                            <div class="mt-2 flex items-center justify-between text-sm">
                                <div class="flex items-center">
                                    <i class="fas fa-motorcycle text-gray-400 mr-2"></i>
                                    <span>{{ assignment.driver.fullName }}</span>
                                </div>
                                <a href="{{ path('vendor_order_show', {id: assignment.order.id}) }}" 
                                   class="text-primary-600 hover:underline text-xs">
                                    Suivre →
                                </a>
                            </div>
                        </div>
                    {% else %}
                        <div class="p-6 text-center text-gray-500">
                            <i class="fas fa-check-circle fa-2x mb-2 text-green-500"></i>
                            <p>Aucune livraison en cours</p>
                        </div>
                    {% endfor %}
                </div>
            </div>
        </div>
        
        <!-- Low Stock Alert -->
        {% if lowStockProducts|length > 0 %}
            <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 rounded">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-triangle text-yellow-400 text-xl"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-yellow-700">
                            <strong>Attention :</strong> {{ lowStockProducts|length }} produit(s) ont un stock faible
                            (< 5 unités).
                        </p>
                    </div>
                </div>
            </div>
        {% endif %}
    </div>
</div>

<!-- Modal d'assignation de livreur -->
<div id="assignModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
        <div class="p-6">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold">Assigner un livreur</h2>
                <button onclick="closeAssignModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="assignForm" onsubmit="assignDriver(event)">
                <input type="hidden" id="assignOrderId" name="order_id">
                <div class="mb-4">
                    <label class="block text-sm font-medium mb-1">Sélectionner un livreur</label>
                    <select id="assignDriverId" name="driver_id" required class="w-full border rounded-lg px-3 py-2">
                        <option value="">Choisir un livreur...</option>
                        {% for driver in availableDrivers|default([]) %}
                            <option value="{{ driver.id }}">{{ driver.fullName }} ({{ driver.completedDeliveriesToday }}/{{ driver.maxDeliveriesPerDay }} livraisons)</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium mb-1">Livraison estimée</label>
                    <input type="date" id="assignEstimatedDate" name="estimated_date" class="w-full border rounded-lg px-3 py-2">
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeAssignModal()" class="px-4 py-2 border rounded-lg hover:bg-gray-50">Annuler</button>
                    <button type="submit" class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700">Assigner</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // Modal functions
    function openAssignModal(orderId) {
        document.getElementById('assignOrderId').value = orderId;
        document.getElementById('assignModal').classList.remove('hidden');
        document.getElementById('assignModal').classList.add('flex');
    }
    
    function closeAssignModal() {
        document.getElementById('assignModal').classList.add('hidden');
        document.getElementById('assignModal').classList.remove('flex');
    }
    
    async function assignDriver(event) {
        event.preventDefault();
        
        const orderId = document.getElementById('assignOrderId').value;
        const driverId = document.getElementById('assignDriverId').value;
        const estimatedDate = document.getElementById('assignEstimatedDate').value;
        
        const response = await fetch('{{ path('vendor_delivery_assign') }}', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
                order_id: orderId, 
                driver_id: driverId,
                estimated_date: estimatedDate
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            location.reload();
        } else {
            alert(data.error || 'Erreur lors de l\'assignation');
        }
    }
    
    // Chart initialization
    document.addEventListener('DOMContentLoaded', function() {
        const canvas = document.getElementById('salesChart');
        if (!canvas) return;
        
        try {
            const labels = JSON.parse(canvas.dataset.labels || '[]');
            const salesData = JSON.parse(canvas.dataset.sales || '[]').map(v => parseFloat(v) || 0);
            const ordersData = JSON.parse(canvas.dataset.orders || '[]').map(v => parseInt(v) || 0);
            
            if (labels.length === 0) return;
            
            const ctx = canvas.getContext('2d');
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [
                        {
                            label: 'Ventes (€)',
                            data: salesData,
                            borderColor: '#3b82f6',
                            backgroundColor: 'rgba(59, 130, 246, 0.1)',
                            borderWidth: 2,
                            tension: 0.4,
                            fill: true,
                            yAxisID: 'y'
                        },
                        {
                            label: 'Nombre de commandes',
                            data: ordersData,
                            borderColor: '#10b981',
                            backgroundColor: 'rgba(16, 185, 129, 0.1)',
                            borderWidth: 2,
                            tension: 0.4,
                            fill: true,
                            yAxisID: 'y1'
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: { mode: 'index', intersect: false },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    let label = context.dataset.label || '';
                                    let value = context.raw;
                                    if (context.dataset.label === 'Ventes (€)') {
                                        return label + ': ' + value.toFixed(2) + ' €';
                                    }
                                    return label + ': ' + value;
                                }
                            }
                        },
                        legend: { position: 'bottom' }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: { display: true, text: 'Ventes (€)', color: '#3b82f6' },
                            ticks: { callback: function(value) { return value.toLocaleString('fr-FR') + ' €'; } }
                        },
                        y1: {
                            beginAtZero: true,
                            position: 'right',
                            title: { display: true, text: 'Nombre de commandes', color: '#10b981' },
                            grid: { drawOnChartArea: false },
                            ticks: { stepSize: 1 }
                        }
                    }
                }
            });
        } catch (error) {
            console.error('Erreur de chargement du graphique:', error);
        }
    });
</script>
{% endblock %}