@extends('layouts.app')
@section('title',$loan->exists?'Edit Loan Application':'New Loan Application')
@section('content')
@php
    $selectedCollateral=collect(old('collateral_ids',$loan->exists?$loan->collaterals->pluck('id')->all():[]))->map(fn($id)=>(int)$id)->all();
    $customDates=old('custom_dates_text',$loan->exists?implode("\n",$loan->custom_repayment_dates ?? []):'');
    $branches->load('loanProducts:id');
    $productBranchIds=$products->mapWithKeys(function($product) use ($branches) {
        return [$product->id=>$branches
            ->filter(fn($branch)=>$branch->allowsLoanProduct($product))
            ->pluck('id')
            ->map(fn($id)=>(string)$id)
            ->all()];
    });
@endphp
<x-ui.form-shell
    :title="$loan->exists ? 'Edit Loan Application' : 'New Loan Application'"
    description="Select the customer, loan product and required security. All financial calculations and the proposed schedule are produced by the backend calculation engine."
    :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Loan Applications','url'=>route('loans.index')],['label'=>$loan->exists?'Edit':'Create']]"
>
<form id="loan-application-form" method="POST" enctype="multipart/form-data" action="{{ $loan->exists?route('loans.update',$loan):route('loans.store') }}" class="mf-form">
@csrf
@if($loan->exists)@method('PUT')@endif

<x-ui.form-section title="Application identity" description="Choose the branch and borrower. These are fixed once the draft is created.">
<x-ui.form-grid>
@if($loan->exists)
    <input type="hidden" name="branch_id" value="{{ $loan->branch_id }}"><input type="hidden" name="customer_id" value="{{ $loan->customer_id }}">
    <div class="mf-col-4"><label class="mf-field-label">Branch</label><input class="mf-input" value="{{ $branches->firstWhere('id',$loan->branch_id)?->name }}" disabled></div>
    <div class="mf-col-8"><label class="mf-field-label">Customer</label><input class="mf-input" value="{{ $customers->firstWhere('id',$loan->customer_id)?->full_name }} · {{ $customers->firstWhere('id',$loan->customer_id)?->customer_number }}" disabled></div>
@else
    <div class="mf-col-4"><label class="mf-field-label">Branch</label><select id="loan-branch" class="mf-input" name="branch_id" required><option value="">Select branch</option>@foreach($branches as $branch)<option value="{{ $branch->id }}" @selected((int)old('branch_id')===$branch->id)>{{ $branch->name }}</option>@endforeach</select>@error('branch_id')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
    <div class="mf-col-8"><label class="mf-field-label">Customer</label><select id="loan-customer" class="mf-input" name="customer_id" required><option value="">Select customer</option>@foreach($customers as $customer)<option value="{{ $customer->id }}" data-branch="{{ $customer->branch_id }}" @selected((int)old('customer_id')===$customer->id)>{{ $customer->full_name }} · {{ $customer->customer_number }} · {{ $customer->phone }}</option>@endforeach</select>@error('customer_id')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
@endif
</x-ui.form-grid>
</x-ui.form-section>

