@extends('layouts.app')
@section('title','Daily Closing '.$dailyClosing->closing_number)

@push('styles')
<style>
@media print {
    .mf-sidebar,
    .mf-topbar,
    [data-mobile-drawer],
    [data-mobile-overlay],
    .no-print { display: none !important; }
    .mf-content { margin: 0 !important; }
    .mf-page { padding: 0 !important; }
    .mf-card,
    .mf-table-frame { break-inside: avoid; }
}
</style>
@endpush

@section('content')
<x-ui.page-toolbar
    :title="$dailyClosing->closing_number"
    :description="'Branch daily closing for '.$dailyClosing->branch->name.' · '.$dailyClosing->closing_date->format('d M Y')"
    :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Cash Closing','url'=>route('cash-closing.index',['branch_id'=>$dailyClosing->branch_id,'date'=>$dailyClosing->closing_date->toDateString()])],['label'=>$dailyClosing->closing_number]]"
>
    <x-slot:actions>
        <a class="mf-btn no-print" href="{{ route('cash-closing.index',['branch_id'=>$dailyClosing->branch_id,'date'=>$dailyClosing->closing_date->toDateString()]) }}">Back</a>
        <button type="button" class="mf-btn no-print" onclick="window.print()">Print</button>
    </x-slot:actions>
</x-ui.page-toolbar>

@php($isStale=$dailyClosing->status==='prepared' && $dailyClosing->snapshot_fingerprint!==$preview['summary']['snapshot_fingerprint'])

@if($isStale)
    <div class="mf-alert mf-alert-danger mb-6 no-print" role="alert">
        The ledger or an active account reconciliation changed after this closing was prepared. Refresh the closing before manager confirmation.
    </div>
@endif

<div class="grid gap-3 md:grid-cols-2 xl:grid-cols-4 mb-6">
    <div class="mf-card mf-card-body">
        <div class="text-xs text-muted-foreground">Status</div>
        <div class="mt-2"><span class="mf-badge {{ $dailyClosing->status==='confirmed'?'mf-badge-success':'mf-badge-warning' }}">{{ ucfirst($dailyClosing->status) }}</span></div>
    </div>
    <div class="mf-card mf-card-body">
        <div class="text-xs text-muted-foreground">Closing funds</div>
        <div class="mt-1 text-xl font-semibold">{{ number_format((float)$dailyClosing->closing_funds,2) }}</div>
    </div>
    <div class="mf-card mf-card-body">
        <div class="text-xs text-muted-foreground">Expected / reconciled funds</div>
        <div class="mt-1 text-xl font-semibold">{{ number_format((float)$dailyClosing->expected_cash,2) }} / {{ number_format((float)$dailyClosing->actual_cash,2) }}</div>
    </div>
    <div class="mf-card mf-card-body">
        <div class="text-xs text-muted-foreground">Account variance</div>
        <div class="mt-1 text-xl font-semibold {{ (float)$dailyClosing->variance!==0.0?'text-destructive':'' }}">{{ number_format((float)$dailyClosing->variance,2) }}</div>
    </div>
</div>

