@extends('layouts.admin')

@section('title', 'Créer Produit')
@section('page-title', 'Créer un Produit')

@section('content')
<div class="card">
    <div class="card-header bg-white">
        <h5 class="mb-0"><i class="bi bi-plus-circle me-2"></i>Nouveau Produit</h5>
    </div>
    <div class="card-body">
        @if ($errors->any())
            <div class="alert alert-danger">
                <strong><i class="bi bi-exclamation-triangle me-2"></i>Erreurs de validation:</strong>
                <ul class="mb-0 mt-2">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <form action="{{ route('admin.products.store') }}" method="POST" enctype="multipart/form-data" id="productForm">
            @csrf
            <div class="row">
                <div class="col-md-8">
                    <div class="mb-3">
                        <label class="form-label">Nom du Produit <span class="text-danger">*</span></label>
                        <input type="text" name="name" id="product-name" class="form-control @error('name') is-invalid @enderror" value="{{ old('name') }}" required>
                        @error('name')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                    
                    <div class="mb-3">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <label class="form-label mb-0">Description</label>
                            <button type="button" id="generate-ai-description" class="btn btn-sm btn-outline-primary">
                                <i class="bi bi-stars"></i> Générer avec IA
                            </button>
                        </div>
                        <textarea name="description" id="product-description" rows="4" class="form-control @error('description') is-invalid @enderror">{{ old('description') }}</textarea>
                        <small class="text-muted" id="ai-status"></small>
                        @error('description')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Prix (FCFA) <span class="text-danger">*</span></label>
                            <input type="number" name="price" id="product-price" class="form-control @error('price') is-invalid @enderror" value="{{ old('price') }}" min="0" required>
                            @error('price')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Stock <span class="text-danger">*</span></label>
                            <input type="number" name="stock" class="form-control @error('stock') is-invalid @enderror" value="{{ old('stock', 0) }}" min="0" required>
                            @error('stock')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Catégorie <span class="text-danger">*</span></label>
                            <select name="category_id" id="product-category" class="form-select @error('category_id') is-invalid @enderror" required>
                                <option value="">-- Sélectionner --</option>
                                @foreach($categories as $category)
                                    <option value="{{ $category->id }}" {{ old('category_id') == $category->id ? 'selected' : '' }}>
                                        {{ $category->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('category_id')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <!-- Image principale -->
                    <div class="card mb-3">
                        <div class="card-header bg-light py-2">
                            <h6 class="mb-0"><i class="bi bi-image me-2"></i>Image principale</h6>
                        </div>
                        <div class="card-body">
                            <input type="file" name="image" id="main-image" class="form-control @error('image') is-invalid @enderror" accept="image/jpeg,image/png,image/jpg,image/gif,image/webp">
                            @error('image')<div class="invalid-feedback">{{ $message }}</div>@enderror
                            <small class="text-muted d-block mt-1">Formats: JPG, PNG, GIF, WEBP. Max: 10MB</small>
                            
                            <div id="main-image-preview" class="mt-3 text-center" style="display: none;">
                                <img src="" id="main-preview-img" class="img-fluid rounded" style="max-height: 200px;">
                            </div>
                        </div>
                    </div>
                    
                    <!-- Images supplémentaires -->
                    <div class="card">
                        <div class="card-header bg-light py-2">
                            <h6 class="mb-0"><i class="bi bi-images me-2"></i>Images supplémentaires</h6>
                        </div>
                        <div class="card-body">
                            <input type="file" name="additional_images[]" id="additional-images" class="form-control @error('additional_images.*') is-invalid @enderror" accept="image/jpeg,image/png,image/jpg,image/gif,image/webp" multiple>
                            @error('additional_images.*')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                            <small class="text-muted d-block mt-1">Max 5 images, 10MB chacune</small>
                            
                            <div id="additional-images-preview" class="mt-3 row g-2"></div>
                            <div id="images-count" class="text-muted small mt-2"></div>
                        </div>
                    </div>
                </div>
            </div>
            
            <hr class="my-4">
            
            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary" id="submit-btn">
                    <i class="bi bi-check-circle me-1"></i> Créer le Produit
                </button>
                <a href="{{ route('admin.products.index') }}" class="btn btn-secondary">
                    <i class="bi bi-x-circle me-1"></i> Annuler
                </a>
            </div>
        </form>
    </div>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Variables
    let imageBase64 = null;
    const form = document.getElementById('productForm');
    const submitBtn = document.getElementById('submit-btn');
    
    // Preview image principale
    const mainImageInput = document.getElementById('main-image');
    const mainImagePreview = document.getElementById('main-image-preview');
    const mainPreviewImg = document.getElementById('main-preview-img');
    
    if (mainImageInput) {
        mainImageInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                // Validation taille
                if (file.size > 10 * 1024 * 1024) {
                    alert('L\'image principale ne doit pas dépasser 10MB');
                    this.value = '';
                    return;
                }
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    imageBase64 = e.target.result;
                    mainPreviewImg.src = e.target.result;
                    mainImagePreview.style.display = 'block';
                };
                reader.readAsDataURL(file);
            } else {
                mainImagePreview.style.display = 'none';
                imageBase64 = null;
            }
        });
    }
    
    // Preview images supplémentaires
    const additionalInput = document.getElementById('additional-images');
    const additionalPreview = document.getElementById('additional-images-preview');
    const imagesCount = document.getElementById('images-count');
    
    if (additionalInput) {
        additionalInput.addEventListener('change', function(e) {
            additionalPreview.innerHTML = '';
            const files = Array.from(e.target.files);
            
            if (files.length > 5) {
                alert('Vous ne pouvez sélectionner que 5 images supplémentaires maximum');
                this.value = '';
                imagesCount.textContent = '';
                return;
            }
            
            let validFiles = 0;
            files.forEach((file, index) => {
                if (file.size > 10 * 1024 * 1024) {
                    alert('L\'image ' + file.name + ' dépasse 10MB et sera ignorée');
                    return;
                }
                
                validFiles++;
                const reader = new FileReader();
                reader.onload = function(e) {
                    const col = document.createElement('div');
                    col.className = 'col-4';
                    col.innerHTML = '<div class="position-relative">' +
                        '<img src="' + e.target.result + '" class="img-fluid rounded" style="height: 80px; width: 100%; object-fit: cover;">' +
                        '<span class="position-absolute top-0 start-0 badge bg-primary" style="font-size: 10px;">' + (index + 1) + '</span>' +
                        '</div>';
                    additionalPreview.appendChild(col);
                };
                reader.readAsDataURL(file);
            });
            
            imagesCount.textContent = validFiles > 0 ? validFiles + ' image(s) sélectionnée(s)' : '';
        });
    }
    
    // Form submission avec loading state
    if (form) {
        form.addEventListener('submit', function(e) {
            // Ne pas bloquer la soumission, juste montrer le loading
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Création en cours...';
        });
    }
    
    // AI Description Generator
    const aiBtn = document.getElementById('generate-ai-description');
    if (aiBtn) {
        aiBtn.addEventListener('click', function() {
            const name = document.getElementById('product-name').value;
            const categorySelect = document.getElementById('product-category');
            const categoryName = categorySelect.options[categorySelect.selectedIndex] ? categorySelect.options[categorySelect.selectedIndex].text : '';
            const price = document.getElementById('product-price').value;
            const descriptionField = document.getElementById('product-description');
            const statusField = document.getElementById('ai-status');
            
            if (!name) {
                alert('Veuillez d\'abord entrer le nom du produit');
                return;
            }
            
            aiBtn.disabled = true;
            aiBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Génération...';
            statusField.innerHTML = '<i class="bi bi-hourglass-split text-primary"></i> Génération en cours...';
            
            fetch('/api/test-generate-description', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    name: name,
                    category_name: categoryName !== '-- Sélectionner --' ? categoryName : null,
                    price: price,
                    image_base64: imageBase64
                })
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                if (data.success) {
                    descriptionField.value = data.description;
                    statusField.innerHTML = '<i class="bi bi-check-circle text-success"></i> Description générée avec succès';
                } else {
                    statusField.innerHTML = '<i class="bi bi-exclamation-circle text-danger"></i> ' + (data.message || 'Erreur');
                }
            })
            .catch(function(error) {
                console.error('Error:', error);
                statusField.innerHTML = '<i class="bi bi-exclamation-circle text-danger"></i> Erreur de connexion';
            })
            .finally(function() {
                aiBtn.disabled = false;
                aiBtn.innerHTML = '<i class="bi bi-stars"></i> Générer avec IA';
                setTimeout(function() { statusField.innerHTML = ''; }, 5000);
            });
        });
    }
});
</script>
@endpush
@endsection
