@extends('layouts.app')

@section('title', 'Produits & Stocks')
@section('page-title', 'Produits & Stocks')

@section('content')
<div class="space-y-6">
    <!-- En-tête -->
    <div class="flex justify-between items-center">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">Produits & Stocks</h1>
            <p class="mt-1 text-sm text-gray-600">Catalogue des produits et niveaux de stock en un seul endroit</p>
        </div>

        @if(auth()->user()->hasPermissionTo('products.create'))
        <button type="button" data-modal-toggle="modal-new-product" class="inline-flex items-center px-5 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg shadow-sm hover:shadow-md transition-all">
            <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
            </svg>
            Nouveau produit
        </button>
        @endif
    </div>

    @can('create', App\Models\Product::class)
    <x-form-modal id="modal-new-product" title="Nouveau produit et stock" action="{{ route('product-stocks.store') }}" method="POST" size="xl">
        <x-forms.product-form :categories="$categories" :units="\App\Models\Unit::orderBy('name')->get()" :suppliers="\App\Models\Supplier::orderBy('name')->get()" :showStockFields="true" />
    </x-form-modal>
    @endcan

    <!-- Filtres -->
    <div class="bg-white shadow-sm border border-gray-200 rounded-xl p-4">
        <form method="GET" action="{{ route('product-stocks.index') }}" class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div class="md:col-span-2">
                <input type="text" name="search" value="{{ request('search') }}" placeholder="Rechercher par nom ou référence..." class="w-full px-4 py-2.5 border border-gray-200 rounded-lg bg-white text-gray-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all">
            </div>
            <div>
                <select name="category_id" class="w-full px-4 py-2.5 border border-gray-200 rounded-lg bg-white text-gray-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all">
                    <option value="">Toutes les catégories</option>
                    @foreach($categories as $category)
                    <option value="{{ $category->id }}" {{ request('category_id') == $category->id ? 'selected' : '' }}>{{ $category->name }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <select name="status" class="w-full px-4 py-2.5 border border-gray-200 rounded-lg bg-white text-gray-900 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all">
                    <option value="">Tous les statuts</option>
                    <option value="actif" {{ request('status') === 'actif' ? 'selected' : '' }}>Actif</option>
                    <option value="archivé" {{ request('status') === 'archivé' ? 'selected' : '' }}>Archivé</option>
                </select>
            </div>
            <div class="md:col-span-4 flex gap-3">
                <button type="submit" class="px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors">
                    Filtrer
                </button>
                @if(request()->hasAny(['search', 'category_id', 'status']))
                <a href="{{ route('product-stocks.index') }}" class="px-4 py-2.5 border border-gray-200 rounded-lg text-gray-700 hover:bg-gray-50 font-medium transition-colors">
                    Réinitialiser
                </a>
                @endif
            </div>
        </form>
    </div>

    <!-- Tableau unifié -->
    <div class="bg-white shadow-sm border border-gray-200 rounded-xl overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Produit</th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Catégorie</th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Fournisseur</th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Unité</th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Stock</th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Statut</th>
                        <th class="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    @forelse($products as $product)
                    <tr class="hover:bg-blue-50/50 transition-colors">
                        <td class="px-6 py-4">
                            <div>
                                <div class="text-sm font-medium text-gray-900">{{ $product->name }}</div>
                                <div class="text-xs text-gray-500">{{ $product->reference ?? '-' }}</div>
                            </div>
                        </td>
                        <td class="px-6 py-4 text-sm text-gray-700">{{ $product->category?->name ?? '-' }}</td>
                        <td class="px-6 py-4 text-sm text-gray-700">{{ $product->supplier?->name ?? '-' }}</td>
                        <td class="px-6 py-4 text-sm text-gray-700">{{ $product->unit?->abbreviation ?? $product->unit?->name ?? '-' }}</td>
                        <td class="px-6 py-4">
                            @php $qty = (int) ($product->total_stock ?? 0); @endphp
                            <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium
                                {{ $qty <= 0 ? 'bg-red-100 text-red-800' : ($qty <= 10 ? 'bg-amber-100 text-amber-800' : 'bg-green-100 text-green-800') }}">
                                {{ $qty }}
                            </span>
                        </td>
                        <td class="px-6 py-4">
                            <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium {{ $product->status === 'actif' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800' }}">
                                {{ $product->status === 'actif' ? 'Actif' : 'Archivé' }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <div class="flex items-center justify-end gap-2">
                                @if(auth()->user()->hasPermissionTo('products.view') || auth()->user()->hasPermissionTo('stocks.view'))
                                <a href="{{ route('movements.index') }}?product={{ $product->id }}" class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-gray-50 text-gray-600 hover:bg-gray-500 hover:text-white transition-colors" title="Voir les mouvements">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                    </svg>
                                </a>
                                @endif
                                @can('update', $product)
                                @php $qty = (int) ($product->total_stock ?? 0); @endphp
                                <button type="button" onclick="openEditProductModal({{ $product->id }}, {{ json_encode($product->name) }}, {{ $product->category_id }}, {{ $product->supplier_id }}, {{ $product->unit_id ?? 'null' }}, {{ json_encode($product->status) }}, {{ $qty }}, {{ json_encode($product->minimum_threshold ?? '') }})" class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-gradient-to-br from-blue-50 to-blue-100 text-blue-600 hover:from-blue-500 hover:to-blue-600 hover:text-white transform hover:scale-110 transition-all duration-200 shadow-sm hover:shadow-md" title="Modifier">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                    </svg>
                                </button>
                                @endcan
                                @can('delete', $product)
                                <form method="POST" action="{{ route('product-stocks.destroy', $product) }}" class="inline-block" id="delete-form-product-{{ $product->id }}">
                                    @csrf
                                    @method('DELETE')
                                    <button type="button" onclick="openDeleteProductModal({{ $product->id }})" class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-red-50 text-red-600 hover:bg-red-500 hover:text-white transition-colors" title="Supprimer">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                        </svg>
                                    </button>
                                </form>
                                @endcan
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="7" class="px-6 py-12 text-center">
                            <div class="flex flex-col items-center">
                                <svg class="w-16 h-16 text-gray-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
                                </svg>
                                <p class="text-sm font-medium text-gray-600 mb-1">Aucun produit trouvé</p>
                                <p class="text-xs text-gray-500">Utilisez les filtres ou ajoutez un nouveau produit.</p>
                            </div>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        @if($products->hasPages())
        <div class="px-6 py-4 border-t border-gray-200">
            {{ $products->links() }}
        </div>
        @endif
    </div>
</div>

@if(auth()->user()->hasPermissionTo('products.update'))
<!-- Modal d'édition du produit -->
<x-modal-form id="modal-edit-product" title="Modifier le produit" size="xl">
    <form method="POST" id="edit-product-form" class="space-y-5">
        @csrf
        @method('PUT')
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-5">
            <div class="sm:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-2">Nom <span class="text-red-500">*</span></label>
                <input type="text" name="name" id="edit_product_name" class="w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500" required>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Catégorie <span class="text-red-500">*</span></label>
                <select name="category_id" id="edit_product_category" class="w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500" required>
                    <option value="">Choisir une catégorie</option>
                    @foreach($categories as $cat)
                    <option value="{{ $cat->id }}">{{ $cat->name }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Fournisseur <span class="text-red-500">*</span></label>
                <select name="supplier_id" id="edit_product_supplier" class="w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500" required>
                    <option value="">Choisir un fournisseur</option>
                    @foreach(\App\Models\Supplier::orderBy('name')->get() as $sup)
                    <option value="{{ $sup->id }}">{{ $sup->name }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Unité</label>
                <select name="unit_id" id="edit_product_unit" class="w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    <option value="">Choisir une unité</option>
                    @foreach(\App\Models\Unit::orderBy('name')->get() as $u)
                    <option value="{{ $u->id }}">{{ $u->name }} ({{ $u->abbreviation ?? '' }})</option>
                    @endforeach
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Statut <span class="text-red-500">*</span></label>
                <select name="status" id="edit_product_status" class="w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500" required>
                    <option value="actif">Actif</option>
                    <option value="archivé">Archivé</option>
                </select>
            </div>
        </div>
        @if(auth()->user()->hasPermissionTo('stocks.update'))
        <div class="pt-5 mt-5 border-t border-gray-200">
            <div class="flex items-center gap-2 mb-4">
                <div class="w-8 h-8 rounded-lg bg-green-100 flex items-center justify-center">
                    <svg class="w-4 h-4 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4" />
                    </svg>
                </div>
                <p class="text-sm font-semibold text-gray-700">Stock</p>
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-5">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Quantité en stock</label>
                    <input type="number" name="stock_quantity" id="edit_product_stock" min="0" class="w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500" placeholder="0">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Seuil d'alerte</label>
                    <input type="number" name="minimum_threshold" id="edit_product_threshold" min="0" class="w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500" placeholder="10">
                    <p class="mt-1 text-xs text-gray-500">Alerte quand le stock passe en dessous</p>
                </div>
            </div>
        </div>
        @endif
        @include('components.modals.modal-actions', ['modalId' => 'modal-edit-product', 'submitLabel' => 'Enregistrer'])
    </form>
</x-modal-form>
@endif

@if(auth()->user()->hasPermissionTo('products.delete'))
<x-delete-confirmation-modal modalId="delete-product-modal" title="Confirmer la suppression" message="Êtes-vous sûr de vouloir supprimer ce produit ? Les stocks associés seront également affectés." />
@endif

<script>
    function openEditProductModal(id, name, categoryId, supplierId, unitId, status, stockQty, threshold) {
        const modal = document.getElementById('modal-edit-product');
        const form = document.getElementById('edit-product-form');
        if (!modal || !form) return;
        form.action = '{{ url("/product-stocks") }}/' + id;
        document.getElementById('edit_product_name').value = name || '';
        document.getElementById('edit_product_category').value = categoryId || '';
        document.getElementById('edit_product_supplier').value = supplierId || '';
        document.getElementById('edit_product_unit').value = unitId || '';
        document.getElementById('edit_product_status').value = status || 'actif';
        var stockEl = document.getElementById('edit_product_stock');
        var thresholdEl = document.getElementById('edit_product_threshold');
        if (stockEl) stockEl.value = stockQty ? ? 0;
        if (thresholdEl) thresholdEl.value = threshold ? ? 10;
        modal.classList.remove('hidden');
        modal.classList.add('flex', 'items-center', 'justify-center');
        document.body.style.overflow = 'hidden';
    }

    function openDeleteProductModal(productId) {
        openDeleteConfirmModal('delete-product-modal', function() {
            const form = document.getElementById('delete-form-product-' + productId);
            if (form) form.submit();
        });
    }

</script>
@endsection
