@extends('layouts.app')
@section('title','Restructure '.$loan->loan_number)
@section('content')
<x-ui.form-shell title="Restructure Loan" description="Propose new installment amounts and repayment dates without deleting the current schedule." :breadcrumbs="[['label'=>'Loan Adjustments','url'=>route('loan-adjustments.index')],['label'=>$loan->loan_number]]">
<form method="POST" action="{{ route('loan-restructurings.store',$loan) }}" enctype="multipart/form-data" class="space-y-4" id="restructure-form">
    @csrf
    <x-ui.form-section title="Current loan position">
        <div class="grid gap-3 md:grid-cols-4">
            <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">Schedule version</div><div class="font-medium">v{{ $loan->current_schedule_version }}</div></div>
            <div><div class="text-xs text-muted-foreground">Total outstanding</div><div class="font-semibold">{{ number_format((float)$loan->total_outstanding,2) }}</div></div>
        </div>
        <div class="mf-table-frame mt-4"><table class="mf-table" data-standard-table><thead><tr><th>#</th><th>Due date</th><th>Principal</th><th>Interest</th><th>Fees</th><th>Penalty</th><th>Remaining</th><th>Status</th></tr></thead><tbody>
        @foreach($loan->installments as $item)<tr><td>{{ $item->installment_number }}</td><td>{{ $item->due_date->format('d M Y') }}</td><td>{{ number_format((float)$item->principal,2) }}</td><td>{{ number_format((float)$item->interest,2) }}</td><td>{{ number_format((float)$item->fees,2) }}</td><td>{{ number_format((float)$item->penalty_due,2) }}</td><td>{{ number_format((float)$item->remaining,2) }}</td><td>{{ ucfirst($item->status) }}</td></tr>@endforeach
        </tbody></table></div>
    </x-ui.form-section>

    <x-ui.form-section title="Proposed schedule" description="Enter one line per new installment. Amounts must total the current outstanding principal + interest + fees exactly. Existing penalties remain due and are carried into the first new installment.">
        <label class="mf-label">New repayment dates and installment amounts</label>
        <textarea class="mf-input min-h-44 font-mono text-sm" name="new_schedule" id="new_schedule" required placeholder="2026-09-30 | 25000.00&#10;2026-10-31 | 25000.00&#10;2026-11-30 | 25000.00">{{ old('new_schedule') }}</textarea>
        @error('new_schedule')<p class="mf-error">{{ $message }}</p>@enderror
        <div class="mt-3"><button class="mf-btn" type="button" id="preview-restructure">Preview schedule</button><span class="ml-2 text-xs text-muted-foreground" id="restructure-message"></span></div>
        <div class="mt-4 hidden" id="preview-panel">
            <div class="grid gap-2 sm:grid-cols-3"><div class="rounded-md border p-3"><div class="text-xs text-muted-foreground">Scheduled outstanding</div><div class="font-semibold" data-summary="scheduled_outstanding"></div></div><div class="rounded-md border p-3"><div class="text-xs text-muted-foreground">Existing penalties</div><div class="font-semibold" data-summary="penalties"></div></div><div class="rounded-md border p-3"><div class="text-xs text-muted-foreground">Total outstanding</div><div class="font-semibold" data-summary="total_outstanding"></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>Penalty</th><th>Remaining</th></tr></thead><tbody id="preview-body"></tbody></table></div>
        </div>
    </x-ui.form-section>

    <x-ui.form-section title="Reason and evidence">
        <div class="grid gap-3 md:grid-cols-2">
            <div><label class="mf-label">Reason</label><textarea class="mf-input min-h-28" name="reason" required maxlength="4000">{{ old('reason') }}</textarea>@error('reason')<p class="mf-error">{{ $message }}</p>@enderror</div>
            <div><label class="mf-label">Supporting documents</label><input class="mf-input" type="file" name="documents[]" multiple accept=".jpg,.jpeg,.png,.webp,.pdf,.doc,.docx"><p class="mt-1 text-xs text-muted-foreground">Up to 10 files, 8 MB each.</p>@error('documents.*')<p class="mf-error">{{ $message }}</p>@enderror</div>
        </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">Submit for approval</button></x-ui.form-actions>
</form>
</x-ui.form-shell>
<script>
(() => {
    const button=document.getElementById('preview-restructure'), form=document.getElementById('restructure-form'), message=document.getElementById('restructure-message'), panel=document.getElementById('preview-panel'), body=document.getElementById('preview-body');
    button?.addEventListener('click', async () => {
        message.textContent='Calculating…'; panel.classList.add('hidden'); body.innerHTML='';
        const payload=new FormData(); payload.append('_token',form.querySelector('[name="_token"]').value); payload.append('new_schedule',form.new_schedule.value);
        const response=await fetch(@json(route('loan-restructurings.preview',$loan)),{method:'POST',body:payload,headers:{'Accept':'application/json'}}); const data=await response.json();
        if(!response.ok){ message.textContent=data.message || Object.values(data.errors || {}).flat()[0] || 'Unable to preview schedule.'; return; }
        ['scheduled_outstanding','penalties','total_outstanding'].forEach(key=>{document.querySelector(`[data-summary="${key}"]`).textContent=data[key];});
        data.new_schedule.forEach(row=>{ const tr=document.createElement('tr'); ['installment_number','due_date','principal','interest','fees','penalty_due','remaining'].forEach(key=>{const td=document.createElement('td');td.textContent=row[key];tr.appendChild(td);}); body.appendChild(tr); });
        panel.classList.remove('hidden'); message.textContent='Preview uses the current balance. Approval will recheck the balance and schedule before activating it.';
    });
})();
</script>
@endsection
