@extends('layouts.app')
@section('title','Financial Reports')
@section('content')
<x-ui.page-toolbar title="Financial Reports" description="Transaction-backed financial reporting with branch and date reconciliation." :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Financial Reports']]">
    <x-slot:actions><a class="mf-btn" href="{{ route('reports.export', array_merge(['report'=>$report], request()->query())) }}">Download CSV</a><button type="button" class="mf-btn" onclick="window.print()">Print Report</button></x-slot:actions>
</x-ui.page-toolbar>

<div class="flex flex-wrap gap-2 mb-3 print:hidden">
    @foreach($reports as $slug=>$label)
        <a class="mf-btn {{ $report===$slug ? 'mf-btn-primary' : '' }}" href="{{ route('reports.index', array_merge(['report'=>$slug], request()->except('account_id'))) }}">{{ $label }}</a>
    @endforeach
</div>

<form method="GET" action="{{ route('reports.index',['report'=>$report]) }}" class="mf-table-toolbar mb-4 print:hidden" data-ui="table-toolbar">
    <div class="mf-table-toolbar-left">
        <div class="mf-table-quick-filters">
            <input class="mf-filter-control" type="date" name="from" value="{{ $from }}" required aria-label="From date" title="From date">
            <input class="mf-filter-control" type="date" name="to" value="{{ $to }}" required aria-label="To date" title="To date">

            <details class="mf-columns-menu">
                <summary class="mf-filter-control cursor-pointer min-w-[220px]" style="line-height: 2.4" aria-label="Select branches">
                    {{ $selectedBranches->count() ? ($selectedBranches->count() === 1 ? $selectedBranches->first()->name : $selectedBranches->count().' branches') : 'All branches' }}
                </summary>
                <div class="mf-columns-popover">
                    <div class="mf-columns-title">Branches</div>
                    @foreach($branches as $branch)
                        <label>
                            <input type="checkbox" name="branch_ids[]" value="{{ $branch->id }}" @checked($selectedBranchIds->contains($branch->id))>
                            <span>{{ $branch->name }}</span>
                        </label>
                    @endforeach
                    <div class="text-[11px] text-muted-foreground px-3 pb-2" style="line-height: 1.2">Clear all selections to include every accessible branch.</div>
                </div>
            </details>

            @if($report==='account-statement')
                <select class="mf-filter-control" name="account_id" aria-label="Account">
                    <option value="">All account summaries</option>
                    @foreach($accounts as $account)<option value="{{ $account->id }}" @selected($accountId===$account->id)>{{ $account->branch->name }} — {{ $account->name }}</option>@endforeach
                </select>
            @endif
        </div>
        <button class="mf-btn mf-btn-sm" type="submit">Run Report</button>
    </div>
</form>

<div class="mb-4 flex flex-wrap items-center justify-between gap-2">
    <div><div class="text-lg font-semibold">{{ $reports[$report] }}</div><div class="text-xs text-muted-foreground">{{ \Carbon\Carbon::parse($from)->format('d M Y') }} — {{ \Carbon\Carbon::parse($to)->format('d M Y') }} · {{ $selectedBranches->pluck('name')->join(', ') }}</div></div>
</div>

