@extends('layouts.app')
@section('title',$loan->loan_number)
@section('content')
<x-ui.page-toolbar :title="$loan->loan_number" :description="'Loan application for '.$loan->customer->full_name.' · '.$loan->product->name" :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Loan Applications','url'=>route('loans.index')],['label'=>$loan->loan_number]]">
<x-slot:actions>
    @if(auth()->user()->can('loans.approve'))<a class="mf-btn" href="{{ route('loans.approvals.index') }}">Approval queue</a>@endif
    @if($loan->canEditCoreTerms() && auth()->user()->can('loans.update'))<a class="mf-btn" href="{{ route('loans.edit',$loan) }}">{{ $loan->status==='correction_requested'?'Apply correction':'Edit draft' }}</a>@endif
    @if($loan->canGenerateContract() && auth()->user()->can('loans.contract'))<form method="POST" action="{{ route('loans.contract',$loan) }}" class="inline">@csrf<button class="mf-btn mf-btn-primary">Generate contract</button></form>@endif
</x-slot:actions>
</x-ui.page-toolbar>

<div class="mf-stat-grid 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 {{ $loan->status==='ready_for_disbursement'?'mf-badge-success':'mf-badge-muted' }}">{{ str($loan->status)->replace('_',' ')->title() }}</span></div></div>
<div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Principal</div><div class="mt-1 font-semibold">{{ number_format((float)$loan->principal,2) }}</div></div>
<div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Interest + fees</div><div class="mt-1 font-semibold">{{ number_format((float)($loan->interest+$loan->fees),2) }}</div></div>
<div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Total repayment</div><div class="mt-1 font-semibold">{{ number_format((float)$loan->total_repayment,2) }}</div></div>
</div>

@if(auth()->user()->can('credit-score.view'))
@php
    $applicationScore = $loan->applicationCreditScoreHistory;
    $currentScore = $loan->customer->riskProfile;
    $reviewScore = $applicationScore ?: $currentScore;
    $reviewFactors = $reviewScore?->factors ?? [];
    $reviewComponents = collect(data_get($reviewFactors, 'components', []));
    $positiveFactors = $reviewComponents->flatMap(fn($component) => $component['positive_factors'] ?? [])->filter()->take(3);
    $negativeFactors = $reviewComponents->flatMap(fn($component) => $component['negative_factors'] ?? [])->filter()->take(3);
    $affordability = data_get($reviewFactors, 'components.affordability.factors', []);
    $collateralScore = data_get($reviewFactors, 'components.collateral.factors', []);
    $reviewBandLabel = data_get($reviewFactors, 'band_label') ?: str($reviewScore?->score_band ?? 'unrated')->replace('_',' ')->title();
    $currentIsNewer = $applicationScore && $currentScore && $currentScore->calculated_at && $applicationScore->calculated_at && $currentScore->calculated_at->gt($applicationScore->calculated_at);
    $currentDiffers = $applicationScore && $currentScore && (
        (int) round((float)$applicationScore->score) !== (int) round((float)$currentScore->score)
        || $applicationScore->score_version !== $currentScore->score_version
        || $currentIsNewer
    );
