{# templates/vendor/products/edit.html.twig #}
{% extends 'base.html.twig' %}

{% block title %}Modifier {{ product.name }} - Marketplace{% endblock %}

{% block body %}
<div class="container mx-auto px-4 py-8">
    <div class="max-w-4xl mx-auto">
        <div class="flex items-center mb-6">
            <a href="{{ path('vendor_products') }}" class="text-gray-600 hover:text-gray-900 mr-4">
                <i class="fas fa-arrow-left text-xl"></i>
            </a>
            <h1 class="text-2xl font-bold">Modifier le produit</h1>
        </div>
        
        <div class="bg-white rounded-lg shadow overflow-hidden" x-data="productForm()" x-init="init()">
            <form @submit.prevent="submitProduct" method="POST" enctype="multipart/form-data" class="p-6 space-y-6">
                <!-- Messages d'erreur globaux -->
                <div x-show="errors.global" x-cloak class="bg-red-50 border-l-4 border-red-500 p-4 rounded">
                    <div class="flex items-center">
                        <i class="fas fa-exclamation-circle text-red-500 mr-2"></i>
                        <span class="text-red-700" x-text="errors.global"></span>
                    </div>
                </div>
                
                <!-- Informations générales -->
                <div>
                    <h2 class="text-lg font-semibold mb-4">Informations générales</h2>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- Nom du produit -->
                        <div>
                            <label class="block text-sm font-medium mb-1">
                                Nom du produit <span class="text-red-500">*</span>
                            </label>
                            <input type="text" 
                                   x-model="form.name"
                                   @input="validateField('name')"
                                   class="w-full border rounded-lg px-3 py-2 focus:ring-2 focus:ring-primary-500"
                                   :class="{'border-red-500': errors.name, 'border-green-500': valid.name}">
                            <p class="text-xs text-gray-500 mt-1">Minimum 3 caractères, maximum 255</p>
                            <p x-show="errors.name" x-text="errors.name" class="text-red-500 text-xs mt-1"></p>
                        </div>
                        
                        <!-- Catégorie -->
                        <div>
                            <label class="block text-sm font-medium mb-1">
                                Catégorie <span class="text-red-500">*</span>
                            </label>
                            <select x-model="form.category" 
                                    @change="validateField('category')"
                                    class="w-full border rounded-lg px-3 py-2"
                                    :class="{'border-red-500': errors.category}">
                                <option value="">Sélectionner une catégorie</option>
                                {% for category in categories %}
                                    <option value="{{ category.id }}">{{ category.name }}</option>
                                {% endfor %}
                            </select>
                            <p x-show="errors.category" x-text="errors.category" class="text-red-500 text-xs mt-1"></p>
                        </div>
                    </div>
                    
                    <!-- Description -->
                    <div class="mt-4">
                        <label class="block text-sm font-medium mb-1">
                            Description <span class="text-red-500">*</span>
                        </label>
                        <textarea x-model="form.description"
                                  @input="validateField('description')"
                                  rows="5"
                                  class="w-full border rounded-lg px-3 py-2"
                                  :class="{'border-red-500': errors.description}"></textarea>
                        <div class="flex justify-between text-xs mt-1">
                            <p class="text-gray-500">Description détaillée du produit</p>
                            <p class="text-gray-500" :class="{'text-red-500': form.description.length < 20}">
                                <span x-text="form.description.length"></span> / 2000 caractères
                            </p>
                        </div>
                        <p x-show="errors.description" x-text="errors.description" class="text-red-500 text-xs mt-1"></p>
                    </div>
                </div>
                
                <!-- Prix et stock -->
                <div>
                    <h2 class="text-lg font-semibold mb-4">Prix et stock</h2>
                    
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <!-- Prix -->
                        <div>
                            <label class="block text-sm font-medium mb-1">
                                Prix (€) <span class="text-red-500">*</span>
                            </label>
                            <input type="number" 
                                   x-model="form.price"
                                   @input="validateField('price')"
                                   step="0.01"
                                   class="w-full border rounded-lg px-3 py-2"
                                   :class="{'border-red-500': errors.price}">
                            <p x-show="errors.price" x-text="errors.price" class="text-red-500 text-xs mt-1"></p>
                        </div>
                        
                        <!-- Prix barré -->
                        <div>
                            <label class="block text-sm font-medium mb-1">Prix barré (€)</label>
                            <input type="number" 
                                   x-model="form.compareAtPrice"
                                   @input="validateField('compareAtPrice')"
                                   step="0.01"
                                   class="w-full border rounded-lg px-3 py-2"
                                   :class="{'border-yellow-500': form.compareAtPrice && form.compareAtPrice <= form.price}">
                            <p x-show="form.compareAtPrice && form.compareAtPrice <= form.price" 
                               class="text-yellow-500 text-xs mt-1">
                                ⚠️ Le prix barré doit être supérieur au prix normal
                            </p>
                        </div>
                        
                        <!-- Stock -->
                        <div>
                            <label class="block text-sm font-medium mb-1">
                                Stock <span class="text-red-500">*</span>
                            </label>
                            <input type="number" 
                                   x-model="form.stock"
                                   @input="validateField('stock')"
                                   class="w-full border rounded-lg px-3 py-2"
                                   :class="{'border-red-500': errors.stock}">
                            <p x-show="errors.stock" x-text="errors.stock" class="text-red-500 text-xs mt-1"></p>
                            <p x-show="form.stock < 5 && form.stock > 0" class="text-yellow-500 text-xs mt-1">
                                ⚠️ Stock faible
                            </p>
                        </div>
                    </div>
                </div>
                
                <!-- Livraison -->
                <div>
                    <h2 class="text-lg font-semibold mb-4">Livraison</h2>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- Poids -->
                        <div>
                            <label class="block text-sm font-medium mb-1">Poids (kg)</label>
                            <input type="number" 
                                   x-model="form.weight"
                                   step="0.1"
                                   class="w-full border rounded-lg px-3 py-2">
                            <p class="text-xs text-gray-500 mt-1">Utilisé pour calculer les frais de port</p>
                        </div>
                        
                        <!-- Dimensions -->
                        <div>
                            <label class="block text-sm font-medium mb-1">Dimensions (L x l x h cm)</label>
                            <input type="text" 
                                   x-model="form.dimensions"
                                   placeholder="30 x 20 x 10"
                                   class="w-full border rounded-lg px-3 py-2">
                            <p class="text-xs text-gray-500 mt-1">Format: L x l x h</p>
                        </div>
                    </div>
                </div>
                
                <!-- Images existantes -->
                <div>
                    <h2 class="text-lg font-semibold mb-4">Images actuelles</h2>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
                        {% for image in product.images %}
                            <div class="relative group" x-data="{ showDelete: false }">
                                <img src="{{ asset('uploads/products/' ~ image) }}" 
                                     class="w-full h-32 object-cover rounded-lg">
                                <button type="button" 
                                        @click="deleteExistingImage('{{ image }}')"
                                        class="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center opacity-0 group-hover:opacity-100 transition">
                                    <i class="fas fa-times text-xs"></i>
                                </button>
                                <input type="hidden" name="existing_images[]" value="{{ image }}">
                            </div>
                        {% endfor %}
                    </div>
                </div>
                
                <!-- Nouvelles images -->
                <div>
                    <h2 class="text-lg font-semibold mb-4">Ajouter des images</h2>
                    
                    <!-- Zone de drop -->
                    <div @dragover.prevent="dragover = true"
                         @dragleave.prevent="dragover = false"
                         @drop.prevent="handleDrop"
                         @click="$refs.fileInput.click()"
                         class="border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition"
                         :class="{'border-primary-500 bg-primary-50': dragover, 'border-gray-300 hover:border-primary-500': !dragover}">
                        <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-2"></i>
                        <p class="text-gray-600">Glissez-déposez vos images ici ou cliquez pour sélectionner</p>
                        <p class="text-xs text-gray-400 mt-1">PNG, JPG, JPEG jusqu'à 5MB</p>
                        <input type="file" 
                               x-ref="fileInput"
                               @change="handleFileSelect"
                               multiple 
                               accept="image/*" 
                               class="hidden">
                    </div>
                    
                    <!-- Aperçu des nouvelles images -->
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-4">
                        <template x-for="(image, index) in newImages" :key="index">
                            <div class="relative group">
                                <img :src="image.preview" class="w-full h-32 object-cover rounded-lg">
                                <button type="button" 
                                        @click="removeNewImage(index)"
                                        class="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center opacity-0 group-hover:opacity-100 transition">
                                    <i class="fas fa-times text-xs"></i>
                                </button>
                            </div>
                        </template>
                    </div>
                    
                    <p x-show="errors.images" x-text="errors.images" class="text-red-500 text-xs mt-2"></p>
                </div>
                
                <!-- Attributs -->
                <div>
                    <div class="flex justify-between items-center mb-4">
                        <h2 class="text-lg font-semibold">Attributs</h2>
                        <button type="button" 
                                @click="addAttribute"
                                class="text-primary-600 hover:text-primary-700">
                            <i class="fas fa-plus mr-1"></i> Ajouter un attribut
                        </button>
                    </div>
                    
                    <div class="space-y-2">
                        <template x-for="(attr, index) in attributes" :key="index">
                            <div class="flex gap-2">
                                <input type="text" 
                                       x-model="attr.name"
                                       placeholder="Nom (ex: Couleur)"
                                       class="flex-1 border rounded-lg px-3 py-2">
                                <input type="text" 
                                       x-model="attr.value"
                                       placeholder="Valeur (ex: Rouge)"
                                       class="flex-1 border rounded-lg px-3 py-2">
                                <button type="button" 
                                        @click="removeAttribute(index)"
                                        class="text-red-500 hover:text-red-700 px-3">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </template>
                    </div>
                </div>
                
                <!-- Statut du produit -->
                <div>
                    <h2 class="text-lg font-semibold mb-4">Statut</h2>
                    <label class="flex items-center">
                        <input type="checkbox" 
                               x-model="form.isActive"
                               class="mr-2">
                        <span>Produit actif (visible dans la boutique)</span>
                    </label>
                </div>
                
                <!-- Boutons d'action -->
                <div class="bg-gray-50 -mx-6 -mb-6 px-6 py-4 flex justify-end space-x-3 rounded-b-lg">
                    <button type="button" 
                            onclick="window.history.back()"
                            class="px-4 py-2 border rounded-lg hover:bg-gray-100 transition">
                        Annuler
                    </button>
                    <button type="submit" 
                            :disabled="!isValid || isSubmitting"
                            class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fas fa-spinner fa-spin mr-2" x-show="isSubmitting" x-cloak></i>
                        <span x-show="!isSubmitting">Mettre à jour</span>
                        <span x-show="isSubmitting">Mise à jour...</span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function productForm() {
        return {
            // Données initiales du produit
            productId: {{ product.id }},
            
            // Formulaire
            form: {
                name: '{{ product.name|escape('js') }}',
                category: '{{ product.category ? product.category.id : '' }}',
                description: '{{ product.description|escape('js') }}',
                price: '{{ product.price }}',
                compareAtPrice: '{{ product.compareAtPrice }}',
                stock: '{{ product.stock }}',
                weight: '{{ product.weight ?? '' }}',
                dimensions: '{{ product.dimensions ?? '' }}',
                isActive: {{ product.isActive ? 'true' : 'false' }}
            },
            
            // État
            newImages: [],
            attributes: [],
            imagesToDelete: [],
            isSubmitting: false,
            dragover: false,
            
            // Validation
            errors: {
                global: '',
                name: '',
                category: '',
                description: '',
                price: '',
                stock: '',
                images: ''
            },
            
            valid: {
                name: true,
                category: true,
                description: true,
                price: true,
                stock: true
            },
            
            // Initialisation
            init() {
                // Charger les attributs existants
                const existingAttributes = {{ product.attributes|json_encode|raw }};
                if (existingAttributes && existingAttributes.length > 0) {
                    this.attributes = existingAttributes;
                } else {
                    this.addAttribute();
                }
                
                // Valider les champs initiaux
                this.validateAll();
                
                // Observer les changements
                this.$watch('form', () => this.validateAll());
            },
            
            // Validation
            validateField(field) {
                switch(field) {
                    case 'name':
                        if (!this.form.name.trim()) {
                            this.errors.name = 'Le nom du produit est requis';
                            this.valid.name = false;
                        } else if (this.form.name.length < 3) {
                            this.errors.name = 'Le nom doit contenir au moins 3 caractères';
                            this.valid.name = false;
                        } else if (this.form.name.length > 255) {
                            this.errors.name = 'Le nom ne peut pas dépasser 255 caractères';
                            this.valid.name = false;
                        } else {
                            this.errors.name = '';
                            this.valid.name = true;
                        }
                        break;
                        
                    case 'category':
                        if (!this.form.category) {
                            this.errors.category = 'Veuillez sélectionner une catégorie';
                            this.valid.category = false;
                        } else {
                            this.errors.category = '';
                            this.valid.category = true;
                        }
                        break;
                        
                    case 'description':
                        if (!this.form.description.trim()) {
                            this.errors.description = 'La description est requise';
                            this.valid.description = false;
                        } else if (this.form.description.length < 20) {
                            this.errors.description = 'La description doit contenir au moins 20 caractères';
                            this.valid.description = false;
                        } else {
                            this.errors.description = '';
                            this.valid.description = true;
                        }
                        break;
                        
                    case 'price':
                        if (!this.form.price) {
                            this.errors.price = 'Le prix est requis';
                            this.valid.price = false;
                        } else if (parseFloat(this.form.price) <= 0) {
                            this.errors.price = 'Le prix doit être supérieur à 0';
                            this.valid.price = false;
                        } else {
                            this.errors.price = '';
                            this.valid.price = true;
                        }
                        break;
                        
                    case 'stock':
                        if (this.form.stock === '' || this.form.stock === null) {
                            this.errors.stock = 'Le stock est requis';
                            this.valid.stock = false;
                        } else if (parseInt(this.form.stock) < 0) {
                            this.errors.stock = 'Le stock ne peut pas être négatif';
                            this.valid.stock = false;
                        } else {
                            this.errors.stock = '';
                            this.valid.stock = true;
                        }
                        break;
                }
            },
            
            validateAll() {
                this.validateField('name');
                this.validateField('category');
                this.validateField('description');
                this.validateField('price');
                this.validateField('stock');
            },
            
            get isValid() {
                return this.valid.name && 
                       this.valid.category && 
                       this.valid.description && 
                       this.valid.price && 
                       this.valid.stock;
            },
            
            // Gestion des images
            handleFileSelect(event) {
                this.handleFiles(event.target.files);
            },
            
            handleDrop(event) {
                this.dragover = false;
                this.handleFiles(event.dataTransfer.files);
            },
            
            handleFiles(files) {
                const validTypes = ['image/jpeg', 'image/jpg', 'image/png'];
                const maxSize = 5 * 1024 * 1024;
                
                for (let file of files) {
                    if (!validTypes.includes(file.type)) {
                        this.showNotification('Format non supporté: ' + file.name, 'error');
                        continue;
                    }
                    
                    if (file.size > maxSize) {
                        this.showNotification('Fichier trop volumineux: ' + file.name, 'error');
                        continue;
                    }
                    
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        this.newImages.push({
                            file: file,
                            preview: e.target.result
                        });
                    };
                    reader.readAsDataURL(file);
                }
            },
            
            removeNewImage(index) {
                this.newImages.splice(index, 1);
            },
            
            deleteExistingImage(imageName) {
                if (confirm('Supprimer cette image ?')) {
                    this.imagesToDelete.push(imageName);
                    const element = event.target.closest('.relative');
                    if (element) element.remove();
                }
            },
            
            // Gestion des attributs
            addAttribute() {
                this.attributes.push({ name: '', value: '' });
            },
            
            removeAttribute(index) {
                this.attributes.splice(index, 1);
            },
            
            // Soumission
            async submitProduct() {
                this.validateAll();
                
                if (!this.isValid) {
                    this.showNotification('Veuillez corriger les erreurs', 'error');
                    return;
                }
                
                this.isSubmitting = true;
                this.errors.global = ''; // Reset global error
                
                const formData = new FormData();
                formData.append('name', this.form.name);
                formData.append('category', this.form.category);
                formData.append('description', this.form.description);
                formData.append('price', this.form.price);
                if (this.form.compareAtPrice) formData.append('compareAtPrice', this.form.compareAtPrice);
                formData.append('stock', this.form.stock);
                if (this.form.weight) formData.append('weight', this.form.weight);
                if (this.form.dimensions) formData.append('dimensions', this.form.dimensions);
                formData.append('isActive', this.form.isActive ? '1' : '0');
                
                // Attributs
                const validAttributes = this.attributes.filter(attr => attr.name && attr.value);
                if (validAttributes.length > 0) {
                    formData.append('attributes', JSON.stringify(validAttributes));
                }
                
                // CORRECTION: Nouvelles images - vérifier que les fichiers existent
                console.log('Nombre de nouvelles images:', this.newImages.length);
                
                for (let image of this.newImages) {
                    if (image.file instanceof File) {
                        formData.append('new_images[]', image.file); // Utiliser 'new_images[]'
                    }
                }
                
                // Images à supprimer
                for (let image of this.imagesToDelete) {
                    formData.append('delete_images[]', image);
                }
                
                // DEBUG: Afficher le contenu de FormData
                for (let pair of formData.entries()) {
                    if (pair[1] instanceof File) {
                        console.log(`${pair[0]}: ${pair[1].name} (${pair[1].size} bytes)`);
                    } else {
                        console.log(`${pair[0]}: ${pair[1]}`);
                    }
                }
                
                try {
                    const response = await fetch(`/api/vendor/products/${this.productId}`, {
                        method: 'POST',
                        body: formData,
                        // Ne pas mettre Content-Type header, le navigateur le définira automatiquement avec le boundary
                        headers: {
                            'Accept': 'application/json'
                        }
                    });
                    
                    // Vérifier si la réponse est OK
                    if (!response.ok) {
                        const errorText = await response.text();
                        console.error('Erreur serveur:', response.status, errorText);
                        throw new Error(`Erreur ${response.status}: ${errorText}`);
                    }
                    
                    const data = await response.json();
                    
                    if (data.success) {
                        if (window.showNotification) {
                            window.showNotification('Produit mis à jour avec succès !', 'success');
                        }
                        setTimeout(() => {
                            window.location.href = '{{ path('vendor_products') }}';
                        }, 1500);
                    } else {
                        this.errors.global = data.error || 'Erreur lors de la mise à jour';
                        if (window.showNotification) {
                            window.showNotification(this.errors.global, 'error');
                        }
                    }
                } catch (error) {
                    console.error('Error:', error);
                    this.errors.global = 'Erreur de connexion: ' + error.message;
                    if (window.showNotification) {
                        window.showNotification(this.errors.global, 'error');
                    }
                } finally {
                    this.isSubmitting = false;
                }
            },
            
            showNotification(message, type) {
                if (window.showNotification) {
                    window.showNotification(message, type);
                } else {
                    alert(message);
                }
            }
        }
    }
</script>

<style>
    [x-cloak] { display: none !important; }
    
    input:focus, textarea:focus, select:focus {
        outline: none;
        ring: 2px solid #3b82f6;
    }
</style>
{% endblock %}