@extends('layouts.app')
@section('title','Early Settlement')
@section('content')
<x-ui.form-shell title="Early Settlement" description="Collect the complete settlement amount, close the loan and mark linked collateral ready for release." :breadcrumbs="[['label'=>'Loan Adjustments','url'=>route('loan-adjustments.index')],['label'=>$loan->loan_number]]">
<form method="POST" action="{{ route('loan-early-settlements.store',$loan) }}" class="space-y-4" id="settlement-form">
    @csrf
    <x-ui.form-section title="Loan and settlement quote" description="Penalties are assessed through the selected settlement date. Final figures are recalculated under database locks before posting.">
        <div class="grid gap-3 md:grid-cols-3">
            <div><div class="text-xs text-muted-foreground">Loan</div><div class="font-medium">{{ $loan->loan_number }}</div></div>
            <div><div class="text-xs text-muted-foreground">Customer</div><div class="font-medium">{{ $loan->customer->full_name }}</div></div>
            <div><div class="text-xs text-muted-foreground">Branch</div><div class="font-medium">{{ $loan->branch->name }}</div></div>
        </div>
        <div class="mt-4 grid gap-2 sm:grid-cols-3 lg:grid-cols-6" id="settlement-quote">
            @foreach(['principal'=>'Principal','interest'=>'Interest','fees'=>'Fees','penalties'=>'Penalties','settlement_adjustment'=>'Adjustment','final_amount'=>'Final amount'] as $key=>$label)
                <div class="rounded-md border p-3"><div class="text-[11px] text-muted-foreground">{{ $label }}</div><div class="mt-1 font-semibold" data-quote="{{ $key }}">{{ $quote[$key] }}</div></div>
            @endforeach
        </div>
    </x-ui.form-section>

    <x-ui.form-section title="Settlement posting">
        <x-ui.form-grid>
            <div><label class="mf-label">Receiving account</label><select class="mf-select" name="financial_account_id" required><option value="">Select account</option>@foreach($accounts as $account)<option value="{{ $account->id }}" @selected(old('financial_account_id')==$account->id)>{{ $account->name }} — {{ number_format((float)$account->current_balance,2) }}</option>@endforeach</select>@error('financial_account_id')<p class="mf-error">{{ $message }}</p>@enderror</div>
            <div><label class="mf-label">Settlement date</label><input class="mf-input" type="date" name="date" value="{{ old('date',now()->toDateString()) }}" required>@error('date')<p class="mf-error">{{ $message }}</p>@enderror</div>
            <div><label class="mf-label">Settlement adjustment</label><input class="mf-input" name="settlement_adjustment" value="{{ old('settlement_adjustment','0.00') }}" inputmode="decimal" placeholder="0.00"><p class="mt-1 text-xs text-muted-foreground">Use a negative value for an authorized reduction or positive value for an addition. A reduction can never waive principal.</p>@error('settlement_adjustment')<p class="mf-error">{{ $message }}</p>@enderror</div>
            <div><label class="mf-label">Adjustment reason</label><input class="mf-input" name="adjustment_reason" value="{{ old('adjustment_reason') }}" maxlength="2000" placeholder="Required when adjustment is not zero">@error('adjustment_reason')<p class="mf-error">{{ $message }}</p>@enderror</div>
            <div><label class="mf-label">Reference</label><input class="mf-input" name="reference" value="{{ old('reference') }}" maxlength="150" placeholder="Optional external reference"></div>
            <div><label class="mf-label">Notes</label><input class="mf-input" name="notes" value="{{ old('notes') }}" maxlength="2000"></div>
        </x-ui.form-grid>
        <div class="mt-3"><button class="mf-btn" type="button" id="preview-settlement">Refresh quote</button><span class="ml-2 text-xs text-muted-foreground" id="quote-message"></span></div>
    </x-ui.form-section>

    <x-ui.form-actions><a class="mf-btn" href="{{ route('loan-adjustments.index') }}">Cancel</a><button class="mf-btn mf-btn-primary" type="submit">Post full settlement</button></x-ui.form-actions>
</form>
</x-ui.form-shell>
<script>
(() => {
    const button=document.getElementById('preview-settlement');
    const form=document.getElementById('settlement-form');
    const message=document.getElementById('quote-message');
    button?.addEventListener('click', async () => {
        message.textContent='Calculating…';
        const body=new FormData(); body.append('_token',form.querySelector('[name="_token"]').value); body.append('date',form.date.value); body.append('settlement_adjustment',form.settlement_adjustment.value || '0.00');
        const response=await fetch(@json(route('loan-early-settlements.preview',$loan)),{method:'POST',body,headers:{'Accept':'application/json'}});
        const data=await response.json();
        if(!response.ok){ message.textContent=data.message || Object.values(data.errors || {}).flat()[0] || 'Unable to calculate quote.'; return; }
        Object.entries(data).forEach(([key,value])=>{ const target=document.querySelector(`[data-quote="${key}"]`); if(target) target.textContent=value; });
        message.textContent='Quote refreshed. Final posting will recalculate these values again.';
    });
})();
</script>
@endsection