@endphp
<div class="mf-card mb-4">
    <div class="flex flex-col gap-2 border-b p-4 sm:flex-row sm:items-start sm:justify-between">
        <div><h2 class="font-semibold">Credit review</h2><p class="mt-1 text-xs text-muted-foreground">Decision support only. The score does not approve or reject this application.</p></div>
        @if(auth()->user()->can('credit-score.history'))<a class="mf-btn" href="{{ route('customers.credit-score.history',$loan->customer) }}">Customer score history</a>@endif
    </div>
    @if($reviewScore && $reviewScore->score !== null)
    <div class="grid gap-0 lg:grid-cols-[240px_1fr]">
        <div class="border-b p-4 lg:border-b-0 lg:border-r">
            <div class="text-xs font-medium uppercase tracking-wide text-muted-foreground">{{ $applicationScore ? 'Application score' : 'Current score' }}</div>
            <div class="mt-2 text-4xl font-semibold leading-none">{{ (int) round((float)$reviewScore->score) }}</div>
            <div class="mt-2 text-sm font-medium">{{ $reviewBandLabel }}</div>
            <div class="mt-2 flex flex-wrap gap-1">
                <span class="mf-badge mf-badge-muted">{{ str($reviewScore->risk_level)->replace('_',' ')->title() }} risk</span>
                @if($reviewScore->thin_file)<span class="mf-badge mf-badge-muted">Thin file</span>@endif
                @if($reviewScore->manual_review_required)<span class="mf-badge">Manual review</span>@endif
            </div>
            <div class="mt-4 grid grid-cols-2 gap-3 text-sm">
                <div><div class="text-xs text-muted-foreground">Confidence</div><div class="font-medium">{{ number_format((float)$reviewScore->confidence,0) }}%</div></div>
                <div><div class="text-xs text-muted-foreground">Version</div><div class="font-medium">{{ strtoupper($reviewScore->score_version ?? '—') }}</div></div>
            </div>
            <div class="mt-3 text-xs text-muted-foreground">{{ $applicationScore ? 'Captured' : 'Calculated' }} {{ $reviewScore->calculated_at?->format('d M Y H:i') ?? '—' }}</div>
            @if($currentDiffers)
            <div class="mt-4 border-t pt-3"><div class="text-xs text-muted-foreground">Current score</div><div class="mt-1 flex items-end gap-2"><span class="text-xl font-semibold">{{ (int) round((float)$currentScore->score) }}</span><span class="text-xs text-muted-foreground">{{ str($currentScore->score_band)->replace('_',' ')->title() }}</span></div><div class="mt-1 text-xs text-muted-foreground">Updated {{ $currentScore->calculated_at?->format('d M Y H:i') }}</div></div>
            @endif
        </div>
        <div class="p-4">
            @if($reviewScore->manual_review_required)<div class="mb-3 border-l-2 border-current pl-3 text-sm"><span class="font-medium">Manual review required.</span> <span class="text-muted-foreground">This flag asks the reviewer to inspect the underlying data; it is not an automatic decline.</span></div>@endif
            <div class="grid gap-3 sm:grid-cols-3 text-sm">
                <div><div class="text-xs text-muted-foreground">Debt service ratio</div><div class="font-medium">{{ array_key_exists('debt_service_ratio',$affordability) ? number_format(((float)$affordability['debt_service_ratio'])*100,1).'%' : '—' }}</div></div>
                <div><div class="text-xs text-muted-foreground">Collateral coverage</div><div class="font-medium">{{ array_key_exists('coverage_ratio',$collateralScore) ? number_format((float)$collateralScore['coverage_ratio'],2).'×' : (data_get($collateralScore,'required')===false?'Not required':'—') }}</div></div>
                <div><div class="text-xs text-muted-foreground">Current arrears</div><div class="font-medium">{{ (int)($loan->days_overdue ?? 0) }} days · {{ number_format((float)($loan->total_overdue ?? 0),2) }}</div></div>
            </div>
            <p class="mt-4 text-sm">{{ $reviewScore->explanation ?: 'No score explanation is available.' }}</p>
            <div class="mt-4 grid gap-4 md:grid-cols-2">
                <div><div class="text-xs font-medium uppercase tracking-wide text-muted-foreground">Positive factors</div><div class="mt-2 space-y-1.5">@forelse($positiveFactors as $factor)<div class="text-sm">+ {{ $factor }}</div>@empty<div class="text-sm text-muted-foreground">No strong positive factor recorded.</div>@endforelse</div></div>
                <div><div class="text-xs font-medium uppercase tracking-wide text-muted-foreground">Factors to review</div><div class="mt-2 space-y-1.5">@forelse($negativeFactors as $factor)<div class="text-sm">− {{ $factor }}</div>@empty<div class="text-sm text-muted-foreground">No major negative factor recorded.</div>@endforelse</div></div>
            </div>
            @if(!$applicationScore)<div class="mt-4 border-t pt-3 text-xs text-muted-foreground">The immutable application score will be captured when this loan is submitted for approval.</div>@elseif($currentDiffers)<div class="mt-4 border-t pt-3 text-xs text-muted-foreground">The application score above remains unchanged for audit. The newer current score is shown separately and does not rewrite the review snapshot.</div>@endif
        </div>
    </div>
    @else
    <div class="p-4 text-sm text-muted-foreground">No credit score is available for this customer yet.</div>
    @endif
