@extends('layouts.app')
@section('title','Create Loan Top-Up')
@section('content')
<x-ui.form-shell
    title="Create Loan Top-Up"
    description="Create a replacement loan linked to the active loan. It will still pass through the normal contract and approval workflow before top-up execution."
    :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Loan Top-Ups','url'=>route('loan-top-ups.index')],['label'=>$loan->loan_number]]"
>
<form method="POST" action="{{ route('loan-top-ups.store',$loan) }}" class="mf-form" id="top-up-form">
@csrf
<x-ui.form-section title="Previous loan" description="Current loan and eligibility snapshot used for this top-up request.">
    <x-ui.form-grid>
        <div class="mf-col-3"><label class="mf-field-label">Loan</label><div class="mf-input bg-muted/30">{{ $loan->loan_number }}</div></div>
        <div class="mf-col-3"><label class="mf-field-label">Customer</label><div class="mf-input bg-muted/30">{{ $loan->customer->full_name }}</div></div>
        <div class="mf-col-2"><label class="mf-field-label">Current outstanding</label><div class="mf-input bg-muted/30">{{ number_format((float)$loan->total_outstanding,2) }}</div></div>
        <div class="mf-col-2"><label class="mf-field-label">Repaid</label><div class="mf-input bg-muted/30">{{ $eligibility['paid_percentage'] }}%</div></div>
        <div class="mf-col-2"><label class="mf-field-label">Required</label><div class="mf-input bg-muted/30">{{ $eligibility['threshold'] }}%</div></div>
        <div class="mf-col-12">@if($eligibility['eligible'])<span class="mf-badge mf-badge-success">Eligible for top-up</span>@else<span class="mf-badge mf-badge-warning">Below configured eligibility threshold</span>@endif</div>
    </x-ui.form-grid>
</x-ui.form-section>

<x-ui.form-section title="Replacement loan terms" description="The new principal must exceed the old loan's current outstanding. The old balance will be settled internally only when this replacement loan is approved and executed.">
    <x-ui.form-grid>
        <div class="mf-col-4"><label class="mf-field-label">Loan product</label><select class="mf-input" name="loan_product_id" id="loan_product_id" required><option value="">Select product</option>@foreach($products as $product)<option value="{{ $product->id }}" @selected((string)old('loan_product_id')===(string)$product->id)>{{ $product->name }} · {{ number_format((float)$product->minimum_amount,2) }}–{{ number_format((float)$product->maximum_amount,2) }}</option>@endforeach</select>@error('loan_product_id')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
        <div class="mf-col-3"><label class="mf-field-label">New principal</label><input type="number" step="0.01" min="0.01" class="mf-input" name="principal" id="principal" value="{{ old('principal') }}" required>@error('principal')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
        <div class="mf-col-3"><label class="mf-field-label">Schedule start date</label><input type="date" class="mf-input" name="schedule_start_date" id="schedule_start_date" value="{{ old('schedule_start_date',now()->format('Y-m-d')) }}" required></div>
        <div class="mf-col-12"><label class="mf-field-label">Purpose</label><textarea class="mf-input" name="purpose" rows="3" required>{{ old('purpose','Top-up of '.$loan->loan_number) }}</textarea>@error('purpose')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
        <div class="mf-col-12"><label class="mf-field-label">Custom repayment dates <span class="text-muted-foreground">(optional; one date per line)</span></label><textarea class="mf-input" name="custom_dates_text" id="custom_dates_text" rows="3">{{ old('custom_dates_text') }}</textarea></div>
    </x-ui.form-grid>
</x-ui.form-section>

<x-ui.form-section title="Collateral & guarantor" description="Normal loan-product security requirements still apply to the replacement loan.">
    <x-ui.form-grid>
        <div class="mf-col-8">
            <label class="mf-field-label">Collateral</label>
            <div class="grid gap-2 md:grid-cols-2">@forelse($collaterals as $item)<label class="mf-option"><input type="checkbox" name="collateral_ids[]" value="{{ $item->id }}" @checked(in_array($item->id,old('collateral_ids',[])))><span><strong>{{ $item->code }}</strong><small class="block text-muted-foreground">{{ $item->item }} · {{ $item->category?->name }}</small></span></label>@empty<p class="text-sm text-muted-foreground">No available collateral for this customer.</p>@endforelse</div>
            @error('collateral_ids')<p class="mf-field-error">{{ $message }}</p>@enderror
        </div>
        <div class="mf-col-4"><label class="mf-field-label">Guarantor</label><select class="mf-input" name="guarantor_id"><option value="">No guarantor selected</option>@foreach($guarantors as $guarantor)<option value="{{ $guarantor->id }}" @selected((string)old('guarantor_id')===(string)$guarantor->id)>{{ $guarantor->full_name }} · {{ $guarantor->phone }}</option>@endforeach</select>@error('guarantor_id')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
    </x-ui.form-grid>