<div class="grid gap-4 xl:grid-cols-[minmax(0,1.4fr)_minmax(320px,.6fr)] mb-6">
    <div class="mf-card min-w-0">
        <div class="mf-card-body border-b">
            <h2 class="text-sm font-semibold">End-of-day financial report</h2>
            <p class="mt-1 text-xs text-muted-foreground">Permanent values stored in this closing snapshot.</p>
        </div>
        <div class="mf-table-frame border-0">
            <table class="mf-table" data-standard-table>
                <tbody>
                    <tr><th>Opening funds</th><td class="text-right font-semibold">{{ number_format((float)$dailyClosing->opening_funds,2) }}</td></tr>
                    <tr><th>Collections</th><td class="text-right">{{ number_format((float)$dailyClosing->collections,2) }}</td></tr>
                    <tr><th>Cash collections</th><td class="text-right">{{ number_format((float)$dailyClosing->cash_collections,2) }}</td></tr>
                    <tr><th>Mobile-money collections</th><td class="text-right">{{ number_format((float)$dailyClosing->mobile_money_collections,2) }}</td></tr>
                    <tr><th>Bank collections</th><td class="text-right">{{ number_format((float)$dailyClosing->bank_collections,2) }}</td></tr>
                    @if((float)$dailyClosing->other_collections!==0.0)
                        <tr><th>Other collections</th><td class="text-right">{{ number_format((float)$dailyClosing->other_collections,2) }}</td></tr>
                    @endif
                    <tr><th>Disbursements</th><td class="text-right">{{ number_format((float)$dailyClosing->disbursements,2) }}</td></tr>
                    <tr><th>Expenses incl. payroll</th><td class="text-right">{{ number_format((float)$dailyClosing->expenses,2) }}</td></tr>
                    <tr><th>Net transfers</th><td class="text-right">{{ number_format((float)$dailyClosing->transfers,2) }}</td></tr>
                    @if((float)$dailyClosing->capital_inflows!==0.0)
                        <tr><th>Capital / account opening inflows</th><td class="text-right">{{ number_format((float)$dailyClosing->capital_inflows,2) }}</td></tr>
                    @endif
                    @if((float)$dailyClosing->other_inflows!==0.0)
                        <tr><th>Other inflows</th><td class="text-right">{{ number_format((float)$dailyClosing->other_inflows,2) }}</td></tr>
                    @endif
                    @if((float)$dailyClosing->other_outflows!==0.0)
                        <tr><th>Other outflows</th><td class="text-right">{{ number_format((float)$dailyClosing->other_outflows,2) }}</td></tr>
                    @endif
                    <tr><th>Closing funds</th><td class="text-right font-semibold">{{ number_format((float)$dailyClosing->closing_funds,2) }}</td></tr>
                    <tr><th>Expected account funds</th><td class="text-right font-semibold">{{ number_format((float)$dailyClosing->expected_cash,2) }}</td></tr>
                    <tr><th>Reconciled account funds</th><td class="text-right font-semibold">{{ number_format((float)$dailyClosing->actual_cash,2) }}</td></tr>
                    <tr><th>Variance</th><td class="text-right font-semibold {{ (float)$dailyClosing->variance!==0.0?'text-destructive':'' }}">{{ number_format((float)$dailyClosing->variance,2) }}</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <div class="mf-card self-start">
        <div class="mf-card-body flex items-start justify-between gap-3 border-b">
            <div>
                <h2 class="text-sm font-semibold">Closing control</h2>
                <p class="mt-1 text-xs text-muted-foreground">Preparation and manager confirmation details.</p>
            </div>
            <span class="mf-badge {{ $dailyClosing->status==='confirmed'?'mf-badge-success':'mf-badge-warning' }}">{{ ucfirst($dailyClosing->status) }}</span>
        </div>

        <div class="mf-card-body">
            <dl class="grid grid-cols-[120px_minmax(0,1fr)] gap-x-3 gap-y-2 text-sm">
                <dt class="text-muted-foreground">Branch</dt><dd>{{ $dailyClosing->branch->name }}</dd>
                <dt class="text-muted-foreground">Prepared by</dt><dd>{{ $dailyClosing->preparer?->name ?? '—' }}</dd>
                <dt class="text-muted-foreground">Prepared at</dt><dd>{{ $dailyClosing->prepared_at?->format('d M Y H:i') ?? '—' }}</dd>
                <dt class="text-muted-foreground">Confirmed by</dt><dd>{{ $dailyClosing->managerConfirmer?->name ?? 'Pending' }}</dd>
                <dt class="text-muted-foreground">Confirmed at</dt><dd>{{ $dailyClosing->manager_confirmed_at?->format('d M Y H:i') ?? '—' }}</dd>
            </dl>

            @if($dailyClosing->manager_comments)
                <div class="mt-4 border-t pt-3">
                    <div class="text-xs text-muted-foreground">Manager comments</div>
                    <div class="mt-1 text-sm">{{ $dailyClosing->manager_comments }}</div>
                </div>
            @endif
        </div>

        @if($dailyClosing->status==='prepared')
            <div class="mf-card-body border-t no-print">
                <div class="flex flex-wrap gap-2 mb-3">
                    @if(auth()->user()->can('daily-closing.prepare'))
                        <form method="POST" action="{{ route('cash-closing.prepare') }}">
                            @csrf
                            <input type="hidden" name="branch_id" value="{{ $dailyClosing->branch_id }}">
                            <input type="hidden" name="date" value="{{ $dailyClosing->closing_date->toDateString() }}">
                            <button class="mf-btn">Refresh snapshot</button>
                        </form>
                    @endif
                </div>

                @if(auth()->user()->can('daily-closing.confirm'))
                    <form method="POST" action="{{ route('cash-closing.confirm',$dailyClosing) }}" class="space-y-3" data-ui="form-shell">
                        @csrf
                        <div>
                            <label class="mf-field-label" for="manager_comments">Manager comments {{ (float)$dailyClosing->variance!==0.0?'(required because variance exists)':'(optional)' }}</label>
                            <textarea id="manager_comments" class="mf-textarea w-full" name="manager_comments" rows="3" placeholder="Confirmation notes">{{ old('manager_comments') }}</textarea>
                        </div>
                        <button class="mf-btn mf-btn-primary w-full" @disabled($isStale)>Confirm and close books</button>
                    </form>
                @endif
            </div>
        @endif
    </div>