@switch($report)
@case('trial-balance')
    <div class="grid gap-3 md:grid-cols-4 mb-4"><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Period debits</div><div class="text-xl font-semibold">{{ number_format((float)$data['period_debits'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Period credits</div><div class="text-xl font-semibold">{{ number_format((float)$data['period_credits'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Closing debit balances</div><div class="text-xl font-semibold">{{ number_format((float)$data['debit_balances'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Difference</div><div class="text-xl font-semibold">{{ number_format((float)$data['difference'],2) }}</div><div class="text-[11px] text-muted-foreground">{{ $data['balanced']?'Balanced':'Review ledger scope / inter-branch postings' }}</div></div></div>
    <div class="mf-card"><div class="mf-table-frame border-0"><table class="mf-table"><thead><tr><th>Account / Ledger Category</th><th class="text-right">Opening</th><th class="text-right">Debit</th><th class="text-right">Credit</th><th class="text-right">Closing Debit</th><th class="text-right">Closing Credit</th></tr></thead><tbody>@forelse($data['rows'] as $row)<tr><td>{{ $row['label'] }}</td><td class="text-right">{{ number_format((float)$row['opening_balance'],2) }}</td><td class="text-right">{{ number_format((float)$row['period_debit'],2) }}</td><td class="text-right">{{ number_format((float)$row['period_credit'],2) }}</td><td class="text-right font-medium">{{ number_format((float)$row['debit_balance'],2) }}</td><td class="text-right font-medium">{{ number_format((float)$row['credit_balance'],2) }}</td></tr>@empty<tr><td colspan="6" class="text-center text-muted-foreground">No accounting entries in this scope.</td></tr>@endforelse<tr><td class="font-semibold">TOTAL</td><td></td><td class="text-right font-semibold">{{ number_format((float)$data['period_debits'],2) }}</td><td class="text-right font-semibold">{{ number_format((float)$data['period_credits'],2) }}</td><td class="text-right font-semibold">{{ number_format((float)$data['debit_balances'],2) }}</td><td class="text-right font-semibold">{{ number_format((float)$data['credit_balances'],2) }}</td></tr></tbody></table></div></div>
@break

@case('income-statement')
    <div class="grid gap-3 md:grid-cols-3 mb-4"><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Total income</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_income'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Total expenses</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_expenses'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Net profit / loss</div><div class="text-xl font-semibold">{{ number_format((float)$data['net_profit'],2) }}</div></div></div>
    <div class="grid gap-4 lg:grid-cols-2"><div class="mf-card"><div class="mf-table-frame border-0"><table class="mf-table"><thead><tr><th>Income</th><th class="text-right">Amount</th></tr></thead><tbody>@foreach($data['income_rows'] as $row)<tr><td>{{ $row['label'] }}</td><td class="text-right">{{ number_format((float)$row['amount'],2) }}</td></tr>@endforeach<tr><td class="font-semibold">Total income</td><td class="text-right font-semibold">{{ number_format((float)$data['total_income'],2) }}</td></tr></tbody></table></div></div><div class="mf-card"><div class="mf-table-frame border-0"><table class="mf-table"><thead><tr><th>Expense</th><th class="text-right">Amount</th></tr></thead><tbody>@foreach($data['expense_rows'] as $row)<tr><td>{{ $row['label'] }}</td><td class="text-right">{{ number_format((float)$row['amount'],2) }}</td></tr>@endforeach<tr><td class="font-semibold">Total expenses</td><td class="text-right font-semibold">{{ number_format((float)$data['total_expenses'],2) }}</td></tr></tbody></table></div></div></div>
@break

@case('statement-of-financial-position')
    <div class="grid gap-3 md:grid-cols-4 mb-4"><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Total assets</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_assets'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Total liabilities</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_liabilities'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Total equity</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_equity'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Accounting difference</div><div class="text-xl font-semibold">{{ number_format((float)$data['difference'],2) }}</div><div class="text-[11px] text-muted-foreground">As of {{ \Carbon\Carbon::parse($data['as_of'])->format('d M Y') }}</div></div></div>
    <div class="grid gap-4 lg:grid-cols-2"><div class="mf-card"><div class="border-b p-4"><h2 class="font-semibold">Assets</h2></div><div class="mf-table-frame border-0"><table class="mf-table"><tbody>@foreach($data['asset_rows'] as $row)<tr><td>{{ $row['label'] }}</td><td class="text-right">{{ number_format((float)$row['amount'],2) }}</td></tr>@endforeach<tr><td class="font-semibold">Total Assets</td><td class="text-right font-semibold">{{ number_format((float)$data['total_assets'],2) }}</td></tr></tbody></table></div></div><div class="mf-card"><div class="border-b p-4"><h2 class="font-semibold">Liabilities & Equity</h2></div><div class="mf-table-frame border-0"><table class="mf-table"><tbody><tr><td>Total Liabilities</td><td class="text-right">{{ number_format((float)$data['total_liabilities'],2) }}</td></tr>@foreach($data['equity_rows'] as $row)<tr><td>{{ $row['label'] }}</td><td class="text-right">{{ number_format((float)$row['amount'],2) }}</td></tr>@endforeach<tr><td class="font-semibold">Total Equity</td><td class="text-right font-semibold">{{ number_format((float)$data['total_equity'],2) }}</td></tr></tbody></table></div></div></div>
    <div class="mt-3 text-xs text-muted-foreground">{{ $data['liability_note'] }}</div>
@break

@case('portfolio-summary')
    <div class="grid gap-3 md:grid-cols-4 mb-4"><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Active loans</div><div class="text-xl font-semibold">{{ number_format($data['active_loans']) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Principal outstanding</div><div class="text-xl font-semibold">{{ number_format((float)$data['principal_outstanding'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Total outstanding</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_outstanding'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Portfolio at risk</div><div class="text-xl font-semibold">{{ $data['portfolio_at_risk_percent'] }}%</div><div class="text-[11px] text-muted-foreground">{{ $data['overdue_loans'] }} overdue loans</div></div></div>
    <div class="grid gap-3 md:grid-cols-4 mb-4"><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Interest outstanding</div><div class="font-semibold">{{ number_format((float)$data['interest_outstanding'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Fees outstanding</div><div class="font-semibold">{{ number_format((float)$data['fees_outstanding'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Penalties outstanding</div><div class="font-semibold">{{ number_format((float)$data['penalties_outstanding'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Total overdue</div><div class="font-semibold">{{ number_format((float)$data['total_overdue'],2) }}</div></div></div>
    <div class="mf-card"><div class="mf-table-frame border-0"><table class="mf-table"><thead><tr><th>Branch</th><th>Active Loans</th><th class="text-right">Principal Outstanding</th><th class="text-right">Total Outstanding</th><th class="text-right">Overdue</th><th class="text-right">PAR %</th></tr></thead><tbody>@forelse($data['branch_rows'] as $row)<tr><td>{{ $row['branch']->name }}</td><td>{{ $row['active_loans'] }}</td><td class="text-right">{{ number_format((float)$row['principal_outstanding'],2) }}</td><td class="text-right">{{ number_format((float)$row['total_outstanding'],2) }}</td><td class="text-right">{{ number_format((float)$row['overdue'],2) }}</td><td class="text-right">{{ $row['par_percent'] }}%</td></tr>@empty<tr><td colspan="6" class="text-center text-muted-foreground">No active loans in this scope.</td></tr>@endforelse</tbody></table></div></div>
    <div class="mt-3 text-xs text-muted-foreground">{{ $data['historical_note'] }}</div>
@break

@case('profit-loss')
    <div class="grid gap-3 md:grid-cols-3 mb-4"><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Total income</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_income'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Total expenses</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_expenses'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Net profit / loss</div><div class="text-xl font-semibold">{{ number_format((float)$data['net_profit'],2) }}</div></div></div>
    <div class="grid gap-4 lg:grid-cols-2"><div class="mf-card"><div class="mf-table-frame border-0"><table class="mf-table"><thead><tr><th>Income</th><th class="text-right">Amount</th></tr></thead><tbody>@foreach($data['income_rows'] as $row)<tr><td>{{ $row['label'] }}</td><td class="text-right">{{ number_format((float)$row['amount'],2) }}</td></tr>@endforeach<tr><td class="font-semibold">Total income</td><td class="text-right font-semibold">{{ number_format((float)$data['total_income'],2) }}</td></tr></tbody></table></div></div><div class="mf-card"><div class="mf-table-frame border-0"><table class="mf-table"><thead><tr><th>Expense</th><th class="text-right">Amount</th></tr></thead><tbody>@foreach($data['expense_rows'] as $row)<tr><td>{{ $row['label'] }}</td><td class="text-right">{{ number_format((float)$row['amount'],2) }}</td></tr>@endforeach<tr><td class="font-semibold">Total expenses</td><td class="text-right font-semibold">{{ number_format((float)$data['total_expenses'],2) }}</td></tr></tbody></table></div></div></div>
    <div class="mt-3 text-xs text-muted-foreground">Loan principal credits excluded from revenue: {{ number_format((float)$data['principal_activity_excluded'],2) }}.</div>
@break

@case('cash-flow')
    <div class="grid gap-3 md:grid-cols-3 mb-4"><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Cash in</div><div class="text-xl font-semibold">{{ number_format((float)$data['money_in'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Cash out</div><div class="text-xl font-semibold">{{ number_format((float)$data['money_out'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Net cash flow</div><div class="text-xl font-semibold">{{ number_format((float)$data['net_cash_flow'],2) }}</div></div></div>
    <div class="mf-card"><div class="mf-table-frame border-0"><table class="mf-table"><thead><tr><th>Movement</th><th>Transactions</th><th class="text-right">Money in</th><th class="text-right">Money out</th><th class="text-right">Net</th></tr></thead><tbody>@forelse($data['rows'] as $row)<tr><td>{{ $row['label'] }}</td><td>{{ $row['count'] }}</td><td class="text-right">{{ number_format((float)$row['money_in'],2) }}</td><td class="text-right">{{ number_format((float)$row['money_out'],2) }}</td><td class="text-right">{{ number_format((float)$row['net'],2) }}</td></tr>@empty<tr><td colspan="5" class="text-center text-muted-foreground">No financial movements in this period.</td></tr>@endforelse</tbody></table></div></div>
@break

@case('account-statement')
    <div class="mf-card mb-4"><div class="mf-table-frame border-0"><table class="mf-table"><thead><tr><th>Account</th><th>Branch</th><th class="text-right">Opening</th><th class="text-right">Money in</th><th class="text-right">Money out</th><th class="text-right">Closing</th></tr></thead><tbody>@foreach($data['summaries'] as $summary)<tr><td>{{ $summary['account']->name }}</td><td>{{ $summary['account']->branch->name }}</td><td class="text-right">{{ number_format((float)$summary['opening_balance'],2) }}</td><td class="text-right">{{ number_format((float)$summary['money_in'],2) }}</td><td class="text-right">{{ number_format((float)$summary['money_out'],2) }}</td><td class="text-right font-semibold">{{ number_format((float)$summary['closing_balance'],2) }}</td></tr>@endforeach</tbody></table></div></div>
    @if($accountId)<div class="mf-card"><div class="mf-table-frame border-0"><table class="mf-table"><thead><tr><th>Date</th><th>Transaction</th><th>Reference</th><th>Description</th><th class="text-right">In</th><th class="text-right">Out</th><th class="text-right">Balance</th></tr></thead><tbody>@forelse($data['rows'] as $row)@php($tx=$row['transaction'])<tr><td>{{ $tx->transaction_date->format('d M Y H:i') }}</td><td>{{ $tx->transaction_number }}</td><td>{{ $tx->reference }}</td><td>{{ $tx->description }}</td><td class="text-right">{{ number_format((float)$tx->money_in,2) }}</td><td class="text-right">{{ number_format((float)$tx->money_out,2) }}</td><td class="text-right font-semibold">{{ number_format((float)$row['report_balance'],2) }}</td></tr>@empty<tr><td colspan="7" class="text-center text-muted-foreground">No transactions for this account in the period.</td></tr>@endforelse</tbody></table></div></div>@endif
@break

@case('capital')
    <div class="grid gap-3 md:grid-cols-3 mb-4"><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Total capital</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_capital'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Opening funds</div><div class="text-xl font-semibold">{{ number_format((float)$data['opening_funds'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Capital injections</div><div class="text-xl font-semibold">{{ number_format((float)$data['capital_injections'],2) }}</div></div></div>
    @include('reports.partials.transaction-table',['rows'=>$data['rows'],'amountField'=>'money_in'])
@break

@case('expenses')
    <div class="mf-card mf-card-body mb-4"><div class="text-xs text-muted-foreground">Approved expenses</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_expenses'],2) }}</div></div>
    <div class="mf-card"><div class="mf-table-frame border-0"><table class="mf-table"><thead><tr><th>Date</th><th>Expense</th><th>Branch</th><th>Category</th><th>Description / Supplier</th><th>Account</th><th class="text-right">Amount</th></tr></thead><tbody>@forelse($data['rows'] as $expense)<tr><td>{{ $expense->expense_date->format('d M Y') }}</td><td>{{ $expense->expense_number }}</td><td>{{ $expense->branch->name }}</td><td>{{ $expense->category->name }}</td><td>{{ $expense->description }}<div class="text-xs text-muted-foreground">{{ $expense->supplier ?: '—' }}</div></td><td>{{ $expense->financialAccount->name }}</td><td class="text-right font-semibold">{{ number_format((float)$expense->amount,2) }}</td></tr>@empty<tr><td colspan="7" class="text-center text-muted-foreground">No approved expenses in this period.</td></tr>@endforelse</tbody></table></div></div>
@break

@case('payroll')
    <div class="grid gap-3 md:grid-cols-3 mb-4"><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Gross payroll</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_gross'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Deductions</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_deductions'],2) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Net paid</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_net'],2) }}</div></div></div>
    <div class="mf-card"><div class="mf-table-frame border-0"><table class="mf-table"><thead><tr><th>Paid</th><th>Payslip</th><th>Employee</th><th>Branch</th><th>Period</th><th class="text-right">Gross</th><th class="text-right">Deductions</th><th class="text-right">Net</th></tr></thead><tbody>@forelse($data['rows'] as $entry)<tr><td>{{ $entry->paid_at?->format('d M Y H:i') }}</td><td>{{ $entry->payslip_number }}</td><td>{{ $entry->employee_name_snapshot }}</td><td>{{ $entry->branch->name }}</td><td>{{ $entry->period->period_number }}</td><td class="text-right">{{ number_format((float)$entry->gross,2) }}</td><td class="text-right">{{ number_format((float)$entry->total_deductions,2) }}</td><td class="text-right font-semibold">{{ number_format((float)$entry->net,2) }}</td></tr>@empty<tr><td colspan="8" class="text-center text-muted-foreground">No paid payroll entries in this period.</td></tr>@endforelse</tbody></table></div></div>
@break

@case('collections')
    <div class="mf-card mf-card-body mb-4"><div class="text-xs text-muted-foreground">Total collections</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_collections'],2) }}</div></div>
    @include('reports.partials.transaction-table',['rows'=>$data['rows'],'amountField'=>'money_in'])
@break

@case('disbursements')
    <div class="mf-card mf-card-body mb-4"><div class="text-xs text-muted-foreground">Total disbursements</div><div class="text-xl font-semibold">{{ number_format((float)$data['total_disbursements'],2) }}</div></div>
    @include('reports.partials.transaction-table',['rows'=>$data['rows'],'amountField'=>'money_out'])
@break
@endswitch
@endsection

@push('styles')
<style>@media print{.mf-sidebar,.mf-topbar,.print\:hidden{display:none!important}.mf-content{margin:0!important}.mf-page{padding:0!important}.mf-card{box-shadow:none!important}}</style>
@endpush
