<x-layouts.tenant pageTitle="Caja">
    <x-page-header
        title="Caja"
        subtitle="Controla ingresos, egresos y movimientos administrativos del negocio."
    />

    <div x-data="{ voidMovement: null }">
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <x-card>
            <p class="text-sm font-semibold text-ink-500">Ingresos del periodo</p>
            <p class="mt-2 text-3xl font-black text-emerald-600 font-display">$ {{ number_format($income, 0, ',', '.') }}</p>
            <p class="mt-1 text-xs text-ink-400">{{ $currency }}</p>
        </x-card>
        <x-card>
            <p class="text-sm font-semibold text-ink-500">Egresos del periodo</p>
            <p class="mt-2 text-3xl font-black text-rose-600 font-display">$ {{ number_format($expense, 0, ',', '.') }}</p>
            <p class="mt-1 text-xs text-ink-400">{{ $currency }}</p>
        </x-card>
        <x-card>
            <p class="text-sm font-semibold text-ink-500">Saldo del periodo</p>
            <p class="mt-2 text-3xl font-black {{ $balance >= 0 ? 'text-ink-900' : 'text-rose-600' }} font-display">$ {{ number_format($balance, 0, ',', '.') }}</p>
            <p class="mt-1 text-xs text-ink-400">Hoy: +${{ number_format($todayIncome, 0, ',', '.') }} / -${{ number_format($todayExpense, 0, ',', '.') }}</p>
        </x-card>
    </div>

    <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
        <x-card title="Nuevo movimiento" subtitle="Registra entradas y salidas de dinero." class="xl:col-span-1">
            <form method="POST" action="{{ route('tenant.cash.store') }}" class="space-y-4">
                @csrf
                <div class="grid grid-cols-2 gap-3">
                    <label class="block">
                        <span class="text-sm font-semibold text-ink-700">Tipo</span>
                        <select name="type" class="input mt-1.5" required>
                            <option value="income" @selected(old('type') === 'income')>Ingreso</option>
                            <option value="expense" @selected(old('type') === 'expense')>Egreso</option>
                        </select>
                        @error('type') <p class="text-xs text-rose-600 mt-1">{{ $message }}</p> @enderror
                    </label>
                    <label class="block">
                        <span class="text-sm font-semibold text-ink-700">Método</span>
                        <select name="payment_method" class="input mt-1.5" required>
                            <option value="cash" @selected(old('payment_method') === 'cash')>Efectivo</option>
                            <option value="card" @selected(old('payment_method') === 'card')>Tarjeta</option>
                            <option value="transfer" @selected(old('payment_method') === 'transfer')>Transferencia</option>
                            <option value="online" @selected(old('payment_method') === 'online')>Online</option>
                            <option value="other" @selected(old('payment_method') === 'other')>Otro</option>
                        </select>
                        @error('payment_method') <p class="text-xs text-rose-600 mt-1">{{ $message }}</p> @enderror
                    </label>
                </div>

                <label class="block">
                    <span class="text-sm font-semibold text-ink-700">Categoría</span>
                    <input name="category" value="{{ old('category', 'General') }}" class="input mt-1.5" required>
                    @error('category') <p class="text-xs text-rose-600 mt-1">{{ $message }}</p> @enderror
                </label>

                <label class="block">
                    <span class="text-sm font-semibold text-ink-700">Descripción</span>
                    <input name="description" value="{{ old('description') }}" class="input mt-1.5" placeholder="Ej: Venta mostrador, compra de insumos..." required>
                    @error('description') <p class="text-xs text-rose-600 mt-1">{{ $message }}</p> @enderror
                </label>

                <div class="grid grid-cols-2 gap-3">
                    <label class="block">
                        <span class="text-sm font-semibold text-ink-700">Valor</span>
                        <input type="number" min="1" step="1" name="amount" value="{{ old('amount') }}" class="input mt-1.5" required>
                        @error('amount') <p class="text-xs text-rose-600 mt-1">{{ $message }}</p> @enderror
                    </label>
                    <label class="block">
                        <span class="text-sm font-semibold text-ink-700">Fecha</span>
                        <input type="datetime-local" name="occurred_at" value="{{ old('occurred_at', now()->format('Y-m-d\\TH:i')) }}" class="input mt-1.5">
                        @error('occurred_at') <p class="text-xs text-rose-600 mt-1">{{ $message }}</p> @enderror
                    </label>
                </div>

                <label class="block">
                    <span class="text-sm font-semibold text-ink-700">Referencia</span>
                    <input name="reference" value="{{ old('reference') }}" class="input mt-1.5" placeholder="Factura, recibo, comprobante">
                    @error('reference') <p class="text-xs text-rose-600 mt-1">{{ $message }}</p> @enderror
                </label>

                <label class="block">
                    <span class="text-sm font-semibold text-ink-700">Notas</span>
                    <textarea name="notes" rows="3" class="input mt-1.5">{{ old('notes') }}</textarea>
                    @error('notes') <p class="text-xs text-rose-600 mt-1">{{ $message }}</p> @enderror
                </label>

                <x-btn type="submit" class="w-full justify-center">Guardar movimiento</x-btn>
            </form>
        </x-card>

        <div class="xl:col-span-2 space-y-5">
            <x-card padding="false">
                <form method="GET" action="{{ route('tenant.cash.index') }}" class="p-4 border-b border-ink-100 grid grid-cols-1 md:grid-cols-5 gap-3">
                    <input type="date" name="from" value="{{ request('from', $from->toDateString()) }}" class="input">
                    <input type="date" name="to" value="{{ request('to', $to->toDateString()) }}" class="input">
                    <select name="type" class="input">
                        <option value="">Todos los tipos</option>
                        <option value="income" @selected(request('type') === 'income')>Ingresos</option>
                        <option value="expense" @selected(request('type') === 'expense')>Egresos</option>
                    </select>
                    <select name="payment_method" class="input">
                        <option value="">Todos los métodos</option>
                        <option value="cash" @selected(request('payment_method') === 'cash')>Efectivo</option>
                        <option value="card" @selected(request('payment_method') === 'card')>Tarjeta</option>
                        <option value="transfer" @selected(request('payment_method') === 'transfer')>Transferencia</option>
                        <option value="online" @selected(request('payment_method') === 'online')>Online</option>
                        <option value="other" @selected(request('payment_method') === 'other')>Otro</option>
                    </select>
                    <x-btn type="submit" variant="secondary" class="justify-center">Filtrar</x-btn>
                </form>

                <div class="divide-y divide-ink-100 md:hidden">
                    @forelse ($movements as $movement)
                        <article class="p-4">
                            <div class="flex items-start gap-3">
                                <span class="mt-0.5 inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl text-lg font-black {{ $movement->isIncome() ? 'bg-emerald-50 text-emerald-700' : 'bg-rose-50 text-rose-700' }}">
                                    {{ $movement->isIncome() ? '+' : '-' }}
                                </span>
                                <div class="min-w-0 flex-1">
                                    <div class="flex items-start justify-between gap-3">
                                        <div class="min-w-0">
                                            <h3 class="truncate text-base font-black text-ink-900">{{ $movement->description }}</h3>
                                            <p class="mt-1 truncate text-xs text-ink-500">{{ $movement->category }} @if($movement->reference) · {{ $movement->reference }} @endif</p>
                                        </div>
                                        <p class="shrink-0 text-sm font-black {{ $movement->isIncome() ? 'text-emerald-700' : 'text-rose-700' }}">
                                            {{ $movement->isIncome() ? '+' : '-' }} $ {{ number_format($movement->amount, 0, ',', '.') }}
                                        </p>
                                    </div>

                                    <div class="mt-3 flex flex-wrap items-center gap-2">
                                        <span class="rounded-full bg-ink-50 px-2.5 py-1 text-xs font-bold text-ink-600">{{ $movement->occurred_at?->format('d/m/Y H:i') }}</span>
                                        <span class="rounded-full bg-violet-50 px-2.5 py-1 text-xs font-bold text-violet-700">{{ $movement->paymentMethodLabel() }}</span>
                                        @if ($movement->booking)
                                            <span class="rounded-full bg-brand-50 px-2.5 py-1 text-xs font-bold text-brand-700">{{ $movement->booking->code }}</span>
                                        @endif
                                    </div>

                                    @if ($movement->status === 'confirmed')
                                        <button type="button"
                                            @click="voidMovement = { url: @js(route('tenant.cash.void', $movement)), title: @js($movement->description), amount: @js(number_format($movement->amount, 0, ',', '.')) }"
                                            class="mt-4 w-full rounded-2xl bg-rose-50 px-4 py-3 text-sm font-black text-rose-700">
                                            Anular movimiento
                                        </button>
                                    @else
                                        <div class="mt-4"><x-badge color="gray">Anulado</x-badge></div>
                                    @endif
                                </div>
                            </div>
                        </article>
                    @empty
                        <div class="p-8">
                            <x-empty-state title="Sin movimientos" message="Registra el primer ingreso o egreso de caja." />
                        </div>
                    @endforelse
                </div>

                <div class="hidden overflow-x-auto md:block">
                    <table class="w-full text-sm">
                        <thead class="bg-ink-50 text-xs uppercase tracking-wider text-ink-500">
                            <tr>
                                <th class="px-4 py-3 text-left">Fecha</th>
                                <th class="px-4 py-3 text-left">Movimiento</th>
                                <th class="px-4 py-3 text-left">Método</th>
                                <th class="px-4 py-3 text-right">Valor</th>
                                <th class="px-4 py-3 text-right">Acciones</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-ink-100">
                            @forelse ($movements as $movement)
                                <tr class="hover:bg-ink-50/60">
                                    <td class="px-4 py-3 text-ink-500 whitespace-nowrap">
                                        {{ $movement->occurred_at?->format('d/m/Y H:i') }}
                                    </td>
                                    <td class="px-4 py-3">
                                        <div class="flex items-start gap-3">
                                            <span class="mt-0.5 inline-flex h-8 w-8 items-center justify-center rounded-xl {{ $movement->isIncome() ? 'bg-emerald-50 text-emerald-700' : 'bg-rose-50 text-rose-700' }}">
                                                {{ $movement->isIncome() ? '+' : '-' }}
                                            </span>
                                            <div>
                                                <p class="font-bold text-ink-900">{{ $movement->description }}</p>
                                                <p class="text-xs text-ink-500">{{ $movement->category }} @if($movement->reference) · {{ $movement->reference }} @endif</p>
                                                @if ($movement->booking)
                                                    <p class="text-xs text-brand-700 mt-1">Reserva {{ $movement->booking->code }}</p>
                                                @endif
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-4 py-3 text-ink-600">{{ $movement->paymentMethodLabel() }}</td>
                                    <td class="px-4 py-3 text-right font-mono font-bold {{ $movement->isIncome() ? 'text-emerald-700' : 'text-rose-700' }}">
                                        {{ $movement->isIncome() ? '+' : '-' }} $ {{ number_format($movement->amount, 0, ',', '.') }}
                                    </td>
                                    <td class="px-4 py-3 text-right">
                                        @if ($movement->status === 'confirmed')
                                            <form method="POST" action="{{ route('tenant.cash.void', $movement) }}" class="inline">
                                                @csrf
                                                @method('PATCH')
                                                <button type="submit" onclick="return confirm('¿Anular este movimiento?')" class="text-xs font-bold text-rose-600 hover:text-rose-700">Anular</button>
                                            </form>
                                        @else
                                            <x-badge color="gray">Anulado</x-badge>
                                        @endif
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="5">
                                        <x-empty-state title="Sin movimientos" message="Registra el primer ingreso o egreso de caja." />
                                    </td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>

                @if ($movements->hasPages())
                    <div class="px-4 py-3 border-t border-ink-100">{{ $movements->links() }}</div>
                @endif
            </x-card>
        </div>
    </div>

    <div x-show="voidMovement" x-cloak class="fixed inset-0 z-50 md:hidden">
        <div class="absolute inset-0 bg-ink-950/40 backdrop-blur-sm" @click="voidMovement = null"></div>
        <section x-show="voidMovement" x-transition:enter="transition ease-out duration-200" x-transition:enter-start="translate-y-full" x-transition:enter-end="translate-y-0" x-transition:leave="transition ease-in duration-150" x-transition:leave-start="translate-y-0" x-transition:leave-end="translate-y-full" class="absolute inset-x-0 bottom-0 rounded-t-[2rem] bg-white p-5 pb-[max(1.25rem,env(safe-area-inset-bottom))] shadow-2xl">
            <div class="mx-auto mb-4 h-1.5 w-12 rounded-full bg-ink-200"></div>
            <p class="text-xs font-black uppercase tracking-[0.16em] text-rose-600">Anular movimiento</p>
            <h3 class="mt-1 text-xl font-black text-ink-900" x-text="voidMovement?.title"></h3>
            <p class="mt-2 text-sm text-ink-500">Esta acción marcará el movimiento como anulado y lo sacará del saldo activo.</p>
            <form method="POST" :action="voidMovement?.url" class="mt-5 grid grid-cols-2 gap-2">
                @csrf
                @method('PATCH')
                <button type="button" @click="voidMovement = null" class="rounded-2xl bg-ink-50 px-4 py-3 text-sm font-black text-ink-700">Volver</button>
                <button type="submit" class="rounded-2xl bg-rose-600 px-4 py-3 text-sm font-black text-white shadow-sm">Anular</button>
            </form>
        </section>
    </div>
    </div>
</x-layouts.tenant>
