@extends('layouts.app')

@section('title', 'Demandes')
@section('page-title', 'Demandes')

@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">Demandes</h1>
            <p class="mt-1 text-sm text-gray-600">Gérez les demandes d'approvisionnement et de transfert</p>
        </div>
        <button type="button" data-modal-toggle="modal-new-request" 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>
            Nouvelle demande
        </button>
    </div>

    <x-modal-form id="modal-new-request" title="Nouvelle demande">
        @include('components.modals.request', ['modalId' => 'modal-new-request', 'departments' => $departments ?? [], 'products' => $products ?? []])
    </x-modal-form>

    <!-- Onglets de statut -->
    <div class="border-b border-gray-200">
        <nav class="-mb-px flex space-x-12">
            <button class="border-b-2 border-blue-600 text-blue-600 py-4 px-3 text-sm font-semibold">
                Toutes
            </button>
            <button class="border-b-2 border-transparent text-gray-600 hover:text-gray-900 hover:border-gray-300 py-4 px-3 text-sm font-medium transition-colors">
                En attente
            </button>
            <button class="border-b-2 border-transparent text-gray-600 hover:text-gray-900 hover:border-gray-300 py-4 px-3 text-sm font-medium transition-colors">
                Validées
            </button>
            <button class="border-b-2 border-transparent text-gray-600 hover:text-gray-900 hover:border-gray-300 py-4 px-3 text-sm font-medium transition-colors">
                Rejetées
            </button>
        </nav>
    </div>

    <!-- Filtres -->
    <div class="bg-white shadow-sm border border-gray-200 rounded-xl p-4">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
                <input type="text" placeholder="Rechercher..." 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 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>Tous les départements</option>
                </select>
            </div>
            <div>
                <input type="date" 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>
    </div>

    <!-- Tableau des demandes -->
    <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">
                            N° Demande
                        </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">
                            Date
                        </th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                            Produits
                        </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">
                            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($demandes as $demande)
                    <tr class="hover:bg-blue-50/50 transition-colors">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm font-medium text-gray-900">{{ $demande->reference ?? '-' }}</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm text-gray-700">{{ $demande->department?->name ?? '-' }}</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="text-sm text-gray-600">{{ $demande->created_at?->format('d/m/Y') ?? '-' }}</span>
                        </td>
                        <td class="px-6 py-4">
                            <span class="text-sm text-gray-700">
                                @foreach($demande->requestDetails as $detail)
                                {{ $detail->product?->name ?? '-' }}
                                @if(!$loop->last) · @endif
                                @endforeach
                                @if($demande->requestDetails->isEmpty())
                                -
                                @endif
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            @php
                            $statusLabels = [
                            'en_attente' => 'En attente',
                            'validée' => 'Validée',
                            'rejetée' => 'Rejetée',
                            ];
                            $statusClasses = [
                            'en_attente' => 'bg-amber-100 text-amber-800',
                            'validée' => 'bg-green-100 text-green-800',
                            'rejetée' => 'bg-red-100 text-red-800',
                            ];
                            @endphp
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {{ $statusClasses[$demande->status] ?? 'bg-gray-100 text-gray-800' }}">
                                {{ $statusLabels[$demande->status] ?? $demande->status }}
                            </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($demande->status === 'en_attente')
                                @can('update', $demande)
                                <button type="button" data-id="{{ $demande->id }}" data-department-id="{{ $demande->department_id }}" data-department-name="{{ e($demande->department?->name ?? '') }}" data-product-id="{{ $demande->requestDetails->first()?->product_id }}" data-product-name="{{ e($demande->requestDetails->first()?->product?->name ?? '') }}" data-quantity="{{ $demande->requestDetails->first()?->quantity }}" data-comments="{{ e($demande->comments ?? '') }}" onclick="openEditRequestModal(this)" 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('approve', $demande)
                                <form method="POST" action="{{ route('requests.approve', $demande) }}" class="inline-block">
                                    @csrf
                                    <button type="submit" class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-gradient-to-br from-green-50 to-green-100 text-green-600 hover:from-green-500 hover:to-green-600 hover:text-white transform hover:scale-110 transition-all duration-200 shadow-sm hover:shadow-md" title="Approuver">
                                        <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="M5 13l4 4L19 7" />
                                        </svg>
                                    </button>
                                </form>
                                @endcan
                                @can('reject', $demande)
                                <form method="POST" action="{{ route('requests.reject', $demande) }}" class="inline-block">
                                    @csrf
                                    <button type="submit" class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-gradient-to-br from-red-50 to-red-100 text-red-600 hover:from-red-500 hover:to-red-600 hover:text-white transform hover:scale-110 transition-all duration-200 shadow-sm hover:shadow-md" title="Rejeter">
                                        <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="M6 18L18 6M6 6l12 12" />
                                        </svg>
                                    </button>
                                </form>
                                @endcan
                                @endif
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr class="hover:bg-blue-50/50 transition-colors">
                        <td colspan="6" 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="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                </svg>
                                <p class="text-sm font-medium text-gray-600 mb-1">Aucune demande enregistrée</p>
                            </div>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        @if($demandes->hasPages())
        <div class="px-6 py-4 border-t border-gray-200">
            {{ $demandes->links() }}
        </div>
        @endif
    </div>
