@extends('layouts.admin', ['heading' => 'Withdrawals', 'subheading' => 'Queue control, payout retry, and settlement summary'])

@section('content')
    <div class="mb-4 grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
        <div class="admin-card bg-gradient-to-br from-amber-500 to-orange-500 p-4 text-white">
            <div class="text-xs uppercase tracking-wide text-amber-100">Pending Queue</div>
            <div class="mt-2 text-2xl font-bold">{{ number_format((int) $summary['pending_count']) }}</div>
            <div class="text-xs text-amber-100">₹ {{ number_format((float) $summary['pending_amount'], 2) }}</div>
        </div>
        <div class="admin-card bg-gradient-to-br from-indigo-500 to-violet-600 p-4 text-white">
            <div class="text-xs uppercase tracking-wide text-indigo-100">Processing</div>
            <div class="mt-2 text-2xl font-bold">{{ number_format((int) $summary['processing_count']) }}</div>
            <div class="text-xs text-indigo-100">₹ {{ number_format((float) $summary['processing_amount'], 2) }}</div>
        </div>
        <div class="admin-card bg-gradient-to-br from-emerald-500 to-teal-600 p-4 text-white">
            <div class="text-xs uppercase tracking-wide text-emerald-100">Today Settlement</div>
            <div class="mt-2 text-2xl font-bold">₹ {{ number_format((float) $summary['today_paid'], 2) }}</div>
            <div class="text-xs text-emerald-100">Requested: ₹ {{ number_format((float) $summary['today_requested'], 2) }}</div>
        </div>
        <div class="admin-card bg-gradient-to-br from-rose-500 to-rose-600 p-4 text-white">
            <div class="text-xs uppercase tracking-wide text-rose-100">Retry / Failed</div>
            <div class="mt-2 text-2xl font-bold">{{ number_format((int) $summary['retry_queue']) }}</div>
            <div class="text-xs text-rose-100">{{ number_format((int) $summary['failed_count']) }} failed withdrawals</div>
        </div>
    </div>

    <div class="mb-4 grid grid-cols-1 gap-4 xl:grid-cols-3">
        <div class="admin-card p-4">
            <h2 class="mb-2 text-sm font-semibold">Settlement Overview</h2>
            <div class="grid grid-cols-2 gap-2 text-sm">
                <div class="rounded bg-slate-50 p-2">Locked Funds: <span class="font-semibold">₹ {{ number_format((float) $summary['locked_funds'], 2) }}</span></div>
                <div class="rounded bg-slate-50 p-2">TDS Collected: <span class="font-semibold">₹ {{ number_format((float) $summary['tds_collected'], 2) }}</span></div>
                <div class="rounded bg-slate-50 p-2">Charges Collected: <span class="font-semibold">₹ {{ number_format((float) $summary['charges_collected'], 2) }}</span></div>
                <div class="rounded bg-slate-50 p-2">Queue Health: <span class="font-semibold {{ $summary['retry_queue'] > 0 ? 'text-rose-600' : 'text-emerald-600' }}">{{ $summary['retry_queue'] > 0 ? 'Action Needed' : 'Healthy' }}</span></div>
            </div>
            <form method="POST" action="{{ route('admin.withdrawals.retry-failed') }}" class="mt-3 flex gap-2">
                @csrf
                <input type="number" name="limit" value="50" min="1" max="500" class="w-24 rounded border p-2 text-sm">
                <button class="rounded bg-slate-900 px-3 py-2 text-sm text-white">Retry Queue</button>
            </form>
        </div>

        <div class="admin-card p-4 xl:col-span-2">
            <h2 class="mb-2 text-sm font-semibold">TDS / Charge Calculator</h2>
            <div class="grid gap-2 md:grid-cols-4">
                <input id="calcAmount" type="number" step="0.01" min="0" placeholder="Amount" class="rounded border p-2 text-sm">
                <input id="calcTds" type="number" step="0.01" min="0" value="{{ $calcDefaults['tds_percent'] }}" class="rounded border p-2 text-sm">
                <input id="calcCharge" type="number" step="0.01" min="0" value="{{ $calcDefaults['charge_percent'] }}" class="rounded border p-2 text-sm">
                <input id="calcFixed" type="number" step="0.01" min="0" value="{{ $calcDefaults['fixed_charge'] }}" class="rounded border p-2 text-sm">
            </div>
            <div class="mt-2 grid gap-2 text-sm md:grid-cols-3">
                <div class="rounded bg-slate-50 p-2">TDS: ₹ <span id="calcTdsAmount">0.00</span></div>
                <div class="rounded bg-slate-50 p-2">Charges: ₹ <span id="calcChargeAmount">0.00</span></div>
                <div class="rounded bg-emerald-50 p-2 font-semibold text-emerald-700">Net Payout: ₹ <span id="calcNetAmount">0.00</span></div>
            </div>
        </div>
    </div>

    <form method="GET" class="mb-4 grid grid-cols-1 gap-2 md:grid-cols-6">
        <input name="q" value="{{ $search }}" placeholder="Request / member / mobile" class="rounded border p-2 text-sm md:col-span-2">
        <select name="status" class="rounded border p-2 text-sm">
            <option value="">All Status</option>
            @foreach(['pending','processing','approved','rejected','failed','paid'] as $option)
                <option value="{{ $option }}" @selected($status === $option)>{{ ucfirst($option) }}</option>
            @endforeach
        </select>
        <select name="payout_status" class="rounded border p-2 text-sm">
            <option value="">All Payout Status</option>
            @foreach(['initiated','processing','success','failed','retry'] as $option)
                <option value="{{ $option }}" @selected($payoutStatus === $option)>{{ ucfirst($option) }}</option>
            @endforeach
        </select>
        <input name="from" type="date" value="{{ $from }}" class="rounded border p-2 text-sm">
        <input name="to" type="date" value="{{ $to }}" class="rounded border p-2 text-sm">
        <div class="flex flex-wrap gap-2 md:col-span-6">
            <button class="rounded bg-slate-900 px-4 py-2 text-white">Filter</button>
            <a href="{{ route('admin.withdrawals') }}" class="rounded border px-4 py-2 text-sm">Reset</a>
            <a href="{{ request()->fullUrlWithQuery(['export' => 'excel']) }}" class="rounded bg-emerald-600 px-4 py-2 text-sm text-white">Export Excel</a>
            <a href="{{ request()->fullUrlWithQuery(['export' => 'pdf']) }}" class="rounded bg-slate-700 px-4 py-2 text-sm text-white">Export PDF</a>
        </div>
    </form>

    <form id="bulkWithdrawalsForm" method="POST" action="{{ route('admin.withdrawals.bulk-approve') }}">
        @csrf
    </form>
    <div class="mb-3 flex gap-2">
        <button form="bulkWithdrawalsForm" class="rounded bg-emerald-600 px-4 py-2 text-sm text-white">Bulk Approve Selected</button>
    </div>
    <div class="overflow-x-auto rounded-2xl border border-slate-200 bg-white shadow-sm">
        <table class="min-w-full text-sm">
            <thead class="bg-slate-100 text-left">
                <tr>
                    <th class="p-3">
                        <input type="checkbox" data-bulk-toggle="withdrawals">
                    </th>
                    <th class="p-3">Request</th>
                    <th class="p-3">Member</th>
                    <th class="p-3">Amount</th>
                    <th class="p-3">Deductions</th>
                    <th class="p-3">Status</th>
                    <th class="p-3">Payout</th>
                    <th class="p-3">Actions</th>
                </tr>
            </thead>
            <tbody>
                @forelse($withdrawals as $withdrawal)
                    <tr class="border-t">
                        <td class="p-3">
                            <input type="checkbox" name="withdrawal_ids[]" value="{{ $withdrawal->id }}" data-bulk-item="withdrawals" form="bulkWithdrawalsForm">
                        </td>
                        <td class="p-3">
                            <div class="font-semibold">{{ $withdrawal->request_number }}</div>
                            <div class="text-xs text-slate-500">{{ optional($withdrawal->requested_at)->format('Y-m-d H:i') }}</div>
                        </td>
                        <td class="p-3">
                            <div class="font-semibold">{{ $withdrawal->user?->member_code ?? 'N/A' }}</div>
                            <div class="text-xs text-slate-500">{{ $withdrawal->user?->name ?? '' }}</div>
                        </td>
                        <td class="p-3">
                            <div>Gross: ₹ {{ number_format((float) $withdrawal->amount, 2) }}</div>
                            <div class="text-xs text-emerald-700">Net: ₹ {{ number_format((float) $withdrawal->net_amount, 2) }}</div>
                        </td>
                        <td class="p-3">
                            <div class="text-xs text-slate-600">TDS: ₹ {{ number_format((float) $withdrawal->tds_amount, 2) }}</div>
                            <div class="text-xs text-slate-600">Charge: ₹ {{ number_format((float) $withdrawal->charge_amount, 2) }}</div>
                            <div class="text-xs text-indigo-700">Locked: ₹ {{ number_format((float) $withdrawal->locked_amount, 2) }}</div>
                        </td>
                        <td class="p-3">
                            <span class="admin-badge {{ in_array($withdrawal->status, ['paid'], true) ? 'success' : (in_array($withdrawal->status, ['failed','rejected'], true) ? 'danger' : 'warning') }}">
                                {{ strtoupper($withdrawal->status) }}
                            </span>
                        </td>
                        <td class="p-3">
                            <div class="text-xs">
                                <div>Status: {{ $withdrawal->latestPayout?->status ?? '-' }}</div>
                                <div>Attempts: {{ $withdrawal->latestPayout?->attempts ?? 0 }}</div>
                                @if($withdrawal->latestPayout?->failure_reason)
                                    <div class="text-rose-600">{{ $withdrawal->latestPayout->failure_reason }}</div>
                                @endif
                            </div>
                        </td>
                        <td class="p-3">
                            <div class="flex flex-wrap gap-2">
                                <form method="POST" action="{{ route('admin.withdrawals.approve', $withdrawal) }}">
                                    @csrf
                                    <button class="rounded bg-emerald-500 px-3 py-1 text-white" {{ in_array($withdrawal->status, ['paid','rejected'], true) ? 'disabled' : '' }}>Approve</button>
                                </form>
                                <form method="POST" action="{{ route('admin.withdrawals.reject', $withdrawal) }}">
                                    @csrf
                                    <input type="hidden" name="reason" value="Rejected by admin" />
                                    <button class="rounded bg-rose-500 px-3 py-1 text-white" {{ in_array($withdrawal->status, ['paid','rejected'], true) ? 'disabled' : '' }}>Reject</button>
                                </form>
                                <form method="POST" action="{{ route('admin.withdrawals.retry', $withdrawal) }}">
                                    @csrf
                                    <button class="rounded bg-slate-700 px-3 py-1 text-white">Retry Payout</button>
                                </form>
                            </div>
                            <form method="POST" action="{{ route('admin.withdrawals.proof', $withdrawal) }}" enctype="multipart/form-data" class="mt-2 flex flex-wrap gap-2">
                                @csrf
                                <input name="payment_reference" placeholder="Payment Ref" class="rounded border p-1 text-xs">
                                <input type="file" name="payment_proof" class="rounded border p-1 text-xs">
                                <button class="rounded bg-slate-900 px-2 py-1 text-xs text-white">Upload Proof</button>
                            </form>
                        </td>
                    </tr>
                @empty
                    <tr><td colspan="8" class="p-4 text-center text-slate-500">No withdrawals found.</td></tr>
                @endforelse
            </tbody>
            </table>
        </div>

    <div class="mt-4">{{ $withdrawals->links() }}</div>

    <script>
        (function () {
            const amountEl = document.getElementById('calcAmount');
            const tdsEl = document.getElementById('calcTds');
            const chargeEl = document.getElementById('calcCharge');
            const fixedEl = document.getElementById('calcFixed');
            const tdsAmountEl = document.getElementById('calcTdsAmount');
            const chargeAmountEl = document.getElementById('calcChargeAmount');
            const netAmountEl = document.getElementById('calcNetAmount');

            const update = () => {
                const amount = parseFloat(amountEl.value || '0');
                const tdsPercent = parseFloat(tdsEl.value || '0');
                const chargePercent = parseFloat(chargeEl.value || '0');
                const fixed = parseFloat(fixedEl.value || '0');
                const tdsAmount = (amount * tdsPercent) / 100;
                const chargeAmount = ((amount * chargePercent) / 100) + fixed;
                const net = Math.max(0, amount - tdsAmount - chargeAmount);

                tdsAmountEl.textContent = tdsAmount.toFixed(2);
                chargeAmountEl.textContent = chargeAmount.toFixed(2);
                netAmountEl.textContent = net.toFixed(2);
            };

            [amountEl, tdsEl, chargeEl, fixedEl].forEach((el) => {
                el.addEventListener('input', update);
            });
            update();
        })();
    </script>
@endsection