</div>
@endif

<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">Application details</h2><p class="mt-1 text-xs text-muted-foreground">Saved application and calculation snapshot.</p></div>
<div class="p-4 grid gap-4 md:grid-cols-2 text-sm">
<div><div class="text-xs text-muted-foreground">Customer</div><a class="font-medium text-primary hover:underline" href="{{ route('customers.show',$loan->customer) }}">{{ $loan->customer->full_name }}</a><div class="text-xs text-muted-foreground">{{ $loan->customer->customer_number }} · {{ $loan->customer->phone }}</div></div>
<div><div class="text-xs text-muted-foreground">Branch</div><div class="font-medium">{{ $loan->branch->name }}</div></div>
<div><div class="text-xs text-muted-foreground">Loan product</div><div class="font-medium">{{ $loan->product->name }}</div><div class="text-xs text-muted-foreground">{{ str($loan->product->interest_calculation_method)->replace('_',' ')->title() }} · {{ str($loan->product->repayment_frequency)->replace('_',' ')->title() }}</div></div>
<div><div class="text-xs text-muted-foreground">Schedule starts</div><div class="font-medium">{{ $loan->schedule_start_date->format('d M Y') }}</div></div>
<div class="md:col-span-2"><div class="text-xs text-muted-foreground">Purpose</div><div class="mt-1">{{ $loan->purpose }}</div></div>
</div></div>

