@extends('layouts.app')

@section('title', 'Mouvements de Stock')
@section('page-title', 'Mouvements de Stock')

@section('content')
<div class="space-y-6">
    <!-- En-tête -->
    <div class="flex justify-between items-center flex-wrap gap-3">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">Mouvements</h1>
            <p class="mt-1 text-sm text-gray-600">Suivez les entrées et sorties de stock</p>
        </div>
        <div class="flex items-center gap-3">
            @if(auth()->user()->hasPermissionTo('movement_stocks.create'))
            <button type="button" data-modal-toggle="modal-movement-in" class="inline-flex items-center px-5 py-2.5 bg-green-600 hover:bg-green-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>
                Entrée
            </button>
            @endif
            @if((auth()->user()->hasPermissionTo('movement_stocks.create') || auth()->user()->hasPermissionTo('movement_stocks.execute_sortie')) && !auth()->user()->hasRole('Magasinier'))
            <button type="button" data-modal-toggle="modal-movement-out" class="inline-flex items-center px-5 py-2.5 bg-red-600 hover:bg-red-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="M20 12H4" />
                </svg>
                Sortie
            </button>
            @endif
            @if(auth()->user()->hasPermissionTo('movement_stocks.view'))
            <a href="{{ route('movements.export', array_merge(request()->query(), ['tab' => $tab ?? 'sortie'])) }}" class="inline-flex items-center px-4 py-2.5 bg-green-600 hover:bg-green-700 text-white font-medium rounded-lg transition-colors">
                <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                </svg>
                Exporter
            </a>
            @endif
        </div>
    </div>

    @if(auth()->user()->hasPermissionTo('movement_stocks.create'))
    <x-modal-form id="modal-movement-in" title="Entrée de stock">
        @include('components.modals.movement-in', ['modalId' => 'modal-movement-in', 'departments' => $departments ?? [], 'products' => $products ?? []])
    </x-modal-form>
    @endif
    @if((auth()->user()->hasPermissionTo('movement_stocks.create') || auth()->user()->hasPermissionTo('movement_stocks.execute_sortie')) && !auth()->user()->hasRole('Magasinier'))
    <x-modal-form id="modal-movement-out" title="Sortie de stock">
        @include('components.modals.movement-out', ['modalId' => 'modal-movement-out', 'departments' => $departments ?? [], 'products' => $products ?? []])
    </x-modal-form>
    @endif

    @php
    $currentTab = $tab ?? 'sortie';
    $tabUrl = fn($t) => route('movements.index', array_filter(array_merge(request()->query(), ['tab' => $t]), fn($v) => $v !== null && $v !== ''));
    @endphp

    <!-- Filtres -->
    <div class="bg-white shadow-sm border border-gray-200 rounded-xl p-4">
        <form method="GET" action="{{ route('movements.index') }}" class="flex flex-wrap items-end gap-4">
            <input type="hidden" name="tab" value="{{ $currentTab }}">
            <div class="flex-1 min-w-[200px]">
                <label class="block text-xs font-medium text-gray-600 mb-1">Département</label>
                @php
                $departmentFilterOptions = collect([['id' => '', 'name' => 'Tous les départements']])->merge(($departments ?? collect())->map(fn($d) => ['id' => $d->id, 'name' => $d->name]));
                @endphp
                <x-searchable-select name="department_id" :options="$departmentFilterOptions" :selected="request('department_id') ?? $departmentId ?? ''" placeholder="Tous les départements" searchPlaceholder="Rechercher un département..." :required="false" :inputClass="'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 class="w-[160px]">
                <label class="block text-xs font-medium text-gray-600 mb-1">Date début</label>
                <input type="date" name="date_from" value="{{ request('date_from') ?? ($dateFrom ?? '') }}" 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 class="w-[160px]">
                <label class="block text-xs font-medium text-gray-600 mb-1">Date fin</label>
                <input type="date" name="date_to" value="{{ request('date_to') ?? ($dateTo ?? '') }}" 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 class="flex gap-2 shrink-0">
                <button type="submit" class="px-5 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors whitespace-nowrap">
                    Filtrer
                </button>
                @if(request()->hasAny(['department_id', 'date_from', 'date_to']) || ($departmentId ?? null) || ($dateFrom ?? null) || ($dateTo ?? null))
                <a href="{{ route('movements.index', ['tab' => $currentTab]) }}" class="px-5 py-2.5 border border-gray-200 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors whitespace-nowrap">
                    Effacer
                </a>
                @endif
            </div>
        </form>
    </div>

    <!-- Onglets Entrée / Sortie / Historique -->
    <div class="border-b border-gray-200">
        <nav class="-mb-px flex space-x-8">
            <a href="{{ $tabUrl('entree') }}" class="border-b-2 py-4 px-1 text-sm font-medium transition-colors flex items-center gap-1.5 {{ $currentTab === 'entree' ? 'border-green-600 text-green-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">
                Entrées
                <span class="inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 rounded-full text-xs font-semibold {{ $currentTab === 'entree' ? 'bg-green-100 text-green-800' : 'bg-green-100 text-green-700' }}">{{ $countEntree ?? 0 }}</span>
            </a>
            <a href="{{ $tabUrl('sortie') }}" class="border-b-2 py-4 px-1 text-sm font-medium transition-colors flex items-center gap-1.5 {{ $currentTab === 'sortie' ? 'border-red-600 text-red-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">
                Sorties
                <span class="inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 rounded-full text-xs font-semibold {{ $currentTab === 'sortie' ? 'bg-red-100 text-red-800' : 'bg-red-100 text-red-700' }}">{{ $countSortie ?? 0 }}</span>
            </a>
            <a href="{{ $tabUrl('historique') }}" class="border-b-2 py-4 px-1 text-sm font-medium transition-colors {{ $currentTab === 'historique' ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">
                Historique
            </a>
        </nav>
    </div>

    @if($currentTab === 'sortie' && ($validatedRequests ?? collect())->isNotEmpty())
    <!-- Demandes validées en attente d'exécution -->
    <div class="bg-white shadow-sm border border-gray-200 rounded-xl overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200 bg-amber-50">
            <h2 class="text-sm font-semibold text-amber-800">Demandes validées à exécuter</h2>
            @if((auth()->user()->hasPermissionTo('movement_stocks.create') || auth()->user()->hasPermissionTo('movement_stocks.execute_sortie')) && !auth()->user()->hasRole('Magasinier'))
            <p class="text-xs text-amber-700 mt-0.5">Cliquez sur « Exécuter la sortie » pour pré-remplir le formulaire</p>
            @endif
        </div>
        <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-3 text-left text-xs font-semibold text-gray-700 uppercase">Référence</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Département</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Produit</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Quantité</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Date validation</th>
                        @if((auth()->user()->hasPermissionTo('movement_stocks.create') || auth()->user()->hasPermissionTo('movement_stocks.execute_sortie')) && !auth()->user()->hasRole('Magasinier'))
                        <th class="px-6 py-3 text-right text-xs font-semibold text-gray-700 uppercase">Actions</th>
                        @endif
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    @foreach($validatedRequests as $req)
                    @php
                    $detail = $req->requestDetails->first();
                    $product = $detail?->product;
                    $productStock = $product ? (int)($product->stocks()->sum('actual_quantity')) : 0;
                    $qty = $detail?->quantity ?? 0;
                    $stockOk = $productStock >= $qty;
                    @endphp
                    <tr class="hover:bg-gray-50 transition-colors {{ !$stockOk ? 'bg-red-50' : '' }}">
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ $req->reference ?? '-' }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{{ $req->department?->name ?? '-' }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{{ $product?->name ?? '-' }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{{ $qty }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{{ $req->approved_at?->format('d/m/Y') ?? '-' }}</td>
                        @if((auth()->user()->hasPermissionTo('movement_stocks.create') || auth()->user()->hasPermissionTo('movement_stocks.execute_sortie')) && !auth()->user()->hasRole('Magasinier'))
                        <td class="px-6 py-4 whitespace-nowrap text-right">
                            @if($stockOk)
                            <button type="button" class="btn-execute-sortie inline-flex items-center px-3 py-1.5 text-xs font-medium rounded-lg bg-red-600 hover:bg-red-700 text-white transition-colors" data-request-id="{{ $req->id }}" data-department-id="{{ $req->department_id }}" data-department-name="{{ e($req->department?->name ?? '') }}" data-product-id="{{ $detail?->product_id ?? 0 }}" data-product-name="{{ e($product?->name ?? '') }}" data-quantity="{{ $qty }}">
                                Exécuter la sortie
                            </button>
                            @else
                            <span class="text-xs text-red-600 font-medium" title="Stock insuffisant ({{ $productStock }} disponible)">Stock insuffisant</span>
                            @endif
                        </td>
                        @endif
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
    @endif

    <!-- Tableau des mouvements -->
    <div class="bg-white shadow-sm border border-gray-200 rounded-xl overflow-hidden">
        @if($currentTab === 'historique')
        <div class="px-6 py-4 border-b border-gray-200 bg-blue-50">
            <h2 class="text-sm font-semibold text-blue-800">Tous les mouvements (entrées et sorties)</h2>
        </div>
        @endif
        <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">Réf.</th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Date de sortie</th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Type</th>
                        <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">Quantité</th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Département</th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Validateur</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    @forelse($movements ?? [] as $m)
                    <tr class="hover:bg-blue-50/50 transition-colors">
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ $m->reference ?? '-' }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{{ $m->created_at?->format('d/m/Y H:i') ?? '-' }}</td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            @php
                            $typeLabels = ['entree' => 'Entrée', 'sortie' => 'Sortie', 'transfert' => 'Transfert', 'perte' => 'Perte', 'endommagement' => 'Endommagement', 'expiration' => 'Expiration'];
                            @endphp
                            <span class="inline-flex px-2 py-0.5 rounded text-xs font-medium {{ $m->type === 'entree' ? 'bg-green-100 text-green-800' : ($m->type === 'sortie' ? 'bg-red-100 text-red-800' : 'bg-gray-100 text-gray-800') }}">
                                {{ $typeLabels[$m->type] ?? $m->type }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{{ $m->product?->name ?? '-' }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{{ $m->quantity }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">{{ $m->department?->name ?? '-' }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{{ $m->user?->full_name ?? '-' }}</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="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
                                </svg>
                                <p class="text-sm font-medium text-gray-600 mb-1">Aucun mouvement enregistré</p>
                            </div>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        @if(isset($movements) && $movements->hasPages())
        <div class="px-6 py-4 border-t border-gray-200">
            {{ $movements->links() }}
        </div>
        @endif
    </div>
</div>

@if((auth()->user()->hasPermissionTo('movement_stocks.create') || auth()->user()->hasPermissionTo('movement_stocks.execute_sortie')) && session('error') && old('product_id'))
<script>
    document.addEventListener('DOMContentLoaded', function() {
        if (typeof openModal === 'function') openModal('modal-movement-out');
    });
</script>
@endif

<script>
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('.btn-execute-sortie').forEach(function(btn) {
            btn.addEventListener('click', function() {
                var form = document.getElementById('sortie-form');
                if (!form) return;

                var requestId = btn.dataset.requestId;
                var departmentId = btn.dataset.departmentId;
                var departmentName = btn.dataset.departmentName || 'Choisir un département';
                var productId = btn.dataset.productId;
                var productName = btn.dataset.productName || 'Choisir un produit';
                var quantity = btn.dataset.quantity;

                form.action = '{{ route("movements.store.sortie") }}';
                form.querySelector('input[name="request_id"]').value = requestId || '';
                form.querySelector('input[name="product_id"]').value = productId || '';
                form.querySelector('input[name="quantity"]').value = quantity || '';
                form.querySelector('input[name="department_id"]').value = departmentId || '';
                form.querySelector('textarea[name="notes"]').value = '';

                var productContainer = form.querySelector('.searchable-select-product');
                var deptContainer = form.querySelector('.searchable-select-department');
                if (productContainer) {
                    productContainer.dataset.selectedId = productId;
                    productContainer.dataset.selectedName = productName;
                    var pl = productContainer.querySelector('.searchable-select-label');
                    if (pl) pl.textContent = productName;
                }
                if (deptContainer) {
                    deptContainer.dataset.selectedId = departmentId;
                    deptContainer.dataset.selectedName = departmentName;
                    var dl = deptContainer.querySelector('.searchable-select-label');
                    if (dl) dl.textContent = departmentName;
                }

                if (typeof openModal === 'function') openModal('modal-movement-out');
            });
        });
    });

</script>
@endsection
