<x-app-layout>
    <link href="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/css/tom-select.css" rel="stylesheet">
    <style>
        /* Custom styling to match your theme */
        .ts-control {
            border-radius: 0.5rem;
            border-color: #e2e8f0;
            padding: 0.6rem;
            font-size: 0.875rem;
            box-shadow: none;
        }
        .ts-control:focus {
            border-color: #6366f1; /* Indigo-500 */
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
        }
        .ts-dropdown {
            border-radius: 0.5rem;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            z-index: 50;
        }
        .ts-dropdown .option.active {
            background-color: #eff6ff; /* Blue-50 */
            color: #1e293b;
        }
    </style>

    <x-slot name="header">
        <div class="flex justify-between items-center">
            <h2 class="font-bold text-2xl text-slate-800 leading-tight flex items-center gap-2">
                <i class="ph-duotone ph-currency-dollar text-emerald-600"></i>
                {{ __('Finance & Cashier') }}
            </h2>
            <div class="flex gap-2">
                 <a href="{{ route('admin.accounts') }}" class="bg-white border border-slate-300 text-slate-700 px-4 py-2 rounded-lg text-sm font-bold hover:bg-slate-50 transition flex items-center gap-2">
                    <i class="ph-bold ph-books"></i> Chart of Accounts
                </a>
                  <a href="{{ route('admin.accounts.ledger') }}" class="bg-white border border-slate-300 text-slate-700 px-4 py-2 rounded-lg text-sm font-bold hover:bg-slate-50 transition flex items-center gap-2">
                    <i class="ph-bold ph-books"></i>Ledger of Accounts
                </a>
            </div>


        </div>
    </x-slot>

    <div class="py-10 bg-slate-50 min-h-screen">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-8">

            <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                <div class="bg-white p-6 rounded-2xl shadow-sm ring-1 ring-slate-900/5 transition hover:shadow-md">
                    <div class="flex items-center justify-between mb-4">
                        <div class="h-10 w-10 rounded-full bg-indigo-50 flex items-center justify-center">
                            <i class="ph-duotone ph-invoice text-xl text-indigo-600"></i>
                        </div>
                        <span class="text-xs font-bold text-slate-400 uppercase tracking-wider">Billed</span>
                    </div>
                    <h4 class="text-2xl font-black text-slate-800">KES {{ number_format($totalInvoiced) }}</h4>
                    <p class="text-xs text-slate-500 mt-1">Total revenue generated</p>
                </div>

                <div class="bg-emerald-50 p-6 rounded-2xl border border-emerald-100 shadow-sm transition hover:shadow-md">
                    <div class="flex items-center justify-between mb-4">
                        <div class="h-10 w-10 rounded-full bg-white flex items-center justify-center shadow-sm">
                            <i class="ph-duotone ph-vault text-xl text-emerald-600"></i>
                        </div>
                        <span class="text-xs font-bold text-emerald-700/60 uppercase tracking-wider">Collected</span>
                    </div>
                    <h4 class="text-2xl font-black text-emerald-800">KES {{ number_format($totalCollected) }}</h4>
                    <p class="text-xs text-emerald-700 mt-1">Actual cash in bank</p>
                </div>

                <div class="bg-amber-50 p-6 rounded-2xl border border-amber-100 shadow-sm transition hover:shadow-md">
                    <div class="flex items-center justify-between mb-4">
                        <div class="h-10 w-10 rounded-full bg-white flex items-center justify-center shadow-sm">
                            <i class="ph-duotone ph-warning-circle text-xl text-amber-600"></i>
                        </div>
                        <span class="text-xs font-bold text-amber-700/60 uppercase tracking-wider">Due</span>
                    </div>
                    <h4 class="text-2xl font-black text-amber-800">KES {{ number_format($outstanding) }}</h4>
                    <p class="text-xs text-amber-700 mt-1">Unpaid invoices</p>
                </div>

                <div class="bg-white p-6 rounded-2xl shadow-sm ring-1 ring-slate-900/5 transition hover:shadow-md">
                    <div class="flex items-center justify-between mb-4">
                        <div class="h-10 w-10 rounded-full bg-slate-50 flex items-center justify-center">
                            <i class="ph-duotone ph-arrow-u-down-left text-xl text-slate-600"></i>
                        </div>
                        <span class="text-xs font-bold text-slate-400 uppercase tracking-wider">Credits</span>
                    </div>
                    <h4 class="text-2xl font-black text-slate-600">KES {{ number_format($totalCredited) }}</h4>
                    <p class="text-xs text-slate-400 mt-1">Refunds & Notes</p>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">

                <div class="lg:col-span-1 space-y-8">

                    <div class="bg-white shadow-lg shadow-indigo-900/5 ring-1 ring-slate-900/5 sm:rounded-2xl p-6 relative overflow-hidden border-t-4 border-indigo-500">
                        <h3 class="font-bold text-lg text-slate-800 mb-4 flex items-center gap-2">
                            <i class="ph-duotone ph-receipt text-indigo-600"></i> Quick Invoice
                        </h3>

                        <form action="{{ route('admin.finance.invoice.store') }}" method="POST">
                            @csrf
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Search Case / Client</label>
                                    <select id="caseSelect" name="case_id" placeholder="Type to search case..." autocomplete="off">
                                        <option value="">Search case number or client name...</option>
                                        @foreach($cases as $case)
                                            <option value="{{ $case->id }}">
                                                {{ $case->case_number }} - {{ $case->client->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

                                <div>
                                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Service Description</label>
                                    <input type="text" name="description" class="w-full rounded-lg border-slate-200 text-sm" placeholder="e.g. Legal Consultation Fee" required>
                                </div>

                                <div class="grid grid-cols-2 gap-4">
                                    <div>
                                        <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Amount</label>
                                        <input type="number" name="amount" class="w-full rounded-lg border-slate-200 text-sm font-bold text-slate-700" placeholder="0.00" required>
                                    </div>
                                    <div>
                                        <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Due Date</label>
                                        <input type="date" name="due_date" value="{{ date('Y-m-d', strtotime('+7 days')) }}" class="w-full rounded-lg border-slate-200 text-sm" required>
                                    </div>
                                </div>

                                <button type="submit" class="w-full bg-indigo-600 text-white py-2.5 rounded-lg font-bold hover:bg-indigo-700 shadow-md shadow-indigo-200 transition flex items-center justify-center gap-2">
                                    <i class="ph-bold ph-paper-plane-right"></i> Generate & Save
                                </button>
                            </div>
                        </form>
                    </div>

                    <div class="bg-white shadow-lg shadow-emerald-900/5 ring-1 ring-slate-900/5 sm:rounded-2xl p-6 relative overflow-hidden" x-data="{ type: 'invoice' }">
                        <div class="absolute top-0 right-0 -mt-6 -mr-6 w-32 h-32 bg-emerald-100 rounded-full blur-3xl opacity-60"></div>

                        <h3 class="font-bold text-lg text-slate-800 mb-5 flex items-center gap-2 relative z-10">
                            <i class="ph-duotone ph-bank text-emerald-600"></i> Record Transaction
                        </h3>

                        <div class="flex space-x-6 mb-5 border-b border-slate-100 relative z-10">
                            <button @click="type = 'invoice'"
                                :class="type === 'invoice' ? 'text-emerald-600 border-b-2 border-emerald-600' : 'text-slate-400 hover:text-slate-600'"
                                class="text-xs font-bold uppercase pb-2 transition-all">
                                Pay Invoice
                            </button>
                            <button @click="type = 'deposit'"
                                :class="type === 'deposit' ? 'text-emerald-600 border-b-2 border-emerald-600' : 'text-slate-400 hover:text-slate-600'"
                                class="text-xs font-bold uppercase pb-2 transition-all">
                                Direct Deposit
                            </button>
                        </div>

                        <form action="{{ route('admin.finance.payment.store') }}" method="POST">
                            @csrf
                            <div class="space-y-4 relative z-10">

                                <div x-show="type === 'invoice'">
                                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Search Outstanding Invoice</label>
                                    <select id="paymentInvoiceSelect" name="invoice_id" placeholder="Search invoice or client..." autocomplete="off">
                                        <option value="">Type to search...</option>
                                        @foreach ($invoices as $inv)
                                            <option value="{{ $inv->id }}">
                                                #{{ $inv->invoice_number }} - {{ $inv->case->client->name }} (Bal: {{ number_format($inv->balance) }})
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

                                <div x-show="type === 'deposit'" style="display: none;">
                                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Search Client</label>
                                    <select id="paymentClientSelect" name="client_id" placeholder="Search client name..." autocomplete="off">
                                        <option value="">Type to search...</option>
                                        @foreach (\App\Models\User::role('client')->get() as $client)
                                            <option value="{{ $client->id }}">{{ $client->name }}</option>
                                        @endforeach
                                    </select>
                                    <p class="text-[10px] text-slate-400 mt-1 italic">For Judgment sums, Trust funds, or Retainers without invoices.</p>
                                </div>

                                <div>
                                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Target Account</label>
                                    <select name="chart_of_account_id" class="w-full rounded-lg border-slate-200 text-sm focus:ring-emerald-500 focus:border-emerald-500" required>
                                        <option value="">-- Classify Funds --</option>
                                        @foreach(\App\Models\ChartOfAccount::all()->groupBy('type') as $type => $accounts)
                                            <optgroup label="{{ ucfirst($type) }}">
                                                @foreach($accounts as $acc)
                                                    <option value="{{ $acc->id }}">{{ $acc->name }} ({{ $acc->code }})</option>
                                                @endforeach
                                            </optgroup>
                                        @endforeach
                                    </select>
                                </div>

                                <div class="grid grid-cols-2 gap-4">
                                    <div>
                                        <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Amount</label>
                                        <div class="relative">
                                            <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-slate-400 text-xs">KES</span>
                                            <input type="number" name="amount" class="w-full pl-10 rounded-lg border-slate-200 text-sm font-bold text-slate-700" placeholder="0.00" required>
                                        </div>
                                    </div>
                                    <div>
                                        <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Date</label>
                                        <input type="date" name="payment_date" value="{{ date('Y-m-d') }}" class="w-full rounded-lg border-slate-200 text-sm" required>
                                    </div>
                                </div>

                                <div>
                                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Payment Method</label>
                                    <select name="method" class="w-full rounded-lg border-slate-200 text-sm">
                                        <option value="Bank Transfer">Bank Transfer</option>
                                        <option value="M-Pesa">M-Pesa</option>
                                        <option value="Cheque">Cheque</option>
                                        <option value="Cash">Cash</option>
                                    </select>
                                </div>

                                <div>
                                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Ref / Receipt No</label>
                                    <input type="text" name="transaction_ref" class="w-full rounded-lg border-slate-200 text-sm uppercase placeholder:normal-case" placeholder="e.g. QGH56...">
                                </div>

                                <button type="submit" class="w-full bg-emerald-600 text-white py-2.5 rounded-lg font-bold hover:bg-emerald-700 shadow-lg shadow-emerald-200 transition transform active:scale-95">
                                    Record Transaction
                                </button>
                            </div>
                        </form>
                    </div>

                    <div class="bg-slate-50 border border-slate-200 sm:rounded-2xl p-6">
                        <h3 class="font-bold text-sm text-slate-700 mb-4 flex items-center gap-2">
                            <i class="ph-bold ph-arrow-u-down-left text-slate-400"></i> Issue Credit Note
                        </h3>
                        <form action="{{ route('admin.finance.credit.store') }}" method="POST">
                            @csrf
                            <div class="space-y-3">
                                <select id="creditInvoiceSelect" name="invoice_id" placeholder="Search Invoice..." autocomplete="off">
                                    <option value="">Type to search...</option>
                                    @foreach ($invoices as $inv)
                                        <option value="{{ $inv->id }}">{{ $inv->invoice_number }} ({{ $inv->client->name }})</option>
                                    @endforeach
                                </select>
                                <div class="grid grid-cols-2 gap-3">
                                    <input type="number" name="amount" class="w-full rounded-lg border-slate-200 text-xs" placeholder="Amount" required>
                                    <input type="text" name="reason" class="w-full rounded-lg border-slate-200 text-xs" placeholder="Reason" required>
                                </div>
                                <button type="submit" class="w-full bg-white border border-slate-300 text-slate-700 py-2 rounded-lg text-xs font-bold hover:bg-slate-100 transition shadow-sm">
                                    Create Credit Note
                                </button>
                            </div>
                        </form>
                    </div>

                </div>

                <div class="lg:col-span-2 space-y-8">

                    <div class="bg-white shadow-sm ring-1 ring-slate-900/5 sm:rounded-2xl overflow-hidden">
                        <div class="px-6 py-5 border-b border-slate-100 flex justify-between items-center bg-white">
                            <h3 class="font-bold text-lg text-slate-800 flex items-center gap-2">
                                <i class="ph-duotone ph-list-dashes text-indigo-500"></i> Recent Transactions
                            </h3>
                            <span class="text-xs font-medium bg-slate-100 text-slate-600 px-2 py-1 rounded">Last 10 Records</span>
                        </div>
                        <div class="overflow-x-auto">
                            <table class="min-w-full text-left text-sm whitespace-nowrap">
                                <thead class="bg-slate-50 text-slate-500 font-semibold border-b border-slate-200">
                                    <tr>
                                        <th class="px-6 py-4">Ref / Details</th>
                                        <th class="px-6 py-4">Client</th>
                                        <th class="px-6 py-4">Ledger Account</th>
                                        <th class="px-6 py-4">Method</th>
                                        <th class="px-6 py-4 text-right">Amount</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-slate-100">
                                    @forelse($payments as $pay)
                                        <tr class="hover:bg-slate-50 transition group">
                                            <td class="px-6 py-4">
                                                <div class="font-bold text-slate-700">{{ $pay->transaction_ref ?? 'CASH' }}</div>
                                                <div class="text-xs text-slate-400 flex items-center gap-1">
                                                    <i class="ph-bold ph-calendar"></i> {{ \Carbon\Carbon::parse($pay->payment_date)->format('M d, Y') }}
                                                </div>
                                            </td>
                                            <td class="px-6 py-4">
                                                <div class="flex items-center gap-2">
                                                    <div class="h-6 w-6 rounded-full bg-indigo-50 text-indigo-600 flex items-center justify-center text-[10px] font-bold">
                                                        {{ substr($pay->client->name ?? ($pay->invoice->case->client->name ?? '?'), 0, 1) }}
                                                    </div>
                                                    <span class="text-slate-600">{{ $pay->client->name ?? ($pay->invoice->case->client->name ?? 'Unknown') }}</span>
                                                </div>
                                            </td>
                                            <td class="px-6 py-4">
                                                @if($pay->account)
                                                    <span class="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-xs font-bold bg-slate-100 text-slate-600 border border-slate-200">
                                                        {{ $pay->account->name }}
                                                    </span>
                                                @else
                                                    <span class="text-xs text-slate-400 italic">Uncategorized</span>
                                                @endif
                                            </td>
                                            <td class="px-6 py-4">
                                                <span class="text-xs font-medium text-slate-500 bg-white border border-slate-200 px-2 py-1 rounded-full">
                                                    {{ $pay->method }}
                                                </span>
                                            </td>
                                            <td class="px-6 py-4 text-right">
                                                <span class="font-mono font-bold text-emerald-600 bg-emerald-50 px-2 py-1 rounded-lg">
                                                    + {{ number_format($pay->amount) }}
                                                </span>
                                            </td>
                                        </tr>
                                    @empty
                                        <tr>
                                            <td colspan="5" class="px-6 py-12 text-center">
                                                <div class="flex flex-col items-center justify-center">
                                                    <div class="bg-slate-50 rounded-full p-4 mb-3">
                                                        <i class="ph-duotone ph-coins text-3xl text-slate-300"></i>
                                                    </div>
                                                    <p class="text-slate-400 italic font-medium">No payments recorded recently.</p>
                                                </div>
                                            </td>
                                        </tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/js/tom-select.complete.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var settings = {
                create: false,
                sortField: {
                    field: "text",
                    direction: "asc"
                },
                maxOptions: 50 // Limit dropdown to 50 results for speed
            };

            // Initialize Search for Quick Invoice
            new TomSelect("#caseSelect", settings);

            // Initialize Search for Payment (Invoice)
            new TomSelect("#paymentInvoiceSelect", settings);

            // Initialize Search for Payment (Direct Client Deposit)
            new TomSelect("#paymentClientSelect", settings);

            // Initialize Search for Credit Note
            new TomSelect("#creditInvoiceSelect", settings);
        });
    </script>
</x-app-layout>
