@extends('layouts.app')
@section('title',$writeOff->write_off_number)
@section('content')
<x-ui.page-toolbar :title="$writeOff->write_off_number" :description="'Loan write-off record for '.$writeOff->loan->loan_number.' · '.$writeOff->loan->customer->full_name" :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Loan Write-Offs','url'=>route('loan-write-offs.index')],['label'=>$writeOff->write_off_number]]">
    <x-slot:actions>
        <a class="mf-btn" href="{{ route('loans.show',$writeOff->loan) }}">Open loan</a>
        @if($writeOff->status==='approved' && (float)$writeOff->recoverable_balance>0 && auth()->user()->can('loans.writeoff.recover'))
            <a class="mf-btn mf-btn-primary" href="{{ route('loan-write-offs.recoveries.create',$writeOff) }}">Post recovery</a>
        @endif
    </x-slot:actions>
</x-ui.page-toolbar>

<div class="grid gap-4 md:grid-cols-2 lg:grid-cols-4 mb-4">
    <div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Status</div><div class="mt-1"><span class="mf-badge {{ $writeOff->status==='approved'?'mf-badge-success':($writeOff->status==='rejected'?'mf-badge-danger':'mf-badge-warning') }}">{{ ucfirst($writeOff->status) }}</span></div></div>
    <div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Written-off amount</div><div class="mt-1 font-semibold">{{ number_format((float)$writeOff->write_off_amount,2) }}</div></div>
    <div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Recovered</div><div class="mt-1 font-semibold">{{ number_format((float)$writeOff->recovered_amount,2) }}</div></div>
    <div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Recoverable balance</div><div class="mt-1 font-semibold">{{ number_format((float)$writeOff->recoverable_balance,2) }}</div></div>
</div>

<div class="grid gap-4 lg:grid-cols-3">
<div class="lg:col-span-2 space-y-4">
    <div class="mf-card">
        <div class="border-b p-4"><h2 class="font-semibold">Permanent balance snapshot</h2><p class="mt-1 text-xs text-muted-foreground">Captured when the request was submitted and never recalculated after approval.</p></div>
        <div class="p-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-3 text-sm">
            @foreach([
                'Original principal'=>$writeOff->original_principal,
                'Original total repayment'=>$writeOff->original_total_repayment,
                'Principal outstanding'=>$writeOff->principal_outstanding,
                'Interest outstanding'=>$writeOff->interest_outstanding,
                'Fees outstanding'=>$writeOff->fees_outstanding,
                'Penalties outstanding'=>$writeOff->penalties_outstanding,
            ] as $label=>$value)
                <div><div class="text-xs text-muted-foreground">{{ $label }}</div><div class="font-medium">{{ number_format((float)$value,2) }}</div></div>
            @endforeach
        </div>
    </div>

    <div class="mf-card">
        <div class="border-b p-4"><h2 class="font-semibold">Reason & supporting evidence</h2></div>
        <div class="p-4">
            <p class="text-sm whitespace-pre-line">{{ $writeOff->reason }}</p>
            <div class="mf-table-frame mt-4"><table class="mf-table" data-standard-table>
                <thead><tr><th>Document</th><th>Type</th><th>Uploaded</th><th></th></tr></thead>
                <tbody>
                @forelse($writeOff->documents as $document)
                    <tr><td>{{ $document->original_name }}</td><td>{{ $document->document_type }}</td><td>{{ $document->created_at->format('d M Y H:i') }}<div class="text-xs text-muted-foreground">{{ $document->uploader?->name ?? 'System' }}</div></td><td class="text-right"><a class="text-primary hover:underline" href="{{ route('loan-write-offs.documents.download',[$writeOff,$document]) }}">Download</a></td></tr>
                @empty<tr><td colspan="4" class="text-center text-muted-foreground">No supporting evidence is stored. Approval is blocked.</td></tr>@endforelse
                </tbody>
            </table></div>
        </div>
    </div>

    <div class="mf-card">
        <div class="border-b p-4"><h2 class="font-semibold">Written-off loan recoveries</h2><p class="mt-1 text-xs text-muted-foreground">These receipts are separate from the original loan-payment ledger.</p></div>
        <div class="mf-table-frame border-0"><table class="mf-table" data-standard-table>
            <thead><tr><th>Recovery</th><th>Date</th><th>Amount</th><th>Method</th><th>Account</th><th>Reference</th><th>Received by</th></tr></thead>
            <tbody>
            @forelse($writeOff->recoveries as $recovery)
                <tr>
                    <td class="font-medium">{{ $recovery->recovery_number }}</td>
                    <td>{{ $recovery->recovery_date->format('d M Y H:i') }}</td>
                    <td class="font-semibold">{{ number_format((float)$recovery->amount,2) }}</td>
                    <td>{{ str($recovery->method)->replace('_',' ')->title() }}</td>
                    <td>{{ $recovery->financialAccount->name }}</td>
                    <td>{{ $recovery->reference ?: '—' }}</td>
                    <td>{{ $recovery->receiver?->name ?? '—' }}</td>
                </tr>
            @empty<tr><td colspan="7" class="text-center text-muted-foreground">No recovery has been posted.</td></tr>@endforelse
            </tbody>
        </table></div>
    </div>

    <div class="mf-card">
        <div class="border-b p-4"><h2 class="font-semibold">Original loan history preserved</h2></div>
        <div class="p-4 grid gap-4 md:grid-cols-3 text-sm">
            <div><div class="text-xs text-muted-foreground">Original loan</div><a class="font-medium text-primary hover:underline" href="{{ route('loans.show',$writeOff->loan) }}">{{ $writeOff->loan->loan_number }}</a><div class="text-xs text-muted-foreground">{{ $writeOff->loan->customer->full_name }}</div></div>
            <div><div class="text-xs text-muted-foreground">Payments preserved</div><div class="font-medium">{{ $writeOff->loan->payments->count() }}</div></div>
            <div><div class="text-xs text-muted-foreground">Collection follow-ups preserved</div><div class="font-medium">{{ $writeOff->loan->collectionFollowUps->count() }}</div></div>
            <div><div class="text-xs text-muted-foreground">Collateral preserved</div><div class="font-medium">{{ $writeOff->loan->collaterals->count() }}</div></div>
            <div><div class="text-xs text-muted-foreground">Loan outstanding snapshot</div><div class="font-medium">{{ number_format((float)$writeOff->loan->total_outstanding,2) }}</div><div class="text-xs text-muted-foreground">Historical loan fields are not zeroed by write-off.</div></div>
            <div><div class="text-xs text-muted-foreground">Accounting journal</div><div class="font-medium">{{ $writeOff->accounting_journal_number ?: 'Pending approval' }}</div></div>
        </div>
    </div>