<div class="mf-card">
<div class="border-b p-4"><h2 class="font-semibold">Financial summary</h2></div>
<div class="p-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3 text-sm">
@foreach(['Principal'=>$loan->principal,'Interest'=>$loan->interest,'Processing fee'=>$loan->processing_fee,'Insurance fee'=>$loan->insurance_fee,'Other charges'=>$loan->other_charges,'Total repayment'=>$loan->total_repayment] 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">Proposed repayment schedule</h2><p class="mt-1 text-xs text-muted-foreground">Persisted when the application was created or last corrected.</p></div>
<div class="mf-table-frame border-0"><table class="mf-table"><thead><tr><th>#</th><th>Due date</th><th>Principal</th><th>Interest</th><th>Fees</th><th>Amount due</th><th>Status</th></tr></thead><tbody>@foreach($loan->installments as $i)<tr><td>{{ $i->installment_number }}</td><td>{{ $i->due_date->format('d M Y') }}</td><td>{{ number_format((float)$i->principal,2) }}</td><td>{{ number_format((float)$i->interest,2) }}</td><td>{{ number_format((float)$i->fees,2) }}</td><td>{{ number_format((float)$i->amount_due,2) }}</td><td>{{ ucfirst($i->status) }}</td></tr>@endforeach</tbody></table></div>
</div>

<div class="mf-card">
<div class="border-b p-4"><h2 class="font-semibold">Collateral & guarantor</h2></div>
<div class="p-4 grid gap-5 md:grid-cols-2">
<div><div class="text-xs font-medium uppercase tracking-wide text-muted-foreground mb-2">Collateral</div>@forelse($loan->collaterals as $collateral)<a href="{{ route('collateral.show',$collateral) }}" class="block rounded-md border p-3 mb-2 hover:border-primary"><div class="font-medium text-sm">{{ $collateral->code }} · {{ $collateral->item }}</div><div class="text-xs text-muted-foreground">{{ $collateral->category->name }} · {{ str($collateral->status)->replace('_',' ')->title() }} · {{ number_format((float)($collateral->accepted_value ?? 0),2) }}</div></a>@empty<p class="text-sm text-muted-foreground">No collateral linked.</p>@endforelse</div>
<div><div class="text-xs font-medium uppercase tracking-wide text-muted-foreground mb-2">Guarantor</div>@if($loan->guarantor)<div class="rounded-md border p-3"><div class="font-medium text-sm">{{ $loan->guarantor->full_name }}</div><div class="text-xs text-muted-foreground">{{ $loan->guarantor->phone }} · NIN {{ $loan->guarantor->nin ?: '—' }}</div></div>@else<p class="text-sm text-muted-foreground">No guarantor linked.</p>@endif</div>
</div>
@if($loan->status==='additional_collateral_requested' && auth()->user()->can('loans.update'))
<div class="border-t p-4">
    <h3 class="text-sm font-semibold">Add requested collateral</h3>
    <p class="mt-1 text-xs text-muted-foreground">Link additional available collateral for this customer, then resubmit the application for review.</p>
    <form method="POST" action="{{ route('loans.additional-collateral',$loan) }}" class="mt-3">@csrf
        <div class="grid gap-2 md:grid-cols-2">@forelse($availableAdditionalCollateral as $item)<label class="mf-option"><input type="checkbox" name="collateral_ids[]" value="{{ $item->id }}"><span><strong>{{ $item->code }} · {{ $item->item }}</strong><small class="block text-muted-foreground">{{ $item->category->name }} · {{ number_format((float)($item->accepted_value ?? 0),2) }}</small></span></label>@empty<p class="text-sm text-muted-foreground">No additional available collateral is registered for this customer.</p>@endforelse</div>
        @if($availableAdditionalCollateral->isNotEmpty())<button class="mf-btn mt-3">Link selected collateral</button>@endif
    </form>
</div>
@endif
</div>

<div class="mf-card">
<div class="border-b p-4"><h2 class="font-semibold">Documents</h2><p class="mt-1 text-xs text-muted-foreground">Supporting application documents and signed contract copies are stored privately.</p></div>
<div class="p-4">
<div class="mf-table-frame"><table class="mf-table"><thead><tr><th>Type</th><th>File</th><th>Uploaded</th><th></th></tr></thead><tbody>@forelse($loan->documents as $document)<tr><td>{{ $document->kind==='signed_contract'?'Signed Contract':($document->document_type ?: 'Supporting') }}</td><td><a class="font-medium text-primary hover:underline" target="_blank" rel="noopener" href="{{ route('loans.documents.review',[$loan,$document]) }}">{{ $document->original_name }}</a></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('loans.documents.download',[$loan,$document]) }}">Download</a></td></tr>@empty<tr><td colspan="4" class="text-center text-muted-foreground">No documents uploaded.</td></tr>@endforelse</tbody></table></div>
@if($loan->canUploadSupportingDocument() && auth()->user()->can('loans.documents'))<form method="POST" enctype="multipart/form-data" action="{{ route('loans.documents.store',$loan) }}" class="mt-4 rounded-md border p-3">@csrf<div class="mf-form-grid"><div class="mf-col-3"><label class="mf-field-label">Document type</label><input class="mf-input" name="document_type" required></div><div class="mf-col-5"><label class="mf-field-label">File</label><input type="file" class="mf-input" name="attachment" required></div><div class="mf-col-4"><label class="mf-field-label">Notes</label><input class="mf-input" name="notes"></div><div class="mf-col-12"><button class="mf-btn">Upload supporting document</button></div></div></form>
@elseif($loan->status==='under_review')<div class="mt-4 rounded-md border p-3 text-xs text-muted-foreground">Application documents are locked while the application is under review. New files can be added only if the reviewer requests correction, documents, or additional collateral.</div>
@elseif($loan->isApplicationApprovalLocked())<div class="mt-4 rounded-md border p-3 text-xs text-muted-foreground">This application has a final approval/rejection decision. Application documents are now read-only.</div>
@endif
</div></div>

