@extends('layouts.app')

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

@section('content')

<script>
    window.__clientsData = @json($clients);
    window.clientManager = function(paginator) {
        const p = paginator && typeof paginator === 'object' && 'data' in paginator ? paginator : {
            data: []
        };
        return {
            showModal: false
            , showDeleteModal: false
            , deleteIndex: null
            , deleteLabel: ''
            , editingIndex: null
            , clients: p.data || []
            , form: {
                nom: ''
                , adresse: ''
                , telephone: ''
                , caution: 0
            }
            , formatPrice(n) {
                return new Intl.NumberFormat('fr-FR').format(n) + ' FCFA';
            }
            , openModal() {
                this.editingIndex = null;
                this.form = {
                    nom: ''
                    , adresse: ''
                    , telephone: ''
                    , caution: 0
                };
                this.showModal = true;
            }
            , editClient(i) {
                this.editingIndex = i;
                this.form = {
                    ...this.clients[i]
                };
                this.showModal = true;
            }
            , openDeleteModal(i) {
                this.deleteIndex = i;
                this.deleteLabel = this.clients[i].nom;
                this.showDeleteModal = true;
            }
            , confirmDelete() {
                if (this.deleteIndex === null) return;
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '{{ url('
                clients ') }}/' + this.clients[this.deleteIndex].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="clientManager(__clientsData)">
    <x-page-card title="Liste des clients" action="openModal()" actionLabel="Nouveau client">
        <div class="rounded-lg border border-amber-200 bg-amber-50/50 p-4 mb-4 flex items-start gap-3">
            <div class="w-8 h-8 rounded-lg bg-amber-100 flex items-center justify-center shrink-0">
                <svg class="w-4 h-4 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
            </div>
            <p class="text-sm text-amber-800">
                <strong>Note :</strong> Lors de l'ajout d'un nouveau client, une caution (dépôt de garantie) est obligatoire.
            </p>
        </div>
        <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">Référence</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Nom complet</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Téléphone</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-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Caution</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($clients as $index => $client)
                    <tr class="hover:bg-slate-50/50 transition-colors">
                        <td class="px-4 py-3 text-slate-600">{{ $client->reference }}</td>
                        <td class="px-4 py-3 font-medium text-slate-800">{{ $client->nom }}</td>
                        <td class="px-4 py-3 text-slate-600">{{ $client->telephone }}</td>
                        <td class="px-4 py-3 text-slate-600">{{ $client->adresse ?? '-' }}</td>
                        <td class="px-4 py-3">
                            <span class="font-semibold text-emerald-600">{{ number_format($client->caution, 0, ',', ' ') }} FCFA</span>
                        </td>
                        <td class="px-4 py-3">
                            <x-action-buttons :viewUrl="route('clients.show', $client->hashId)" :editAction="'editClient(' . $index . ')'" :deleteAction="'openDeleteModal(' . $index . ')'" />
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="6" class="px-4 py-8 text-center text-slate-500">Aucun client.</td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        @if($clients->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">{{ $clients->firstItem() }}</span> à <span class="font-medium">{{ $clients->lastItem() }}</span> sur <span class="font-medium">{{ $clients->total() }}</span> clients
            </p>
            @if($clients->hasPages())
            <div class="flex gap-3">
                @if($clients->onFirstPage())
                <span class="px-4 py-2 text-slate-400 text-sm cursor-not-allowed">Précédent</span>
                @else
                <a href="{{ $clients->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 {{ $clients->currentPage() }} / {{ $clients->lastPage() }}</span>
                @if($clients->hasMorePages())
                <a href="{{ $clients->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>

    {{-- Modal création / modification --}}
    <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" @click.stop 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 client' : 'Modifier le client'"></h3>
                    <p class="text-sm text-slate-500 mt-1" x-show="editingIndex === null">Une caution est requise pour tout nouveau client.</p>
                </div>
                <form :action="editingIndex !== null ? '{{ url('clients') }}/' + clients[editingIndex].id : '{{ route('clients.store') }}'" method="POST" class="p-6 space-y-6">
                    @csrf
                    <template x-if="editingIndex !== null">
                        <input type="hidden" name="_method" value="PUT">
                    </template>
                    @if($errors->any())
                    <div class="p-3 rounded-lg bg-red-50 text-red-700 text-sm">
                        @foreach($errors->all() as $error)
                        <p>{{ $error }}</p>
                        @endforeach
                    </div>
                    @endif
                    <div>
                        <div class="flex items-center gap-2 mb-4">
                            <div class="h-px flex-1 bg-slate-200"></div>
                            <span class="text-xs font-semibold text-slate-500 uppercase tracking-wider">Informations client</span>
                            <div class="h-px flex-1 bg-slate-200"></div>
                        </div>
                        <div class="space-y-4">
                            <x-form-group label="Nom complet" :required="true">
                                <input type="text" name="nom" x-model="form.nom" required class="form-input" placeholder="Ex: Jean Dupont">
                            </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="telephone" x-model="form.telephone" required class="form-input" placeholder="+225 07 00 00 00 00">
                                </x-form-group>
                                <x-form-group label="Adresse">
                                    <input type="text" name="adresse" x-model="form.adresse" class="form-input" placeholder="Ex: Cocody, Abidjan">
                                </x-form-group>
                            </div>
                            <x-form-group label="Caution (FCFA)" help="Obligatoire pour un nouveau client">
                                <input type="number" name="caution" x-model="form.caution" min="0" required class="form-input" placeholder="0">
                            </x-form-group>
                        </div>
                    </div>
                    <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> » ? La caution devra être remboursée. Cette action est irréversible.
    </x-delete-modal>
</div>
@endsection
