@php $money = fn ($minor) => config('care.billing.currency').' '.number_format($minor / 100, 2); @endphp
<x-app-layout title="Bills">
    <div class="flex items-center justify-between">
        <div>
            <h1 class="text-xl font-semibold text-slate-900">Bills & invoices</h1>
            <p class="mt-1 text-sm text-slate-500">Outstanding balances ready for walk-up payment</p>
        </div>
        @if (app(\App\Services\Care\CareFeatures::class)->enabled($organization, \App\Services\Care\CareFeatures::WORKFLOW_ENGINE))
            <a href="{{ route('care.obligations.index') }}" class="btn-primary">Financial gates</a>
        @endif
    </div>
    <form method="GET" class="mt-4 flex flex-wrap gap-3 rounded-2xl border border-slate-200 bg-white p-4">
        @if (($canSwitchBranch ?? false) && isset($branches) && $branches->count() > 1)
            <select name="branch_id" class="rounded-lg border-slate-300 text-sm">
                @foreach ($branches as $branch)
                    <option value="{{ $branch->id }}" @selected((int) $branchId === (int) $branch->id)>{{ $branch->name }}</option>
                @endforeach
            </select>
        @elseif (isset($branches) && $branches->isNotEmpty())
            <input type="hidden" name="branch_id" value="{{ $branchId }}">
            <span class="flex items-center text-sm text-slate-500">{{ $branches->first()->name }}</span>
        @endif
        <select name="status" class="rounded-lg border-slate-300 text-sm">
            <option value="outstanding" @selected(($statusFilter ?? '') === 'outstanding')>Outstanding</option>
            <option value="" @selected(($statusFilter ?? '') === '')>All statuses</option>
            @foreach ($statuses as $value => $label)
                <option value="{{ $value }}" @selected(($statusFilter ?? '') === $value)>{{ $label }}</option>
            @endforeach
        </select>
        <button type="submit" class="btn-primary">Filter</button>
    </form>

    <div class="mt-4 overflow-x-auto rounded-2xl border border-slate-200 bg-white">
        <table class="min-w-full text-sm">
            <thead class="bg-slate-50 text-left text-xs uppercase text-slate-500">
                <tr>
                    <th class="px-4 py-3">Ticket</th>
                    <th class="px-4 py-3">Invoice</th>
                    <th class="px-4 py-3">Patient</th>
                    <th class="px-4 py-3">Total</th>
                    <th class="px-4 py-3">Balance</th>
                    <th class="px-4 py-3">Status</th>
                    <th class="px-4 py-3 text-right">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-50">
                @forelse ($bills as $bill)
                    @php
                        $billUrl = route('care.bills.show', $bill);
                        $canServe = ! empty($queueIntegration['enabled'])
                            && $bill->queue_ticket_uuid
                            && ! in_array($bill->queue_ticket_status ?? '', ['serving', 'completed', 'cancelled'], true)
                            && $bill->balance_minor > 0;
                        $actionLabel = $bill->balance_minor > 0 && $bill->status !== \App\Models\Bill::STATUS_VOID
                            ? 'Pay'
                            : 'View';
                    @endphp
                    <tr
                        class="cursor-pointer hover:bg-slate-50"
                        onclick="window.location='{{ $billUrl }}'"
                    >
                        <td class="px-4 py-3">
                            @if (! empty($queueIntegration['enabled']) && $bill->queue_ticket_number)
                                @include('care.partials.queue-ticket', [
                                    'ticketNumber' => $bill->queue_ticket_number,
                                    'ticketStatus' => $bill->queue_ticket_status,
                                ])
                            @else
                                <span class="text-slate-400">—</span>
                            @endif
                        </td>
                        <td class="px-4 py-3 font-mono text-xs">
                            <a href="{{ $billUrl }}" class="font-medium text-sky-600 hover:text-sky-700" onclick="event.stopPropagation()">{{ $bill->invoice_number }}</a>
                        </td>
                        <td class="px-4 py-3">{{ $bill->patient->fullName() }}</td>
                        <td class="px-4 py-3">{{ $money($bill->total_minor) }}</td>
                        <td class="px-4 py-3 {{ $bill->balance_minor > 0 ? 'text-amber-700' : '' }}">{{ $money($bill->balance_minor) }}</td>
                        <td class="px-4 py-3">{{ $statuses[$bill->status] ?? $bill->status }}</td>
                        <td class="px-4 py-3 text-right" onclick="event.stopPropagation()">
                            <div class="flex items-center justify-end gap-2">
                                @if ($canServe)
                                    <form method="POST" action="{{ route('care.bills.serve', $bill) }}">
                                        @csrf
                                        <button type="submit" class="rounded-lg bg-sky-600 px-2.5 py-1 text-xs font-medium text-white hover:bg-sky-700">Serve</button>
                                    </form>
                                @endif
                                <a href="{{ $billUrl }}" class="rounded-lg border border-slate-200 bg-white px-2.5 py-1 text-xs font-medium text-slate-700 hover:border-slate-300 hover:bg-slate-50">{{ $actionLabel }}</a>
                            </div>
                        </td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="7" class="px-4 py-8 text-center text-slate-500">
                            @if (($statusFilter ?? '') === 'outstanding')
                                No outstanding invoices at this branch. Choose “All statuses” to browse paid bills.
                            @else
                                No bills yet.
                            @endif
                        </td>
                    </tr>
                @endforelse
            </tbody>
        </table>
    </div>
    <div class="mt-4">{{ $bills->links() }}</div>

    @if (! empty($canManageQueue) && ! empty($queueIntegration['enabled']))
        <div class="mt-6 border-t border-slate-100 pt-4">
            <p class="mb-2 text-xs font-medium uppercase tracking-wide text-slate-400">Booth queue (optional)</p>
            @include('care.partials.queue-ops', [
                'queueIntegration' => $queueIntegration,
                'queueCallNextRoute' => 'care.bills.call-next',
                'queueCallNextParams' => [],
                'queueCallNextDescription' => 'Only when a patient is waiting at billing. Otherwise open an unpaid invoice above.',
                'branchId' => $branchId ?? null,
                'variant' => 'muted',
            ])
        </div>
    @endif
</x-app-layout>
