@extends('layouts.app')

@section('title', 'Dépenses')
@section('page-title', 'Dépenses')

@section('content')
<script>
    window.__depensesData = @json($depenses);
    window.__magasinsData = @json($magasins);
    window.depenseManager = function(paginator, magasins) {
        const p = paginator && typeof paginator === 'object' && 'data' in paginator ? paginator : {
            data: []
        };
        const mags = magasins || [];
        return {
            showModal: false
            , showDeleteModal: false
            , deleteIndex: null
            , deleteLabel: ''
            , editingIndex: null
            , depenses: p.data || []
            , magasins: mags
            , form: {
                libelle: ''
                , magasin_id: ''
                , montant: 0
                , date_depense: ''
            }
            , formatPrice(n) {
                return new Intl.NumberFormat('fr-FR').format(n) + ' FCFA';
            }
            , openModal() {
                this.editingIndex = null;
                this.form = {
                    libelle: ''
                    , magasin_id: mags.length ? mags[0].id : ''
                    , montant: 0
                    , date_depense: new Date().toISOString().slice(0, 10)
                };
                this.showModal = true;
            }
            , editDepense(i) {
                this.editingIndex = i;
                const d = this.depenses[i];
                const dateVal = d.date_depense ? (String(d.date_depense).slice(0, 10)) : '';
                this.form = {
                    ...d
                    , date_depense: dateVal
                };
                this.showModal = true;
            }
            , openDeleteModal(i) {
                this.deleteIndex = i;
                this.deleteLabel = this.depenses[i].libelle;
                this.showDeleteModal = true;
            }
            , confirmDelete() {
                if (this.deleteIndex === null) return;
                const c = this.depenses[this.deleteIndex];
                const id = c.hash_id || c.id;
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '{{ url('
                depenses ') }}/' + 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="depenseManager(__depensesData, __magasinsData)">
    <x-page-card title="Liste des dépenses" action="openModal()" actionLabel="Nouvelle dépense">
        {{-- Filtres et export --}}
        <div class="mb-4 p-4 rounded-xl bg-slate-50 border border-slate-200">
            <form method="GET" action="{{ route('depenses.index') }}">
                <div class="flex flex-col sm:flex-row sm:items-end gap-4">
                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 flex-1">
                        <div>
                            <label class="block text-xs font-medium text-slate-500 uppercase tracking-wider mb-1.5">Magasin</label>
                            <select name="magasin_id" class="form-input w-full text-sm">
                                <option value="">Tous les magasins</option>
                                @foreach($magasinsFiltre as $m)
                                <option value="{{ $m->id }}" {{ request('magasin_id') == $m->id ? 'selected' : '' }}>{{ $m->nom }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-slate-500 uppercase tracking-wider mb-1.5">Année</label>
                            <select name="annee" class="form-input w-full text-sm">
                                <option value="">Toutes les années</option>
                                @foreach($annees as $a)
                                <option value="{{ $a }}" {{ request('annee') == $a ? 'selected' : '' }}>{{ $a }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-slate-500 uppercase tracking-wider mb-1.5">Mois</label>
                            <select name="mois" class="form-input w-full text-sm">
                                <option value="">Tous les mois</option>
                                @foreach(['01' => 'Janvier', '02' => 'Février', '03' => 'Mars', '04' => 'Avril', '05' => 'Mai', '06' => 'Juin', '07' => 'Juillet', '08' => 'Août', '09' => 'Septembre', '10' => 'Octobre', '11' => 'Novembre', '12' => 'Décembre'] as $num => $nom)
                                <option value="{{ $num }}" {{ request('mois') == $num ? 'selected' : '' }}>{{ $nom }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="flex flex-col sm:flex-row gap-2 sm:shrink-0">
                        <button type="submit" class="px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition-colors inline-flex items-center justify-center gap-2">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" /></svg>
                            Filtrer
                        </button>
                        <a href="{{ route('depenses.export', request()->only(['magasin_id', 'annee', 'mois'])) }}" class="px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-medium rounded-lg transition-colors inline-flex items-center justify-center gap-2">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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>
                            Exporter
                        </a>
                    </div>
                </div>
            </form>
        </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.</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Libellé</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Magasin</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Montant</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Date</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 ($depenses as $index => $depense)
                    <tr class="hover:bg-slate-50/50 transition-colors">
                        <td class="px-4 py-3 font-mono text-sm text-slate-600">{{ $depense->reference }}</td>
                        <td class="px-4 py-3 font-medium text-slate-800">{{ $depense->libelle }}</td>
                        <td class="px-4 py-3 text-slate-600">{{ $depense->magasin?->nom ?? '-' }}</td>
                        <td class="px-4 py-3 font-semibold text-red-600">{{ number_format($depense->montant, 0, ',', ' ') }} FCFA</td>
                        <td class="px-4 py-3 text-slate-600">{{ $depense->date_depense?->format('d/m/Y') ?? $depense->date_depense }}</td>
                        <td class="px-4 py-3">
                            <x-action-buttons :editAction="'editDepense(' . $index . ')'" :deleteAction="'openDeleteModal(' . $index . ')'" />
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="6" class="px-4 py-8 text-center text-slate-500">Aucune dépense.</td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        @if($depenses->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">{{ $depenses->firstItem() }}</span> à <span class="font-medium">{{ $depenses->lastItem() }}</span> sur <span class="font-medium">{{ $depenses->total() }}</span> dépenses
            </p>
            @if($depenses->hasPages())
            <div class="flex gap-3">
                @if($depenses->onFirstPage())
                <span class="px-4 py-2 text-slate-400 text-sm cursor-not-allowed">Précédent</span>
                @else
                <a href="{{ $depenses->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 {{ $depenses->currentPage() }} / {{ $depenses->lastPage() }}</span>
                @if($depenses->hasMorePages())
                <a href="{{ $depenses->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" @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 ? 'Nouvelle dépense' : 'Modifier la dépense'"></h3>
                </div>
                <form :action="editingIndex !== null ? '{{ url('depenses') }}/' + (depenses[editingIndex].hash_id || depenses[editingIndex].id) : '{{ route('depenses.store') }}'" method="POST" class="p-6 space-y-5">
                    @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

                    <x-form-group label="Libellé" :required="true">
                        <input type="text" name="libelle" x-model="form.libelle" required class="form-input" placeholder="Ex: Loyer, Électricité...">
                    </x-form-group>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <x-form-group label="Magasin" :required="true">
                            <select name="magasin_id" x-model="form.magasin_id" required class="form-input">
                                <option value="">Sélectionner un magasin</option>
                                <template x-for="magasin in magasins" :key="magasin.id">
                                    <option :value="magasin.id" x-text="magasin.nom"></option>
                                </template>
                            </select>
                        </x-form-group>
                        <x-form-group label="Montant (FCFA)" :required="true">
                            <input type="number" name="montant" x-model="form.montant" min="0" required class="form-input" placeholder="0">
                        </x-form-group>
                    </div>
                    <x-form-group label="Date" :required="true">
                        <input type="date" name="date_depense" x-model="form.date_depense" required class="form-input">
                    </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
