@extends('layouts.app')

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

@section('content')

<script>
    window.__fournisseursData = @json($fournisseurs);
    window.fournisseurManager = function(paginator) {
        const p = paginator && typeof paginator === 'object' && 'data' in paginator ? paginator : {
            data: []
        };
        return {
            showModal: false
            , showDeleteModal: false
            , deleteIndex: null
            , deleteLabel: ''
            , editingIndex: null
            , fournisseurs: p.data || []
            , form: {
                nom: ''
                , adresse: ''
                , email: ''
                , contact: ''
            }
            , formatPrice(n) {
                return new Intl.NumberFormat('fr-FR').format(n) + ' FCFA';
            }
            , openModal() {
                this.editingIndex = null;
                this.form = {
                    nom: ''
                    , adresse: ''
                    , email: ''
                    , contact: ''
                };
                this.showModal = true;
            }
            , editFournisseur(i) {
                this.editingIndex = i;
                this.form = {
                    ...this.fournisseurs[i]
                };
                this.showModal = true;
            }
            , openDeleteModal(i) {
                this.deleteIndex = i;
                this.deleteLabel = this.fournisseurs[i].nom;
                this.showDeleteModal = true;
            }
            , confirmDelete() {
                if (this.deleteIndex === null) return;
                const c = this.fournisseurs[this.deleteIndex];
                const id = c.hash_id || c.id;
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '{{ url('fournisseurs') }}/' + id;
                const token = document.querySelector('meta[name="csrf-token"]') ?.content || '';
                form.innerHTML = '<input type="hidden" name="_token" value="' + token + '"><input type="hidden" name="_method" value="DELETE">';
                document.body.appendChild(form);
                form.submit();
            }
        };
    };

</script>


<div x-data="fournisseurManager(__fournisseursData)">
    <x-page-card title="Liste des fournisseurs" :action="$roleAllowsCreateEdit ? 'openModal()' : null" :actionLabel="$roleAllowsCreateEdit ? 'Nouveau fournisseur' : null">
        <div class="overflow-x-auto -mx-4 sm:mx-0">
            <table class="min-w-full divide-y divide-slate-200">
                <thead>
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Nom</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Contact</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Email</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Adresse</th>
                        <th class="px-4 py-3 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider w-24">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    @forelse($fournisseurs as $index => $fournisseur)
                    <tr class="hover:bg-slate-50/50 transition-colors">
                        <td class="px-4 py-3 font-medium text-slate-800">{{ $fournisseur->nom }}</td>
                        <td class="px-4 py-3 text-slate-600">{{ $fournisseur->contact }}</td>
                        <td class="px-4 py-3 text-slate-600">{{ $fournisseur->email }}</td>
                        <td class="px-4 py-3 text-slate-600">{{ $fournisseur->adresse ?? '-' }}</td>
                        <td class="px-4 py-3">
                            @php $canEditThis = $roleAllowsCreateEdit && (!$isVendeur || (auth()->id() == $fournisseur->user_id)); $canDeleteThis = !$isVendeur || (auth()->id() == $fournisseur->user_id); @endphp
                            <x-action-buttons :editAction="$canEditThis ? 'editFournisseur(' . $index . ')' : null" :deleteAction="$canDeleteThis ? 'openDeleteModal(' . $index . ')' : null" />
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="6" class="px-4 py-8 text-center text-slate-500">Aucun fournisseur.</td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        @if($fournisseurs->total() > 0)
        <div class="mt-4 flex flex-col sm:flex-row items-center justify-between gap-3 border-t border-slate-200 pt-4">
            <p class="text-sm text-slate-500">
                Affichage de <span class="font-medium">{{ $fournisseurs->firstItem() }}</span> à <span class="font-medium">{{ $fournisseurs->lastItem() }}</span> sur <span class="font-medium">{{ $fournisseurs->total() }}</span> fournisseurs
            </p>
            @if($fournisseurs->hasPages())
            <div class="flex gap-3">
                @if($fournisseurs->onFirstPage())
                <span class="px-4 py-2 text-slate-400 text-sm cursor-not-allowed">Précédent</span>
                @else
                <a href="{{ $fournisseurs->previousPageUrl() }}" class="px-4 py-2 text-blue-600 hover:text-blue-700 text-sm font-medium rounded-lg hover:bg-blue-50 transition-colors">Précédent</a>
                @endif
                <span class="px-2 py-2 text-slate-600 text-sm">Page {{ $fournisseurs->currentPage() }} / {{ $fournisseurs->lastPage() }}</span>
                @if($fournisseurs->hasMorePages())
                <a href="{{ $fournisseurs->nextPageUrl() }}" class="px-4 py-2 text-blue-600 hover:text-blue-700 text-sm font-medium rounded-lg hover:bg-blue-50 transition-colors">Suivant</a>
                @else
                <span class="px-4 py-2 text-slate-400 text-sm cursor-not-allowed">Suivant</span>
                @endif
            </div>
            @endif
        </div>
        @endif
    </x-page-card>

    <div x-show="showModal" x-cloak class="fixed inset-0 z-50 overflow-y-auto">
        <div class="flex min-h-screen items-center justify-center p-4">
            <div x-show="showModal" @click="showModal = false" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm"></div>
            <div x-show="showModal" x-transition:enter="ease-out duration-200" x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100" class="relative bg-white rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden">
                <div class="px-6 py-5 border-b border-slate-100 bg-gradient-to-b from-slate-50 to-white">
                    <h3 class="text-lg font-semibold text-slate-800" x-text="editingIndex === null ? 'Nouveau fournisseur' : 'Modifier le fournisseur'"></h3>
                </div>
                <form :action="editingIndex !== null ? '{{ url('fournisseurs') }}/' + (fournisseurs[editingIndex].hash_id || fournisseurs[editingIndex].id) : '{{ route('fournisseurs.store') }}'" method="POST" class="p-6 space-y-5">
                    @csrf
                    <template x-if="editingIndex !== null">
                        <input type="hidden" name="_method" value="PUT">
                    </template>
                    <x-form-group label="Nom / Entreprise" :required="true">
                        <input type="text" name="nom" x-model="form.nom" required class="form-input" placeholder="Ex: Distrib SA">
                    </x-form-group>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <x-form-group label="Téléphone" :required="true">
                            <input type="tel" name="contact" x-model="form.contact" required class="form-input" placeholder="+225 27 00 00 00 00">
                        </x-form-group>
                        <x-form-group label="Email">
                            <input type="email" name="email" x-model="form.email" class="form-input" placeholder="contact@entreprise.ci">
                        </x-form-group>
                    </div>
                    <x-form-group label="Adresse">
                        <input type="text" name="adresse" x-model="form.adresse" class="form-input" placeholder="Ex: Zone 4, Abidjan">
                    </x-form-group>
                    <div class="flex gap-3 pt-2">
                        <button type="submit" class="form-btn-primary flex-1">
                            Enregistrer
                        </button>
                        <button type="button" @click="showModal = false" class="form-btn-secondary">Annuler</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <x-delete-modal>
        Êtes-vous sûr de vouloir supprimer « <span x-text="deleteLabel"></span> » ? Cette action est irréversible.
    </x-delete-modal>
</div>
@endsection