</div>

<div class="mf-card mb-6">
    <div class="mf-card-body border-b">
        <h2 class="text-sm font-semibold">Account reconciliation history</h2>
        <p class="mt-1 text-xs text-muted-foreground">Every reconciliation and re-reconciliation is retained; superseded versions are never overwritten.</p>
    </div>

    <div class="mf-table-frame border-0">
        <table class="mf-table" data-standard-table>
            <thead>
                <tr>
                    <th>Reconciliation</th>
                    <th>Account</th>
                    <th>Type</th>
                    <th>Version</th>
                    <th>Opening</th>
                    <th>Money in</th>
                    <th>Money out</th>
                    <th>Expected</th>
                    <th>Actual</th>
                    <th>Variance</th>
                    <th>Status</th>
                    <th>By</th>
                    <th>Explanation</th>
                </tr>
            </thead>
            <tbody>
            @forelse($reconciliations as $rec)
                <tr>
                    <td class="font-medium">{{ $rec->reconciliation_number }}</td>
                    <td>{{ $rec->financialAccount->name }}</td>
                    <td>{{ str($rec->financialAccount->account_type)->replace('_',' ')->title() }}</td>
                    <td>v{{ $rec->version }}</td>
                    <td>{{ number_format((float)$rec->opening_cash,2) }}</td>
                    <td>{{ number_format((float)$rec->cash_in,2) }}</td>
                    <td>{{ number_format((float)$rec->cash_out,2) }}</td>
                    <td>{{ number_format((float)$rec->expected_cash,2) }}</td>
                    <td>{{ number_format((float)$rec->physical_cash,2) }}</td>
                    <td class="{{ (float)$rec->variance!==0.0?'text-destructive font-semibold':'' }}">{{ number_format((float)$rec->variance,2) }}</td>
                    <td><span class="mf-badge {{ $rec->status==='active'?'mf-badge-success':'mf-badge-muted' }}">{{ ucfirst($rec->status) }}</span></td>
                    <td>{{ $rec->reconciler?->name ?? '—' }}</td>
                    <td>{{ $rec->variance_explanation ?: '—' }}</td>
                </tr>
            @empty
                <tr><td colspan="13" class="text-center text-muted-foreground">No account reconciliations were recorded for this branch day.</td></tr>
            @endforelse
            </tbody>
        </table>
    </div>
</div>
@endsection