<div class="mf-card">
<div class="border-b p-4"><h2 class="font-semibold">Approval decision history</h2><p class="mt-1 text-xs text-muted-foreground">Permanent reviewer decisions are stored separately from the general status timeline.</p></div>
<div class="p-4 space-y-3">@forelse($loan->approvalDecisions as $decision)<div class="rounded-md border p-3"><div class="flex flex-wrap items-center justify-between gap-2"><div class="text-sm font-medium">{{ str($decision->decision)->replace('_',' ')->title() }}{{ $decision->is_auto?' · Automatic':'' }}</div><span class="mf-badge {{ $decision->new_status==='ready_for_disbursement'?'mf-badge-success':'mf-badge-muted' }}">{{ str($decision->new_status)->replace('_',' ')->title() }}</span></div><div class="mt-1 text-xs text-muted-foreground">{{ str($decision->previous_status)->replace('_',' ')->title() }} → {{ str($decision->new_status)->replace('_',' ')->title() }} · {{ $decision->decided_at->format('d M Y H:i') }} · {{ $decision->user?->name ?? 'System' }}</div>@if($decision->comments)<p class="mt-2 text-sm">{{ $decision->comments }}</p>@endif</div>@empty<p class="text-sm text-muted-foreground">No approval decision has been recorded yet.</p>@endforelse</div>
</div>
</div>

<div class="space-y-4">
@if($loan->status==='under_review' && auth()->user()->can('loans.approve'))
<div class="mf-card">
<div class="border-b p-4"><h2 class="font-semibold">Review & decision</h2><p class="mt-1 text-xs text-muted-foreground">Record an approval decision. Approval and disbursement remain separate events.</p></div>
<div class="p-4 space-y-3">
    @if($requiresManagerApproval)<div class="rounded-md border p-3 text-xs"><strong>Manager approval required.</strong><div class="mt-1 text-muted-foreground">Principal exceeds {{ number_format((float)$loan->branch->business->manager_approval_threshold,2) }}.</div></div>@endif
    @if($makerCheckerBlocked)<div class="rounded-md border p-3 text-xs"><strong>Maker-checker restriction.</strong><div class="mt-1 text-muted-foreground">You created this application and cannot approve it while maker-checker is enabled.</div></div>@endif
    <form method="POST" action="{{ route('loans.approvals.decide',$loan) }}" class="space-y-3">@csrf
        <div><label class="mf-field-label">Decision</label><select class="mf-input" name="decision" required><option value="approve">Approve</option><option value="reject">Reject</option><option value="request_correction">Request correction</option><option value="request_documents">Request documents</option><option value="request_additional_collateral">Request additional collateral</option></select></div>
        <div><label class="mf-field-label">Comments</label><textarea class="mf-input" name="comments" rows="3" placeholder="Required for rejection or requests"></textarea></div>
        <button class="mf-btn mf-btn-primary w-full">Record decision</button>
    </form>
</div></div>
@endif

<div class="mf-card">
<div class="border-b p-4"><h2 class="font-semibold">Application workflow</h2></div>
<div class="p-4">
@if(count($transitions) && auth()->user()->can('loans.update'))
<form method="POST" action="{{ route('loans.transition',$loan) }}" class="space-y-3">@csrf
<div><label class="mf-field-label">Move to</label><select class="mf-input" name="status" required>@foreach($transitions as $status)<option value="{{ $status }}">{{ $status==='under_review'?'Submit for Approval':str($status)->replace('_',' ')->title() }}</option>@endforeach</select></div>
<div><label class="mf-field-label">Notes</label><textarea class="mf-input" name="notes" rows="2"></textarea></div><button class="mf-btn mf-btn-primary w-full">Update status</button></form>
@else<p class="text-sm text-muted-foreground">No manual transition is available from this status.</p>@endif
</div></div>

