@extends('layouts.admin')

@section('title', 'Financial Reports')

@section('content')
<div class="container mx-auto px-2 sm:px-4 lg:px-6 py-3 sm:py-4 lg:py-6">
    <div class="mb-6 flex items-center justify-between">
        <div>
            <h1 class="text-xl sm:text-2xl lg:text-3xl font-bold text-gray-900">Financial Reports</h1>
            <p class="text-xs sm:text-sm text-gray-600 mt-1">Track invoices, payments, expenses and top merchants</p>
        </div>
        <a href="{{ route('admin.finance.reports.export') }}" class="text-xs bg-blue-600 text-white px-3 py-2 rounded-md hover:bg-blue-700">Go to Export Center</a>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-4 mb-4">
        <form id="filtersForm" class="grid grid-cols-1 md:grid-cols-5 gap-3 items-end">
            <div>
                <label class="block text-xs text-gray-600 mb-1">Start Date</label>
                <input type="date" id="startDate" class="border rounded-md px-3 py-2 w-full" />
            </div>
            <div>
                <label class="block text-xs text-gray-600 mb-1">End Date</label>
                <input type="date" id="endDate" class="border rounded-md px-3 py-2 w-full" />
            </div>
            <div class="md:col-span-2">
                <p class="text-[11px] text-gray-500">Select a date range to filter financial metrics and rankings.</p>
            </div>
            <div class="flex md:justify-end">
                <button type="button" id="applyFilters" class="bg-blue-600 text-white px-3 sm:px-4 py-2 rounded-md text-xs sm:text-sm font-semibold hover:bg-blue-700 transition">Load Data</button>
            </div>
        </form>
    </div>

    <!-- Metric Cards -->
    <div class="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 mb-4 sm:mb-6">
        <div class="bg-white rounded-lg shadow-md p-3 sm:p-4">
            <p class="text-[10px] sm:text-xs text-gray-600">Total Invoices</p>
            <p id="totalInvoices" class="text-lg sm:text-xl font-semibold text-gray-900">—</p>
        </div>
        <div class="bg-white rounded-lg shadow-md p-3 sm:p-4">
            <p class="text-[10px] sm:text-xs text-gray-600">Outstanding Amount</p>
            <p id="outstandingAmount" class="text-lg sm:text-xl font-semibold text-gray-900">—</p>
        </div>
        <div class="bg-white rounded-lg shadow-md p-3 sm:p-4">
            <p class="text-[10px] sm:text-xs text-gray-600">Total Payments</p>
            <p id="totalPayments" class="text-lg sm:text-xl font-semibold text-gray-900">—</p>
        </div>
        <div class="bg-white rounded-lg shadow-md p-3 sm:p-4">
            <p class="text-[10px] sm:text-xs text-gray-600">Approved Expenses</p>
            <p id="approvedExpenses" class="text-lg sm:text-xl font-semibold text-gray-900">—</p>
        </div>
    </div>

    <!-- Top Merchants -->
    <div class="bg-white rounded-lg border border-gray-200">
        <div class="px-4 py-3 border-b border-gray-200">
            <h2 class="text-sm font-semibold text-gray-900">Top Merchants by Billing</h2>
            <p class="text-[11px] text-gray-500">Top 5 sellers by total invoice amount</p>
        </div>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 py-2 text-left text-[11px] font-medium text-gray-600 uppercase tracking-wider">Seller ID</th>
                        <th class="px-4 py-2 text-left text-[11px] font-medium text-gray-600 uppercase tracking-wider">Invoice Count</th>
                        <th class="px-4 py-2 text-left text-[11px] font-medium text-gray-600 uppercase tracking-wider">Total Billed</th>
                    </tr>
                </thead>
                <tbody id="topMerchantsBody" class="bg-white divide-y divide-gray-200">
                    <tr>
                        <td class="px-4 py-2 text-sm text-gray-700" colspan="3">No data loaded yet.</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <div class="mt-4 text-xs text-gray-500">Use the Export Center to download CSV extracts.</div>
</div>

<script>
const currencyFormat = (value) => {
    try {
        const num = Number(value);
        return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(num);
    } catch (e) {
        return value;
    }
};

async function loadFinancialData() {
    const start = document.getElementById('startDate').value;
    const end = document.getElementById('endDate').value;
    const baseUrl = "{{ route('admin.finance.reports.financial.data') }}";
    const url = new URL(baseUrl, window.location.origin);
    if (start) url.searchParams.set('start_date', start);
    if (end) url.searchParams.set('end_date', end);

    // Show loading placeholders
    document.getElementById('totalInvoices').textContent = 'Loading…';
    document.getElementById('outstandingAmount').textContent = 'Loading…';
    document.getElementById('totalPayments').textContent = 'Loading…';
    document.getElementById('approvedExpenses').textContent = 'Loading…';
    document.getElementById('topMerchantsBody').innerHTML = `<tr><td class="px-4 py-2 text-sm text-gray-700" colspan="3">Loading…</td></tr>`;

    try {
        const res = await fetch(url.toString(), { headers: { 'Accept': 'application/json' } });
        if (!res.ok) throw new Error('Failed to load financial data');
        const data = await res.json();

        // Metrics
        document.getElementById('totalInvoices').textContent = Number(data.total_invoices || 0).toLocaleString();
        document.getElementById('outstandingAmount').textContent = currencyFormat(data.outstanding_amount || 0);
        document.getElementById('totalPayments').textContent = currencyFormat(data.total_payments || 0);
        document.getElementById('approvedExpenses').textContent = currencyFormat(data.approved_expenses || 0);

        // Top merchants
        const rows = (data.top_merchants || []).map(m => `
            <tr>
                <td class="px-4 py-2 text-sm text-gray-700">${m.seller_id}</td>
                <td class="px-4 py-2 text-sm text-gray-700">${Number(m.invoice_count || 0).toLocaleString()}</td>
                <td class="px-4 py-2 text-sm text-gray-700">${currencyFormat(m.total_billed || 0)}</td>
            </tr>
        `);
        document.getElementById('topMerchantsBody').innerHTML = rows.length ? rows.join('') : `<tr><td class="px-4 py-2 text-sm text-gray-700" colspan="3">No merchants found for selected range.</td></tr>`;
    } catch (err) {
        console.error(err);
        document.getElementById('topMerchantsBody').innerHTML = `<tr><td class="px-4 py-2 text-sm text-red-600" colspan="3">Error loading data.</td></tr>`;
        document.getElementById('totalInvoices').textContent = '—';
        document.getElementById('outstandingAmount').textContent = '—';
        document.getElementById('totalPayments').textContent = '—';
        document.getElementById('approvedExpenses').textContent = '—';
    }
}

document.getElementById('applyFilters').addEventListener('click', loadFinancialData);
document.addEventListener('DOMContentLoaded', loadFinancialData);
</script>
@endsection



