@extends('layouts.app')
@section('title',$customer->full_name)
@section('content')
@php $tab=request('tab','overview'); $tabs=['overview'=>'Overview','personal'=>'Personal details','kyc'=>'KYC','documents'=>'Documents','guarantors'=>'Guarantors','blacklist'=>'Blacklist / Watchlist','activity'=>'Activity']; @endphp
<div class="mb-5 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between"><div><div class="flex flex-wrap items-center gap-2"><h1 class="text-2xl font-semibold">{{ $customer->full_name }}</h1>@if($customer->hasActiveBlacklist())<span class="mf-badge bg-destructive/10 text-destructive">BLACKLISTED</span>@endif</div><p class="mt-1 text-sm text-muted-foreground">{{ $customer->customer_number }} · {{ $customer->branch->name }}</p></div>@if(auth()->user()->can('customers.update'))<a class="mf-btn" href="{{ route('customers.edit',$customer) }}">Edit customer</a>@endif</div>
<div class="mb-5 flex gap-1 overflow-x-auto border-b" style="margin-bottom: 10px">@foreach($tabs as $key=>$label)<a href="{{ route('customers.show',[$customer,'tab'=>$key]) }}" class="whitespace-nowrap border-b-2 px-3 py-2 text-sm {{ $tab===$key?'border-primary font-medium text-primary':'border-transparent text-muted-foreground' }}">{{ $label }}</a>@endforeach</div>
@if($tab==='overview')
<div class="grid gap-3 md:grid-cols-3"><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Phone</div><div class="mt-1 font-medium">{{ $customer->phone }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Customer status</div><div class="mt-1 font-medium">{{ ucfirst($customer->status) }}</div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Branch</div><div class="mt-1 font-medium">{{ $customer->branch->name }}</div></div></div>

@if(auth()->user()->can('credit-score.view'))
@php
    $risk = $customer->riskProfile;
    $scoreComponents = collect(data_get($risk?->factors, 'components', []));
    $positiveFactors = $scoreComponents->flatMap(fn($component) => $component['positive_factors'] ?? [])->filter()->take(3);
    $negativeFactors = $scoreComponents->flatMap(fn($component) => $component['negative_factors'] ?? [])->filter()->take(3);
    $bandLabel = data_get($risk?->factors, 'band_label') ?: str($risk?->score_band ?? 'unrated')->replace('_',' ')->title();
@endphp
<div class="mt-4 mf-card">
    <div class="flex flex-col gap-3 border-b p-4 sm:flex-row sm:items-center sm:justify-between">
        <div><h2 class="font-semibold">Credit score</h2><p class="mt-1 text-xs text-muted-foreground">Decision support from financial, repayment and credit-control data.</p></div>
        <div class="flex flex-wrap gap-2">
            @if(auth()->user()->can('credit-score.history'))<a class="mf-btn" href="{{ route('customers.credit-score.history',$customer) }}">View history</a>@endif
            @if(auth()->user()->can('credit-score.recalculate'))<form method="POST" action="{{ route('customers.credit-score.recalculate',$customer) }}">@csrf<button class="mf-btn mf-btn-primary">Recalculate</button></form>@endif
        </div>
    </div>
    @if($risk && $risk->score !== null)
    <div class="grid gap-0 lg:grid-cols-[220px_1fr]">
        <div class="border-b p-4 lg:border-b-0 lg:border-r">
            <div class="text-4xl font-semibold leading-none">{{ (int) round((float)$risk->score) }}</div>
            <div class="mt-2 text-sm font-medium">{{ $bandLabel }}</div>
            <div class="mt-2 flex flex-wrap gap-1">
                <span class="mf-badge mf-badge-muted">{{ str($risk->risk_level)->replace('_',' ')->title() }} risk</span>
                @if($risk->thin_file)<span class="mf-badge mf-badge-muted">Thin file</span>@endif
                @if($risk->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)$risk->confidence,0) }}%</div></div>
                <div><div class="text-xs text-muted-foreground">Version</div><div class="font-medium">{{ strtoupper($risk->score_version ?? '—') }}</div></div>
            </div>
            <div class="mt-3 text-xs text-muted-foreground">Calculated {{ $risk->calculated_at?->format('d M Y H:i') ?? '—' }}</div>
        </div>
        <div class="p-4">
            @if($risk->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">Review the factors below before making a lending decision.</span></div>@endif
            <p class="text-sm">{{ $risk->explanation ?: 'No explanation is available for this score.' }}</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(auth()->user()->can('credit-score.history') && $creditScoreHistory->isNotEmpty())
            <div class="mt-4 border-t pt-3"><div class="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">Recent score trend</div><div class="flex gap-2 overflow-x-auto">@foreach($creditScoreHistory->take(6) as $score)<div class="min-w-[84px] border-l pl-2"><div class="font-semibold">{{ (int) round((float)$score->score) }}</div><div class="text-[11px] text-muted-foreground">{{ $score->calculated_at?->format('d M') }}</div></div>@endforeach</div></div>
            @endif
        </div>
    </div>
    @else
    <div class="p-4 text-sm text-muted-foreground">No calculated credit score is available yet.@if(auth()->user()->can('credit-score.recalculate')) Use Recalculate to create the first scored snapshot.@endif</div>
    @endif
</div>
@endif

@if(auth()->user()->can('loans.view'))
<div class="mt-4 mf-card">
    <div class="border-b p-4"><h2 class="font-semibold">Recent loans</h2><p class="mt-1 text-xs text-muted-foreground">Latest applications and repayment relationships for this customer.</p></div>
    <div class="mf-table-frame border-0"><table class="mf-table"><thead><tr><th>Loan</th><th>Product</th><th>Principal</th><th>Status</th><th></th></tr></thead><tbody>@forelse($recentLoans as $loan)<tr><td class="font-medium">{{ $loan->loan_number }}</td><td>{{ $loan->product?->name ?? '—' }}</td><td>{{ number_format((float)$loan->principal,2) }}</td><td><span class="mf-badge mf-badge-muted">{{ str($loan->status)->replace('_',' ')->title() }}</span></td><td class="text-right"><a class="text-primary hover:underline" href="{{ route('loans.show',$loan) }}">Open</a></td></tr>@empty<tr><td colspan="5" class="text-center text-muted-foreground">No loan applications recorded for this customer.</td></tr>@endforelse</tbody></table></div>
</div>
@endif
@elseif($tab==='personal')
<div class="grid gap-4 md:grid-cols-2"><div class="mf-card mf-card-body space-y-2"><h2 class="font-semibold">Personal</h2>@foreach(['NIN'=>$customer->nin,'Gender'=>$customer->gender,'Date of birth'=>optional($customer->date_of_birth)->format('d M Y'),'Email'=>$customer->email,'Alternative phone'=>$customer->alternative_phone,'Marital status'=>$customer->marital_status] as $k=>$v)<div class="flex justify-between gap-4 text-sm"><span class="text-muted-foreground">{{ $k }}</span><span>{{ $v ?: '—' }}</span></div>@endforeach</div><div class="mf-card mf-card-body space-y-2"><h2 class="font-semibold">Address & work</h2>@foreach(['Occupation'=>$customer->occupation,'Employer / business'=>$customer->employer_business,'Monthly income'=>$customer->monthly_income,'Region'=>$customer->address?->region,'District'=>$customer->address?->district,'Ward'=>$customer->address?->ward,'Street / village'=>$customer->address?->street_village,'House'=>$customer->address?->house_number,'GPS'=>$customer->address?->latitude&&$customer->address?->longitude?$customer->address->latitude.', '.$customer->address->longitude:null] as $k=>$v)<div class="flex justify-between gap-4 text-sm"><span class="text-muted-foreground">{{ $k }}</span><span>{{ $v ?: '—' }}</span></div>@endforeach</div></div>
<div class="mt-4 mf-card mf-card-body"><h2 class="font-semibold">Next of Kin</h2>@forelse($customer->nextOfKin as $kin)<div class="mt-2 text-sm">{{ $kin->full_name }} · {{ $kin->relationship ?: 'Relationship not specified' }} · {{ $kin->phone ?: 'No phone' }}</div>@empty<p class="mt-2 text-sm text-muted-foreground">No next of kin recorded.</p>@endforelse</div>
@elseif($tab==='kyc')
<div class="mf-card mf-card-body"><h2 class="font-semibold">KYC status</h2><div class="mt-3 grid gap-3 md:grid-cols-2"><div><div class="text-xs text-muted-foreground">Registration mode</div><div class="font-medium">{{ $customer->identity_mode==='with_nin'?'With NIN':'Without NIN' }}</div></div><div><div class="text-xs text-muted-foreground">NIN</div><div class="font-medium">{{ $customer->nin ?: 'Not provided' }}</div></div><div><div class="text-xs text-muted-foreground">Documents on file</div><div class="font-medium">{{ $customer->documents->count() }}</div></div><div><div class="text-xs text-muted-foreground">Photo</div><div class="font-medium">{{ $customer->photo_path?'Stored securely':'Not uploaded' }}</div></div></div></div>
@elseif($tab==='documents')
@if(auth()->user()->can('customers.documents'))
<form method="POST" enctype="multipart/form-data" action="{{ route('customers.documents.store',$customer) }}" class="mb-5 rounded-md border border-border p-4">@csrf
<div class="mb-3"><h2 class="text-sm font-semibold">Upload customer document</h2><p class="mt-1 text-xs text-muted-foreground">Files are stored privately and linked to this customer’s KYC record.</p></div>
<div class="mf-form-grid">
<div class="mf-col-3"><label class="mf-field-label">Document type</label><select class="mf-input" name="document_type">@foreach(['National ID','Voter ID','Passport','Driving licence','Introduction letter','Employer letter','Business licence','Salary slip','Bank statement','Proof of residence','Customer photograph','Guarantor documents','Other'] as $type)<option>{{ $type }}</option>@endforeach</select></div>
<div class="mf-col-4"><label class="mf-field-label">File</label><input required type="file" class="mf-input" name="document"></div>
<div class="mf-col-2"><label class="mf-field-label">Expiry date</label><input type="date" class="mf-input" name="expiry_date"></div>
<div class="mf-col-3"><label class="mf-field-label">Notes</label><input class="mf-input" name="notes"></div>
<div class="mf-col-12 mf-form-actions"><button class="mf-btn mf-btn-primary">Upload document</button></div>
</div></form>
@endif
<div class="overflow-x-auto rounded-lg border"><table class="w-full text-sm"><thead><tr class="border-b text-left"><th class="p-3">Type</th><th class="p-3">File</th><th class="p-3">Uploaded</th><th class="p-3">Expiry</th><th></th></tr></thead><tbody>@forelse($customer->documents as $doc)<tr class="border-b"><td class="p-3">{{ $doc->document_type }}</td><td class="p-3">{{ $doc->original_name }}</td><td class="p-3">{{ $doc->created_at->format('d M Y') }} by {{ $doc->uploader?->name ?? 'System' }}</td><td class="p-3">{{ $doc->expiry_date?->format('d M Y') ?? '—' }}</td><td class="p-3 text-right">@if(auth()->user()->can('customers.documents'))<a class="text-primary hover:underline" href="{{ route('customers.documents.download',[$customer,$doc]) }}">Download</a>@endif</td></tr>@empty<tr><td colspan="5" class="p-6 text-center text-muted-foreground">No documents uploaded.</td></tr>@endforelse</tbody></table></div>
@elseif($tab==='guarantors')
@if(auth()->user()->can('customers.guarantors'))
<form method="POST" enctype="multipart/form-data" action="{{ route('customers.guarantors.store',$customer) }}" class="mb-5 rounded-md border border-border p-4">@csrf
<div class="mb-3"><h2 class="text-sm font-semibold">Add guarantor</h2><p class="mt-1 text-xs text-muted-foreground">Record the guarantor’s identity, contact details and signed undertaking.</p></div>
<div class="mf-form-grid">
<div class="mf-col-4"><label class="mf-field-label">Full name</label><input class="mf-input" name="full_name" required></div>
<div class="mf-col-2"><label class="mf-field-label">NIN</label><input class="mf-input" name="nin"></div>
<div class="mf-col-2"><label class="mf-field-label">Phone</label><input class="mf-input" name="phone" required></div>
<div class="mf-col-2"><label class="mf-field-label">Relationship</label><input class="mf-input" name="relationship"></div>
<div class="mf-col-2"><label class="mf-field-label">Occupation</label><input class="mf-input" name="occupation"></div>
<div class="mf-col-6"><label class="mf-field-label">Address</label><input class="mf-input" name="address"></div>
<div class="mf-col-6"><label class="mf-field-label">Signed guarantee document</label><input type="file" class="mf-input" name="signed_guarantee"></div>
<div class="mf-col-12 mf-form-actions"><button class="mf-btn mf-btn-primary">Add guarantor</button></div>
</div></form>
@endif
<div class="grid gap-3 md:grid-cols-2">@forelse($customer->guarantors as $g)<div class="mf-card mf-card-body"><div class="font-medium">{{ $g->full_name }}</div><div class="mt-1 text-sm text-muted-foreground">{{ $g->phone }} · {{ $g->relationship ?: 'Relationship not specified' }}</div><div class="mt-2 text-xs">NIN: {{ $g->nin ?: '—' }} · {{ $g->signed_guarantee_path?'Signed document stored':'No signed document' }}</div></div>@empty<p class="text-sm text-muted-foreground">No guarantors recorded.</p>@endforelse</div>
@elseif($tab==='blacklist')
@if(auth()->user()->can('customers.watchlist'))
<form method="POST" enctype="multipart/form-data" action="{{ route('customers.watchlist.store',$customer) }}" class="mb-5 rounded-md border border-border p-4">@csrf
<div class="mb-3"><h2 class="text-sm font-semibold">Add watchlist / blacklist record</h2><p class="mt-1 text-xs text-muted-foreground">Record the reason clearly; the entry becomes part of the customer’s auditable risk history.</p></div>
<div class="mf-form-grid">
<div class="mf-col-2"><label class="mf-field-label">Record type</label><select class="mf-input" name="type"><option value="watchlist">Watchlist</option><option value="blacklist">Blacklist</option></select></div>
<div class="mf-col-4"><label class="mf-field-label">Reason</label><input required class="mf-input" name="reason"></div>
<div class="mf-col-6"><label class="mf-field-label">Supporting document</label><input type="file" class="mf-input" name="supporting_document"></div>
<div class="mf-col-12"><label class="mf-field-label">Notes</label><textarea class="mf-input" name="notes"></textarea></div>
<div class="mf-col-12 mf-form-actions"><button class="mf-btn mf-btn-primary">Add record</button></div>
</div></form>
@endif
<div class="space-y-3">@forelse($customer->blacklistRecords->sortByDesc('created_at') as $record)<div class="rounded-lg border p-4"><div class="flex items-start justify-between"><div><div class="font-medium">{{ ucfirst($record->type) }} · {{ $record->reason }}</div><p class="mt-1 text-sm text-muted-foreground">{{ $record->notes }}</p><div class="mt-2 text-xs text-muted-foreground">Added {{ $record->created_at->format('d M Y') }} by {{ $record->author?->name ?? 'System' }}</div></div><span class="mf-badge">{{ ucfirst($record->status) }}</span></div>@if($record->status==='active'&&auth()->user()->can('customers.watchlist'))<form method="POST" action="{{ route('customers.watchlist.resolve',[$customer,$record]) }}" class="mt-3 flex gap-2">@csrf<input class="mf-input" name="resolution_notes" placeholder="Resolution note"><button class="mf-btn">Resolve</button></form>@endif</div>@empty<p class="text-sm text-muted-foreground">No blacklist or watchlist records.</p>@endforelse</div>
@elseif($tab==='activity')
<div class="space-y-2">@forelse($activity as $log)<div class="rounded-md border p-3"><div class="text-sm font-medium">{{ str_replace('.',' ',$log->action) }}</div><div class="mt-1 text-xs text-muted-foreground">{{ $log->created_at->format('d M Y H:i') }} · {{ $log->user?->name ?? 'System' }}</div></div>@empty<p class="text-sm text-muted-foreground">No customer activity recorded.</p>@endforelse</div>
@endif
@endsection
