{% extends 'base.html.twig' %}

{% block title %}Mes produits - Espace Vendeur{% endblock %}

{% block body %}
<div class="container mx-auto px-4 py-8">
<!-- Bouton retour -->
    <div class="mb-6">
        <a href="{{ path('vendor_dashboard') }}" class="inline-flex items-center text-gray-600 hover:text-primary-600 transition">
            <i class="fas fa-arrow-left mr-2"></i>
            Retour au tableau de bord
        </a>
    </div>
    <!-- En-tête -->
    <div class="flex justify-between items-center mb-6">
        <div>
            <h1 class="text-3xl font-bold">Mes produits</h1>
            <p class="text-gray-600 mt-1">Gérez votre catalogue de produits</p>
        </div>
        <a href="{{ path('vendor_product_new') }}" 
           class="bg-primary-600 text-white px-4 py-2 rounded-lg hover:bg-primary-700 transition flex items-center">
            <i class="fas fa-plus mr-2"></i> Ajouter un produit
        </a>
    </div>

    <!-- Statistiques -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-lg shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">Total produits</p>
                    <p class="text-2xl font-bold">{{ stats.total|default(0) }}</p>
                </div>
                <i class="fas fa-box text-2xl text-blue-500"></i>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">Actifs</p>
                    <p class="text-2xl font-bold text-green-600">{{ stats.active|default(0) }}</p>
                </div>
                <i class="fas fa-check-circle text-2xl text-green-500"></i>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">En rupture</p>
                    <p class="text-2xl font-bold text-red-600">{{ stats.outOfStock|default(0) }}</p>
                </div>
                <i class="fas fa-exclamation-triangle text-2xl text-red-500"></i>
            </div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">Stock faible</p>
                    <p class="text-2xl font-bold text-orange-600">{{ stats.lowStock|default(0) }}</p>
                </div>
                <i class="fas fa-clock text-2xl text-orange-500"></i>
            </div>
        </div>
    </div>

    <!-- Filtres -->
    <div class="bg-white rounded-lg shadow mb-6 p-4">
        <div class="flex flex-wrap gap-4">
            <div class="flex-1 min-w-[200px]">
                <input type="text" 
                       id="searchInput" 
                       placeholder="Rechercher un produit..."
                       class="w-full border rounded-lg px-3 py-2">
            </div>
            <select id="statusFilter" class="border rounded-lg px-3 py-2">
                <option value="all">Tous les statuts</option>
                <option value="active">Actifs</option>
                <option value="inactive">Inactifs</option>
                <option value="outofstock">Rupture de stock</option>
            </select>
            <button id="resetFilters" class="bg-gray-200 px-4 py-2 rounded-lg hover:bg-gray-300">
                Réinitialiser
            </button>
        </div>
    </div>

    <!-- Liste des produits -->
    <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">Produit</th>
                        <th class="px-6 py-3 text-left">Prix</th>
                        <th class="px-6 py-3 text-left">Stock</th>
                        <th class="px-6 py-3 text-left">Statut</th>
                        <th class="px-6 py-3 text-left">Approbation</th>
                        <th class="px-6 py-3 text-left">Ventes</th>
                        <th class="px-6 py-3 text-center">Actions</th>
                    </tr>
                </thead>
                <tbody id="productsTableBody">
                    {% for product in products %}
                        <tr class="border-b hover:bg-gray-50 product-row" 
                            data-name="{{ product.name|lower }}"
                            data-status="{% if product.stock == 0 %}outofstock{% elseif product.isActive %}active{% else %}inactive{% endif %}">
                            <td class="px-6 py-4">
                                <div class="flex items-center">
                                    {% set image = product.images|first %}
                                    <img src="{{ image ? asset('uploads/products/' ~ image) : 'https://via.placeholder.com/50' }}" 
                                         alt="{{ product.name }}"
                                         class="w-12 h-12 object-cover rounded">
                                    <div class="ml-3">
                                        <p class="font-semibold">{{ product.name }}</p>
                                        <p class="text-xs text-gray-500">SKU: {{ product.sku }}</p>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4">
                                <span class="font-semibold">{{ product.price|number_format(2, ',', ' ') }} €</span>
                                {% if product.compareAtPrice %}
                                    <span class="text-sm text-gray-400 line-through ml-1">{{ product.compareAtPrice|number_format(2, ',', ' ') }} €</span>
                                {% endif %}
                            </td>
                            <td class="px-6 py-4">
                                {% if product.stock == 0 %}
                                    <span class="text-red-600 font-semibold">Rupture</span>
                                {% elseif product.stock < 5 %}
                                    <span class="text-orange-600">Stock faible: {{ product.stock }}</span>
                                {% else %}
                                    <span class="text-green-600">{{ product.stock }} unités</span>
                                {% endif %}
                            </td>
                            <td class="px-6 py-4">
                                {% if product.isActive %}
                                    <span class="px-2 py-1 bg-green-100 text-green-800 rounded-full text-xs">Actif</span>
                                {% else %}
                                    <span class="px-2 py-1 bg-red-100 text-red-800 rounded-full text-xs">Inactif</span>
                                {% endif %}
                            </td>
                            <td class="px-6 py-4">
                                {% if product.isApproved %}
                                    <span class="px-2 py-1 bg-green-100 text-green-800 rounded-full text-xs">Approuvé</span>
                                {% else %}
                                    <span class="px-2 py-1 bg-yellow-100 text-yellow-800 rounded-full text-xs">En attente</span>
                                {% endif %}
                            </td>
                            <td class="px-6 py-4">
                                <span class="font-semibold">{{ product.totalSold|default(0) }}</span>
                            </td>
                            <td class="px-6 py-4 text-center">
                                <div class="flex justify-center space-x-2">
                                    <a href="{{ path('vendor_product_edit', {id: product.id}) }}" 
                                       class="text-blue-600 hover:text-blue-800"
                                       title="Modifier">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <button onclick="toggleProductStatus({{ product.id }}, {{ product.isActive ? 'false' : 'true' }})" 
                                            class="text-{{ product.isActive ? 'yellow' : 'green' }}-600 hover:text-{{ product.isActive ? 'yellow' : 'green' }}-800"
                                            title="{{ product.isActive ? 'Désactiver' : 'Activer' }}">
                                        <i class="fas fa-{{ product.isActive ? 'ban' : 'check-circle' }}"></i>
                                    </button>
                                    <button onclick="deleteProduct({{ product.id }})" 
                                            class="text-red-600 hover:text-red-800"
                                            title="Supprimer">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    {% else %}
                        <tr>
                            <td colspan="7" class="px-6 py-12 text-center text-gray-500">
                                <i class="fas fa-box-open text-4xl mb-2 block"></i>
                                <p>Aucun produit trouvé</p>
                                <a href="{{ path('vendor_product_new') }}" class="text-primary-600 hover:underline mt-2 inline-block">
                                    Ajouter votre premier produit
                                </a>
                            </td>
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    // Filtrage des produits
    const searchInput = document.getElementById('searchInput');
    const statusFilter = document.getElementById('statusFilter');
    const resetBtn = document.getElementById('resetFilters');
    const rows = document.querySelectorAll('.product-row');

    function filterProducts() {
        const searchTerm = searchInput.value.toLowerCase();
        const status = statusFilter.value;

        rows.forEach(row => {
            const name = row.dataset.name;
            const rowStatus = row.dataset.status;
            
            let matchesSearch = name.includes(searchTerm);
            let matchesStatus = status === 'all' || rowStatus === status;
            
            if (matchesSearch && matchesStatus) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }

    searchInput.addEventListener('input', filterProducts);
    statusFilter.addEventListener('change', filterProducts);
    
    resetBtn.addEventListener('click', () => {
        searchInput.value = '';
        statusFilter.value = 'all';
        filterProducts();
    });

    // Actions AJAX
    async function toggleProductStatus(productId, activate) {
        if (!confirm(activate ? 'Activer ce produit ?' : 'Désactiver ce produit ?')) return;
        
        try {
            const response = await fetch(`/vendor/products/${productId}/toggle`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });
            
            const data = await response.json();
            
            if (data.success) {
                window.showNotification(data.message || 'Statut mis à jour', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                window.showNotification(data.error || 'Erreur', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            window.showNotification('Erreur de connexion', 'error');
        }
    }

    async function deleteProduct(productId) {
        if (!confirm('Êtes-vous sûr de vouloir supprimer ce produit ? Cette action est irréversible.')) return;
        
        try {
            const response = await fetch(`/vendor/products/${productId}/delete`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });
            
            const data = await response.json();
            
            if (data.success) {
                window.showNotification('Produit supprimé', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                window.showNotification(data.error || 'Erreur', 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            window.showNotification('Erreur de connexion', 'error');
        }
    }
</script>
{% endblock %}