</x-ui.form-section>

@if(!$eligibility['eligible'] && auth()->user()->can('loans.top-up.override'))
<x-ui.form-section title="Eligibility override" description="Authorized override is exceptional and permanently audited.">
    <x-ui.form-grid>
        <div class="mf-col-4 flex items-end"><label class="mf-option w-full"><input type="checkbox" name="override_eligibility" value="1" @checked(old('override_eligibility'))><span><strong>Override eligibility threshold</strong><small class="block text-muted-foreground">Use only with a justified management decision.</small></span></label></div>
        <div class="mf-col-8"><label class="mf-field-label">Override reason</label><textarea class="mf-input" name="override_reason" rows="2">{{ old('override_reason') }}</textarea>@error('override_reason')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
    </x-ui.form-grid>
</x-ui.form-section>
@endif
@error('eligibility')<p class="mf-field-error">{{ $message }}</p>@enderror
@error('override_eligibility')<p class="mf-field-error">{{ $message }}</p>@enderror

<x-ui.form-section title="Backend top-up preview" description="Preview uses the central repayment engine and current old-loan outstanding. Final net cash is recalculated again at execution.">
    <button type="button" class="mf-btn" id="top-up-preview">Calculate preview</button>
    <p id="top-up-preview-error" class="mt-2 text-sm text-destructive hidden"></p>
    <div id="top-up-preview-result" class="mt-3 hidden">
        <div class="grid gap-2 sm:grid-cols-2 lg:grid-cols-6">
            <div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Principal</div><div class="font-semibold" data-preview="principal"></div></div>
            <div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Interest</div><div class="font-semibold" data-preview="interest"></div></div>
            <div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Fees</div><div class="font-semibold" data-preview="fees"></div></div>
            <div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">New total</div><div class="font-semibold" data-preview="total"></div></div>
            <div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Internal settlement</div><div class="font-semibold" data-preview="settlement"></div></div>
            <div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Estimated net cash</div><div class="font-semibold" data-preview="cash"></div></div>
        </div>
        <div class="mf-table-frame mt-3"><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></tr></thead><tbody id="top-up-preview-schedule"></tbody></table></div>
    </div>
</x-ui.form-section>

<x-ui.form-actions><a class="mf-btn" href="{{ route('loan-top-ups.index') }}">Cancel</a><button class="mf-btn mf-btn-primary" type="submit">Create top-up application</button></x-ui.form-actions>
</form>
</x-ui.form-shell>

<script>
(() => {
    const button=document.getElementById('top-up-preview');
    if(!button) return;
    button.addEventListener('click', async () => {
        const error=document.getElementById('top-up-preview-error');
        const result=document.getElementById('top-up-preview-result');
        error.classList.add('hidden'); result.classList.add('hidden');
        try {
            const response=await fetch(@json(route('loan-top-ups.preview',$loan)),{
                method:'POST',headers:{'Content-Type':'application/json','Accept':'application/json','X-CSRF-TOKEN':@json(csrf_token())},
                body:JSON.stringify({loan_product_id:document.getElementById('loan_product_id').value,principal:document.getElementById('principal').value,schedule_start_date:document.getElementById('schedule_start_date').value,custom_dates_text:document.getElementById('custom_dates_text').value})
            });
            const data=await response.json();
            if(!response.ok) throw new Error(data.message || Object.values(data.errors || {})?.[0]?.[0] || 'Unable to calculate preview.');
            const summary=data.summary;
            document.querySelector('[data-preview="principal"]').textContent=summary.principal;
            document.querySelector('[data-preview="interest"]').textContent=summary.interest;
            document.querySelector('[data-preview="fees"]').textContent=summary.fees;
            document.querySelector('[data-preview="total"]').textContent=summary.total_repayment;
            document.querySelector('[data-preview="settlement"]').textContent=data.top_up.previous_outstanding;
            document.querySelector('[data-preview="cash"]').textContent=data.top_up.cash_given_to_customer;
            document.getElementById('top-up-preview-schedule').innerHTML=(data.installments || []).map(row=>`<tr><td>${row.number}</td><td>${row.due_date}</td><td>${row.principal}</td><td>${row.interest}</td><td>${row.fees}</td><td>${row.amount_due}</td></tr>`).join('');
            if(!data.top_up.principal_exceeds_outstanding) throw new Error('New principal must exceed the current old-loan outstanding.');
            result.classList.remove('hidden');
        } catch(e) { error.textContent=e.message; error.classList.remove('hidden'); }
    });
})();
</script>
@endsection