<x-app-layout>
    <div class="portal-container">
        @if (session('status'))
            <div class="alert alert-success">{{ session('status') }}</div>
        @endif

        @if (session('error'))
            <div class="alert alert-error">{{ session('error') }}</div>
        @endif

        @php
            $displayInvoiceNumber = function ($invoice) {
                if ($invoice->whmcs_invoice_id) {
                    return (string) $invoice->whmcs_invoice_id;
                }

                $digits = preg_replace('/\D+/', '', (string) $invoice->invoice_number);
                return $digits !== '' ? $digits : (string) $invoice->invoice_number;
            };

            $displayMoney = function ($invoice) {
                $amount = number_format((float) $invoice->total, 2);
                return strtoupper((string) $invoice->currency) === 'USD'
                    ? '$'.$amount.' USD'
                    : strtoupper((string) $invoice->currency).' '.$amount;
            };

            $invoiceStatusLabel = function ($status) {
                $key = strtolower(str_replace(' ', '_', trim((string) $status)));
                return [
                    'payment_pending_whmcs' => 'Payment Processing',
                    'payment_received' => 'Payment Received',
                    'whmcs_sync_failed' => 'Processing',
                    'sync_failed' => 'Processing',
                    'manual_review' => 'Under Review',
                ][$key] ?? ucwords(str_replace('_', ' ', $key ?: 'pending'));
            };

            $displayDate = function ($value, $fallback = null) {
                try {
                    if ($value) {
                        return \Illuminate\Support\Carbon::parse($value)->format('l, F jS, Y');
                    }
                } catch (\Throwable) {
                    // Fall back below.
                }

                return $fallback ? $fallback->format('l, F jS, Y') : '-';
            };
        @endphp

        <div class="page-head compact-page-head">
            <div>
                <span class="eyebrow">Billing</span>
                <h1 class="page-title">My Invoices</h1>
                <p class="page-subtitle">View invoice history and pay any pending invoice securely.</p>
            </div>
            <form method="POST" action="{{ route('client.invoices.refresh') }}">
                @csrf
                <button class="secondary-btn" type="submit">Refresh</button>
            </form>
        </div>

        <div class="card" style="overflow-x:auto;">
            <table class="client-clean-table">
                <thead>
                    <tr>
                        <th>Invoice #</th>
                        <th>Invoice Date</th>
                        <th>Due Date</th>
                        <th>Total</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse ($invoices as $invoice)
                        @php
                            $status = strtolower(str_replace(' ', '_', (string) $invoice->status));
                            $statusLabel = $invoiceStatusLabel($status);
                            $canPay = $invoice->whmcs_invoice_id && ! in_array($status, ['paid', 'cancelled', 'refunded', 'payment_received', 'payment_pending_whmcs'], true);
                            $invoiceDate = data_get($invoice->whmcs_payload, 'date')
                                ?: data_get($invoice->whmcs_payload, 'datecreated')
                                ?: data_get($invoice->whmcs_payload, 'created_at');
                        @endphp
                        <tr>
                            <td><strong>{{ $displayInvoiceNumber($invoice) }}</strong></td>
                            <td>{{ $displayDate($invoiceDate, $invoice->created_at) }}</td>
                            <td>{{ $displayDate($invoice->due_date) }}</td>
                            <td><strong>{{ $displayMoney($invoice) }}</strong></td>
                            <td><span class="status-pill {{ $status }}">{{ $statusLabel }}</span></td>
                            <td>
                                @if ($canPay)
                                    <a class="primary-btn" href="{{ route('client.invoices.show', $invoice) }}" style="text-decoration:none; display:inline-flex;">Pay Now</a>
                                @else
                                    <span class="service-muted">{{ $status === 'paid' ? 'Paid' : '-' }}</span>
                                @endif
                            </td>
                        </tr>
                    @empty
                        <tr><td colspan="6">No invoices yet.</td></tr>
                    @endforelse
                </tbody>
            </table>
            <div style="margin-top:18px;">{{ $invoices->links() }}</div>
        </div>
    </div>
</x-app-layout>