</div>

@if(auth()->user()->hasPermissionTo('requests.update'))
<x-modal-form id="modal-edit-request" title="Modifier la demande">
    <form method="POST" id="edit-request-form" class="space-y-6">
        @csrf
        @method('PUT')
        @php $inputClass = '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 transition-colors'; @endphp
        <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">Département <span class="text-red-500">*</span></label>
                <x-searchable-select name="department_id" :options="$departments ?? []" :selected="''" placeholder="Choisir un département" searchPlaceholder="Rechercher un département..." :required="true" :inputClass="$inputClass" />
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Produit <span class="text-red-500">*</span></label>
                <x-searchable-select name="product_id" :options="$products ?? []" :selected="''" placeholder="Choisir un produit" searchPlaceholder="Rechercher un produit..." :required="true" :inputClass="$inputClass" />
            </div>
        </div>
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Quantité demandée <span class="text-red-500">*</span></label>
            <input type="number" name="quantity" min="1" id="edit_quantity" class="{{ $inputClass }}" placeholder="0">
        </div>
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Commentaire</label>
            <textarea rows="3" name="comments" id="edit_comments" class="{{ $inputClass }} resize-none" placeholder="Optionnel"></textarea>
        </div>
        @include('components.modals.modal-actions', ['modalId' => 'modal-edit-request', 'submitLabel' => 'Enregistrer'])
    </form>
</x-modal-form>

<script>
    function openEditRequestModal(btn) {
        var id = btn.dataset.id;
        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 || '';
        var comments = btn.dataset.comments || '';

        var form = document.getElementById('edit-request-form');
        form.action = '{{ url("requests") }}/' + id;

        document.getElementById('edit_quantity').value = quantity;
        document.getElementById('edit_comments').value = comments;

        var deptInput = form.querySelector('input[name="department_id"]');
        var productInput = form.querySelector('input[name="product_id"]');
        if (deptInput) {
            deptInput.value = departmentId;
        }
        if (productInput) {
            productInput.value = productId;
        }

        var deptContainer = form.querySelector('input[name="department_id"]') ? .closest('.searchable-select');
        var productContainer = form.querySelector('input[name="product_id"]') ? .closest('.searchable-select');
        if (deptContainer) {
            deptContainer.dataset.selectedId = departmentId;
            deptContainer.dataset.selectedName = departmentName;
            var deptLabel = deptContainer.querySelector('.searchable-select-label');
            if (deptLabel) deptLabel.textContent = departmentName || 'Choisir un département';
            deptLabel ? .classList.toggle('text-gray-500', !departmentId);
            deptLabel ? .classList.toggle('text-gray-900', !!departmentId);
        }
        if (productContainer) {
            productContainer.dataset.selectedId = productId;
            productContainer.dataset.selectedName = productName;
            var productLabel = productContainer.querySelector('.searchable-select-label');
            if (productLabel) productLabel.textContent = productName || 'Choisir un produit';
            productLabel ? .classList.toggle('text-gray-500', !productId);
            productLabel ? .classList.toggle('text-gray-900', !!productId);
        }

        if (typeof openModal === 'function') openModal('modal-edit-request');
    }

</script>
@endif
@endsection
