@extends('layouts.app')

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

<script>
    window.__depensesData = @json($depenses);
    window.depenseManager = function(paginator) {
        const p = paginator && typeof paginator === 'object' && 'data' in paginator ? paginator : {
            data: []
        };
        return {
            showModal: false
            , showDeleteModal: false
            , deleteIndex: null
            , deleteLabel: ''
            , editingIndex: null
            , depenses: p.data || []
            , form: {
                libelle: ''
                , categorie: ''
                , montant: 0
            }
            , formatPrice(n) {
                return new Intl.NumberFormat('fr-FR').format(n) + ' FCFA';
            }
            , openModal() {
                this.editingIndex = null;
                this.form = {
                    libelle: ''
                    , categorie: ''
                    , montant: 0
                };
                this.showModal = true;
            }
            , editDepense(i) {
                this.editingIndex = i;
                this.form = {
                    ...this.depenses[i]
                };
                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.clients[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>

@section('content')
<div x-data="depenseManager()">
    <x-page-card title="Liste des dépenses" action="openModal()" actionLabel="Nouvelle dépense">
        <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">Catégorie</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 $depense)
                    <tr class="hover:bg-slate-50/50 transition-colors">
                        <td class="px-4 py-3 font-mono text-sm text-slate-600" x-text="{{ $depense->reference }}"></td>
                        <td class="px-4 py-3 font-medium text-slate-800" x-text="{{ $depense->libelle }}"></td>
                        <td class="px-4 py-3 text-slate-600" x-text="{{ $depense->categorie }}"></td>
                        <td class="px-4 py-3 font-semibold text-red-600" x-text="{{ $depense->montant }}"></td>
                        <td class="px-4 py-3 text-slate-600" x-text="{{ $depense->date_depense }}"></td>
                        <td class="px-4 py-3">
                            <x-action-buttons :editAction="'editDepense({{ $depense->id }})'" :deleteAction="'openDeleteModal({{ $depense->id }})'" />
                        </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" 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 @submit.prevent="saveDepense()" class="p-6 space-y-5">
                    <x-form-group label="Libellé" :required="true">
                        <input type="text" 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="Catégorie" :required="true">
                            <x-searchable-select form-id="depense-form" model="categorie" placeholder="Sélectionner une catégorie" :options="[['value' => 'Loyer', 'label' => 'Loyer'], ['value' => 'Électricité', 'label' => 'Électricité'], ['value' => 'Transport', 'label' => 'Transport'], ['value' => 'Maintenance', 'label' => 'Maintenance'], ['value' => 'Autre', 'label' => 'Autre']]" />
                        </x-form-group>
                        <x-form-group label="Montant (FCFA)" :required="true">
                            <input type="number" x-model="form.montant" min="0" required class="form-input" placeholder="0">
                        </x-form-group>
                    </div>
                    <div class="flex gap-3 pt-2">
                        <button type="submit" class="form-btn-primary flex-1">
                            <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="M5 13l4 4L19 7" /></svg>
                            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>

<script>
    function depenseManager() {
        return {
            showModal: false
            , showDeleteModal: false
            , deleteIndex: null
            , deleteLabel: ''
            , editingIndex: null
            , depenses: [{
                    reference: 'DEP-001'
                    , libelle: 'Loyer magasin central'
                    , categorie: 'Loyer'
                    , montant: 150000
                    , date: '01/02/2025'
                }
                , {
                    reference: 'DEP-002'
                    , libelle: 'Facture électricité'
                    , categorie: 'Électricité'
                    , montant: 45000
                    , date: '15/02/2025'
                }
            ]
            , form: {
                libelle: ''
                , categorie: ''
                , montant: 0
            }
            , formatPrice(n) {
                return new Intl.NumberFormat('fr-FR').format(n) + ' FCFA';
            }
            , openModal() {
                this.editingIndex = null;
                this.form = {
                    libelle: ''
                    , categorie: ''
                    , montant: 0
                };
                this.showModal = true;
                this.$nextTick(() => this.$el.dispatchEvent(new CustomEvent('form-reset', {
                    bubbles: true
                    , detail: {
                        formId: 'depense-form'
                    }
                })));
            }
            , editDepense(i) {
                this.editingIndex = i;
                this.form = {
                    libelle: this.depenses[i].libelle
                    , categorie: this.depenses[i].categorie
                    , montant: this.depenses[i].montant
                };
                this.showModal = true;
            }
            , saveDepense() {
                if (this.editingIndex !== null) {
                    this.depenses[this.editingIndex] = {
                        reference: this.depenses[this.editingIndex].reference
                        , ...this.form
                        , date: this.depenses[this.editingIndex].date
                    };
                } else {
                    const ref = 'DEP-' + String(this.depenses.length + 1).padStart(3, '0');
                    this.depenses.unshift({
                        reference: ref
                        , ...this.form
                        , date: new Date().toLocaleDateString('fr-FR')
                    });
                }
                this.showModal = false;
            }
            , openDeleteModal(i) {
                this.deleteIndex = i;
                this.deleteLabel = this.depenses[i].libelle;
                this.showDeleteModal = true;
            }
            , confirmDelete() {
                if (this.deleteIndex !== null) {
                    this.depenses.splice(this.deleteIndex, 1);
                    this.showDeleteModal = false;
                    this.deleteIndex = null;
                    this.deleteLabel = '';
                }
            }
        };
    }

</script>
@endsection