<div class="mf-card">
<div class="border-b p-4"><h2 class="font-semibold">Approval controls</h2></div>
<div class="p-4 space-y-3 text-sm">
<div class="flex justify-between gap-3"><span class="text-muted-foreground">Mode</span><span>{{ $loan->branch->business->loan_approval_mode==='auto_authorized'?'Authorized auto approval':'Approval required' }}</span></div>
<div class="flex justify-between gap-3"><span class="text-muted-foreground">Maker-checker</span><span>{{ $loan->branch->business->maker_checker_enabled?'Enabled':'Disabled' }}</span></div>
<div class="flex justify-between gap-3"><span class="text-muted-foreground">Manager threshold</span><span>{{ $loan->branch->business->manager_approval_threshold!==null?number_format((float)$loan->branch->business->manager_approval_threshold,2):'Not configured' }}</span></div>
<div class="flex justify-between gap-3"><span class="text-muted-foreground">Approved by</span><span>{{ $loan->approver?->name ?? '—' }}</span></div>
<div class="flex justify-between gap-3"><span class="text-muted-foreground">Approved at</span><span>{{ $loan->approved_at?->format('d M Y H:i') ?? '—' }}</span></div>
</div></div>

<div class="mf-card">
<div class="border-b p-4"><h2 class="font-semibold">Contract</h2></div>
<div class="p-4 space-y-3 text-sm">
<div class="flex justify-between gap-3"><span class="text-muted-foreground">Generated</span><span>{{ $loan->contract_generated_at?->format('d M Y H:i') ?? 'Not yet' }}</span></div>
<div class="flex justify-between gap-3"><span class="text-muted-foreground">Signed copy</span><span>{{ $loan->hasSignedContract()?'Uploaded':'Not uploaded' }}</span></div>
<div class="rounded-md border p-3 text-xs {{ $requireSignedContract?'bg-muted/30':'' }}"><strong>{{ $requireSignedContract?'Signed contract required before disbursement':'Signed contract not mandatory by current business setting' }}</strong></div>
<div class="rounded-md border p-3 text-xs text-muted-foreground">Contract layout, field mapping and spacing are finalized under Administration → Contract Templates. Loan generation automatically fills the saved template with this loan's system data.</div>
@if($loan->status==='under_review')<div class="rounded-md border p-3 text-xs"><strong>Contract locked during review.</strong><div class="mt-1 text-muted-foreground">A new contract or signed replacement can be added only after the reviewer requests correction, documents, or additional collateral.</div></div>
@elseif($loan->isApplicationApprovalLocked())<div class="rounded-md border p-3 text-xs"><strong>Application locked.</strong><div class="mt-1 text-muted-foreground">This loan has already been approved or rejected. Contract and application editing are read-only.</div></div>
@elseif($loan->isReviewChangeRequested())<div class="rounded-md border p-3 text-xs"><strong>Reviewer changes requested.</strong><div class="mt-1 text-muted-foreground">Contract/document changes are temporarily reopened. Resubmit the application when the requested correction is complete.</div></div>
@endif
@if($loan->canGenerateContract() && auth()->user()->can('loans.contract'))<form method="POST" action="{{ route('loans.contract',$loan) }}">@csrf<button class="mf-btn w-full">Generate completed contract</button></form>@endif
@if($loan->canUploadSignedContract() && auth()->user()->can('loans.documents'))<form method="POST" enctype="multipart/form-data" action="{{ route('loans.signed-contract',$loan) }}" class="space-y-2">@csrf<label class="mf-field-label">Upload signed contract</label><input type="file" class="mf-input" name="signed_contract" accept=".pdf,.jpg,.jpeg,.png,.doc,.docx" required><input class="mf-input" name="notes" placeholder="Optional notes"><button class="mf-btn w-full">Upload signed copy</button></form>@endif
</div></div>

<div class="mf-card">
<div class="border-b p-4"><h2 class="font-semibold">Status history</h2></div>
<div class="p-4 space-y-3">@foreach($loan->statusHistory as $history)<div class="border-l-2 pl-3"><div class="text-sm font-medium">{{ $history->from_status?str($history->from_status)->replace('_',' ')->title().' → ':'' }}{{ str($history->to_status)->replace('_',' ')->title() }}</div><div class="text-xs text-muted-foreground">{{ $history->changed_at->format('d M Y H:i') }} · {{ $history->changer?->name ?? 'System' }}</div>@if($history->notes)<p class="mt-1 text-xs">{{ $history->notes }}</p>@endif</div>@endforeach</div>
</div>
</div>
</div>
@endsection