<x-ui.form-section title="Loan terms" description="The selected product controls amount limits, interest, fees, duration and repayment frequency.">
<x-ui.form-grid>
<div class="mf-col-4"><label class="mf-field-label">Loan product</label><select id="loan-product" class="mf-input" name="loan_product_id" required><option value="">Select product</option>@foreach($products as $product)<option value="{{ $product->id }}" data-branches="{{ implode(',', $productBranchIds->get($product->id, [])) }}" data-collateral="{{ $product->collateral_required?1:0 }}" data-guarantor="{{ $product->guarantor_required?1:0 }}" data-frequency="{{ $product->repayment_frequency }}" @selected((int)old('loan_product_id',$loan->loan_product_id)===$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">Principal requested</label><input id="loan-principal" type="number" step="0.01" min="0.01" class="mf-input" name="principal" value="{{ old('principal',$loan->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 id="loan-start-date" type="date" class="mf-input" name="schedule_start_date" value="{{ old('schedule_start_date',optional($loan->schedule_start_date)->format('Y-m-d') ?? now()->format('Y-m-d')) }}" required>@error('schedule_start_date')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
<div class="mf-col-2 flex items-end"><button id="loan-preview-button" type="button" class="mf-btn w-full">Calculate preview</button></div>
<div class="mf-col-12"><label class="mf-field-label">Purpose</label><textarea class="mf-input" name="purpose" rows="3" required>{{ old('purpose',$loan->purpose) }}</textarea>@error('purpose')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
<div class="mf-col-12" id="custom-dates-wrap"><label class="mf-field-label">Custom repayment dates</label><textarea id="custom-dates-text" class="mf-input" name="custom_dates_text" rows="3" placeholder="One date per line, for example 2026-09-01">{{ $customDates }}</textarea><p class="mf-field-help">Required only for products using custom repayment dates.</p>@error('custom_dates_text')<p class="mf-field-error">{{ $message }}</p>@enderror</div>
</x-ui.form-grid>
<div id="loan-requirement-note" class="mt-3 text-xs text-muted-foreground"></div>
</x-ui.form-section>

<x-ui.form-section title="Collateral / Dhamana" description="Select collateral already registered for this borrower. Required products cannot proceed without linked collateral.">
<div class="mf-option-grid" id="collateral-options">
@forelse($collaterals as $collateral)
<label class="mf-option" data-customer="{{ $collateral->customer_id }}" data-branch="{{ $collateral->branch_id }}"><input type="checkbox" name="collateral_ids[]" value="{{ $collateral->id }}" @checked(in_array($collateral->id,$selectedCollateral,true))><span><strong>{{ $collateral->code }}</strong><small class="block text-muted-foreground">{{ $collateral->item }} · {{ str($collateral->status)->replace('_',' ')->title() }} · value {{ number_format((float)($collateral->accepted_value ?? 0),2) }}</small></span></label>
@empty<p class="text-sm text-muted-foreground">No available collateral records.</p>@endforelse
</div>@error('collateral_ids')<p class="mf-field-error">{{ $message }}</p>@enderror
</x-ui.form-section>

<x-ui.form-section title="Guarantor" description="Select an active guarantor already registered on the customer profile when the product requires one.">
<x-ui.form-grid><div class="mf-col-6"><label class="mf-field-label">Guarantor</label><select id="loan-guarantor" class="mf-input" name="guarantor_id"><option value="">No guarantor selected</option>@foreach($guarantors as $guarantor)<option value="{{ $guarantor->id }}" data-customer="{{ $guarantor->customer_id }}" @selected((int)old('guarantor_id',$loan->guarantor_id)===$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(!$loan->exists)
<x-ui.form-section title="Supporting documents" description="Attach application-specific documents now, or upload additional documents from the loan detail page later.">
<x-ui.form-grid><div class="mf-col-8"><label class="mf-field-label">Supporting files</label><input type="file" class="mf-input" name="supporting_documents[]" multiple accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx"><p class="mf-field-help">PDF, images or Word documents. Maximum 10 MB each.</p></div></x-ui.form-grid>
</x-ui.form-section>
@endif

<x-ui.form-section title="Proposed repayment schedule" description="This preview comes from the same backend engine that will be persisted when the application is saved.">
<div id="loan-preview-empty" class="text-sm text-muted-foreground">Enter the product, principal and start date, then select Calculate preview.</div>
<div id="loan-preview-result" class="hidden">
<div class="grid gap-3 md:grid-cols-4 mb-4"><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Principal</div><div id="preview-principal" class="font-semibold"></div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Interest</div><div id="preview-interest" class="font-semibold"></div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Fees</div><div id="preview-fees" class="font-semibold"></div></div><div class="mf-card mf-card-body"><div class="text-xs text-muted-foreground">Total repayment</div><div id="preview-total" class="font-semibold"></div></div></div>
<div class="mf-table-frame"><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="preview-installments"></tbody></table></div>
</div>
<div id="loan-preview-error" class="hidden mt-3 text-sm text-destructive"></div>
</x-ui.form-section>

<x-ui.form-actions><a class="mf-btn" href="{{ $loan->exists?route('loans.show',$loan):route('loans.index') }}">Cancel</a><button class="mf-btn mf-btn-primary" type="submit">{{ $loan->exists?'Save draft changes':'Create draft application' }}</button></x-ui.form-actions>
</form>
</x-ui.form-shell>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', () => {
    const form=document.getElementById('loan-application-form');
    const branch=document.getElementById('loan-branch');
    const customer=document.getElementById('loan-customer');
    const product=document.getElementById('loan-product');
    const guarantor=document.getElementById('loan-guarantor');
    const collateralOptions=[...document.querySelectorAll('#collateral-options [data-customer]')];
    const customWrap=document.getElementById('custom-dates-wrap');
    const note=document.getElementById('loan-requirement-note');

    function filterOptions(){
        const branchId=branch?.value || '{{ $loan->branch_id }}';
        const customerId=customer?.value || '{{ $loan->customer_id }}';
        if(customer){ [...customer.options].forEach(o=>{ if(!o.value)return; o.hidden=!!branchId && o.dataset.branch!==branchId; }); }
        if(product){
            [...product.options].forEach(o=>{
                if(!o.value)return;
                const allowed=(o.dataset.branches||'').split(',').filter(Boolean);
                const unavailable=!!branchId && !allowed.includes(branchId);
                o.hidden=unavailable;
                o.disabled=unavailable;
            });
            if(product.selectedOptions[0]?.disabled) product.value='';
        }
        collateralOptions.forEach(el=>{ el.hidden=!!customerId && el.dataset.customer!==customerId || !!branchId && el.dataset.branch!==branchId; if(el.hidden) el.querySelector('input').checked=false; });
        if(guarantor){ [...guarantor.options].forEach(o=>{ if(!o.value)return; o.hidden=!!customerId && o.dataset.customer!==customerId; }); if(guarantor.selectedOptions[0]?.hidden) guarantor.value=''; }
        productInfo();
    }
    function productInfo(){
        const option=product?.selectedOptions[0]; if(!option || !option.value){ note.textContent=''; customWrap.hidden=true; return; }
        const needs=[]; if(option.dataset.collateral==='1')needs.push('collateral'); if(option.dataset.guarantor==='1')needs.push('guarantor');
        note.textContent=needs.length?'This product requires '+needs.join(' and ')+'.':'This product does not require collateral or a guarantor.';
        customWrap.hidden=option.dataset.frequency!=='custom';
    }
    branch?.addEventListener('change',()=>{ if(customer)customer.value=''; filterOptions(); });
    customer?.addEventListener('change',filterOptions); product?.addEventListener('change',productInfo);
    filterOptions();

    document.getElementById('loan-preview-button')?.addEventListener('click', async () => {
        const error=document.getElementById('loan-preview-error'); error.classList.add('hidden');
        try {
            const response=await fetch('{{ route('loans.preview') }}',{method:'POST',headers:{'Content-Type':'application/json','Accept':'application/json','X-CSRF-TOKEN':document.querySelector('meta[name="csrf-token"]').content},body:JSON.stringify({branch_id:branch?.value || '{{ $loan->branch_id }}',loan_product_id:product.value,principal:document.getElementById('loan-principal').value,schedule_start_date:document.getElementById('loan-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||{}).flat()[0] || 'Unable to calculate schedule.');
            document.getElementById('preview-principal').textContent=data.summary.principal;
            document.getElementById('preview-interest').textContent=data.summary.interest;
            document.getElementById('preview-fees').textContent=data.summary.fees;
            document.getElementById('preview-total').textContent=data.summary.total_repayment;
            document.getElementById('preview-installments').innerHTML=data.installments.map(i=>`<tr><td>${i.number}</td><td>${i.due_date}</td><td>${i.principal}</td><td>${i.interest}</td><td>${i.fees}</td><td>${i.amount_due}</td></tr>`).join('');
            document.getElementById('loan-preview-empty').classList.add('hidden'); document.getElementById('loan-preview-result').classList.remove('hidden');
        } catch(e) { error.textContent=e.message; error.classList.remove('hidden'); }
    });
});
</script>
@endpush
