@extends('layouts.app')
@section('title','Loan & Branch Reports')
@section('content')
<x-ui.page-toolbar title="Loan & Branch Reports" description="Portfolio, collections, branch and loan-performance reporting from operational records." :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Loan & Branch Reports']]">
    <x-slot:actions>
        <a class="mf-btn" href="{{ route('loan-branch-reports.export', array_merge(['report'=>$report], request()->query())) }}">Export CSV</a>
        <button type="button" class="mf-btn" onclick="window.print()">Print</button>
    </x-slot:actions>
</x-ui.page-toolbar>

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

<form method="GET" action="{{ route('loan-branch-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-[200px]" 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="px-3 pb-2 text-[11px] text-muted-foreground">Clear all selections to include every accessible branch.</div>
                </div>
            </details>

            <select class="mf-filter-control" name="loan_officer_id" aria-label="Loan officer or originator">
                <option value="">All loan officers</option>
                @foreach($loanOfficers as $officer)<option value="{{ $officer->id }}" @selected((string)$filters['loan_officer_id']===(string)$officer->id)>{{ $officer->name }}</option>@endforeach
            </select>

            <select class="mf-filter-control" name="loan_product_id" aria-label="Loan product">
                <option value="">All loan products</option>
                @foreach($loanProducts as $product)<option value="{{ $product->id }}" @selected((string)$filters['loan_product_id']===(string)$product->id)>{{ $product->name }}</option>@endforeach
            </select>

            <input class="mf-filter-control" type="search" name="search" value="{{ $filters['search'] }}" placeholder="Loan, customer, phone…" aria-label="Search loans">

            @if($report==='overdue-loans')
                <select class="mf-filter-control" name="arrears_bucket" aria-label="Arrears bucket">
                    <option value="">All arrears buckets</option>
                    @foreach(['1-7 days','8-30 days','31-60 days','61-90 days','90+ days'] as $bucket)<option value="{{ $bucket }}" @selected($filters['arrears_bucket']===$bucket)>{{ $bucket }}</option>@endforeach
                </select>
            @endif

            @if($statusOptions)
                <select class="mf-filter-control" name="record_status" aria-label="Status">
                    <option value="">All statuses</option>
                    @foreach($statusOptions as $value=>$label)<option value="{{ $value }}" @selected($filters['record_status']===$value)>{{ $label }}</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-start justify-between gap-2">
    <div>
        <div class="text-lg font-semibold">{{ $data['title'] }}</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>
        @if($data['note'])<div class="mt-1 max-w-5xl text-xs text-muted-foreground">{{ $data['note'] }}</div>@endif
    </div>
    <div class="text-xs text-muted-foreground">{{ number_format($data['row_count']) }} row{{ $data['row_count']===1 ? '' : 's' }}</div>
</div>

@if($data['summary'])
<div class="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
    @foreach($data['summary'] as $summary)
        <div class="mf-card mf-card-body">
            <div class="text-xs text-muted-foreground">{{ $summary['label'] }}</div>
            <div class="mt-1 text-lg font-semibold">
                @if($summary['type']==='money'){{ number_format((float)$summary['value'],2) }}
                @elseif($summary['type']==='percent'){{ number_format((float)$summary['value'],2) }}%
                @else{{ number_format((float)$summary['value'],0) }}@endif
            </div>
        </div>
    @endforeach
</div>
@endif

<div class="mf-card">
    <div class="mf-table-frame border-0">
        <table class="mf-table">
            <thead><tr>@foreach($data['columns'] as $key=>$label)<th class="{{ in_array($key,$data['money_columns'],true) || in_array($key,$data['percent_columns'],true) ? 'text-right' : '' }}">{{ $label }}</th>@endforeach</tr></thead>
            <tbody>
            @forelse($data['rows'] as $row)
                <tr>
                @foreach($data['columns'] as $key=>$label)
                    @php($value=$row[$key] ?? '')
                    <td class="{{ in_array($key,$data['money_columns'],true) || in_array($key,$data['percent_columns'],true) ? 'text-right' : '' }}">
                        @if(in_array($key,$data['money_columns'],true)){{ number_format((float)$value,2) }}
                        @elseif(in_array($key,$data['percent_columns'],true)){{ number_format((float)$value,2) }}%
                        @else{{ $value }}@endif
                    </td>
                @endforeach
                </tr>
            @empty
                <tr><td colspan="{{ max(1,count($data['columns'])) }}" class="text-center text-muted-foreground">No records matched the selected filters.</td></tr>
            @endforelse
            </tbody>
        </table>
    </div>
</div>
@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}.mf-table{font-size:10px!important}}</style>
@endpush