</div>

<div class="space-y-4">
    <div class="mf-card">
        <div class="border-b p-4"><h2 class="font-semibold">Approval record</h2></div>
        <div class="p-4 space-y-3 text-sm">
            <div class="flex justify-between gap-3"><span class="text-muted-foreground">Requested by</span><span>{{ $writeOff->requester?->name ?? '—' }}</span></div>
            <div class="flex justify-between gap-3"><span class="text-muted-foreground">Requested at</span><span>{{ $writeOff->requested_at?->format('d M Y H:i') ?? '—' }}</span></div>
            <div class="flex justify-between gap-3"><span class="text-muted-foreground">Approved by</span><span>{{ $writeOff->approver?->name ?? '—' }}</span></div>
            <div class="flex justify-between gap-3"><span class="text-muted-foreground">Approved at</span><span>{{ $writeOff->approved_at?->format('d M Y H:i') ?? '—' }}</span></div>
            <div class="flex justify-between gap-3"><span class="text-muted-foreground">Rejected by</span><span>{{ $writeOff->rejecter?->name ?? '—' }}</span></div>
            <div class="flex justify-between gap-3"><span class="text-muted-foreground">Rejected at</span><span>{{ $writeOff->rejected_at?->format('d M Y H:i') ?? '—' }}</span></div>
            @if($writeOff->decision_comments)<div class="border-t pt-3"><div class="text-xs text-muted-foreground">Decision comments</div><p class="mt-1">{{ $writeOff->decision_comments }}</p></div>@endif
        </div>
    </div>

    @if($writeOff->status==='pending' && auth()->user()->can('loans.writeoff.approve'))
    <div class="mf-card">
        <div class="border-b p-4"><h2 class="font-semibold">Management decision</h2><p class="mt-1 text-xs text-muted-foreground">Approval rechecks the current balance before any accounting entry or status change is posted.</p></div>
        <form method="POST" action="{{ route('loan-write-offs.decision',$writeOff) }}" class="p-4 space-y-3">
            @csrf
            @if($writeOff->branch->business->maker_checker_enabled && $writeOff->requested_by===auth()->id())
                <div class="rounded-md border p-3 text-xs"><strong>Maker-checker enabled.</strong><div class="mt-1 text-muted-foreground">You requested this write-off and cannot approve it. You may reject it or another authorized manager can approve it.</div></div>
            @endif
            <div><label class="mf-field-label">Decision</label><select class="mf-input" name="decision" required><option value="approve">Approve write-off</option><option value="reject">Reject request</option></select></div>
            <div><label class="mf-field-label">Comments</label><textarea class="mf-input" name="comments" rows="4" placeholder="Required for rejection; optional approval note"></textarea></div>
            <button class="mf-btn mf-btn-primary w-full">Record management decision</button>
        </form>
    </div>
    @endif

    <div class="mf-card">
        <div class="border-b p-4"><h2 class="font-semibold">Collateral custody</h2></div>
        <div class="p-4 space-y-2 text-sm">
            @forelse($writeOff->loan->collaterals as $collateral)
                <a href="{{ route('collateral.show',$collateral) }}" class="block rounded-md border p-3 hover:border-primary">
                    <div class="font-medium">{{ $collateral->code }} · {{ $collateral->item }}</div>
                    <div class="text-xs text-muted-foreground">{{ $collateral->category->name }} · {{ str($collateral->status)->replace('_',' ')->title() }}</div>
                </a>
            @empty<p class="text-muted-foreground">No collateral is linked to this loan.</p>@endforelse
            <p class="pt-2 text-xs text-muted-foreground">Write-off does not automatically release, sell or delete collateral.</p>
        </div>
    </div>
</div>
</div>
@endsection
