@extends('layouts.app')

@section('title', $loan->loan_number)
@section('page-title', $loan->loan_number)
@section('page-subtitle', $loan->customer?->fullName())

@section('content')
@php
    $currency = $loan->tenant->settings['currency'] ?? 'NGN';
    $currencySymbol = $currency === 'NGN' ? '₦' : $currency.' ';
    $currencySymbol = $currency.' ';
    $money = fn ($amount) => $currencySymbol.number_format((float) $amount, 2);
    $schedules = $loan->schedules->sortBy('installment_no')->values();
    $archivedSchedules = $loan->archivedSchedules->sortByDesc('schedule_version')->values();
    $archivedScheduleVersions = $archivedSchedules->groupBy('schedule_version');
    $hasArchivedSchedules = $archivedSchedules->isNotEmpty();
    $currentSchedulePaidAmount = (float) $schedules->sum(fn ($schedule) => (float) $schedule->paid_amount);
    $lifetimePaidAmount = (float) $loan->payments->where('status', 'posted')->sum('amount');
    $paidAmount = $currentSchedulePaidAmount;
    $repaymentTotal = max(0, (float) $schedules->sum(fn ($schedule) => (float) $schedule->total_due));
    $remainingBalance = max(0, (float) $loan->balance);
    $paidPercent = $repaymentTotal > 0 ? min(100, round(($paidAmount / $repaymentTotal) * 100, 2)) : 0;
    $nextSchedule = $schedules->whereIn('status', ['pending', 'partial', 'overdue'])->sortBy('due_date')->first();
    $scheduleCount = $schedules->count();
    $paidScheduleCount = $schedules->where('status', 'paid')->count();
    $schedulePercent = $scheduleCount > 0 ? min(100, round(($paidScheduleCount / $scheduleCount) * 100, 2)) : 0;
    $breakdownTotal = max(1, (float) $loan->principal + (float) $loan->interest_amount + (float) $loan->processing_fee);
    $principalPercent = round(((float) $loan->principal / $breakdownTotal) * 100, 2);
    $interestPercent = round(((float) $loan->interest_amount / $breakdownTotal) * 100, 2);
    $feePercent = max(0, 100 - $principalPercent - $interestPercent);
    $scheduleBalance = (float) $schedules->sum(fn ($schedule) => max(0, (float) $schedule->total_due - (float) $schedule->paid_amount));
    $openScheduleCount = max(1, $schedules->whereIn('status', ['pending', 'partial', 'overdue'])->count());
    $frequencyLabels = \App\Services\LoanCalculator::CUSTOM_REPAYMENT_FREQUENCIES;
    $repaymentFrequency = $frequencyLabels[$loan->repayment_frequency] ?? str($loan->repayment_frequency)->replace('_', ' ')->headline()->toString();
    $scheduledAmounts = $schedules
        ->pluck('total_due')
        ->map(fn ($amount) => round((float) $amount, 2))
        ->unique()
        ->values();
    $repaymentAmount = $scheduledAmounts->isEmpty()
        ? null
        : ($scheduledAmounts->count() === 1
            ? $money($scheduledAmounts->first())
            : $money($scheduledAmounts->min()).' - '.$money($scheduledAmounts->max()));
    $canEditBeforeDisbursement = ! $loan->disbursed_at && (float) $loan->amount_disbursed <= 0 && in_array($loan->status, ['applied', 'under_review', 'approved'], true);
    $reschedulePanelOpen = old('remaining_term_value') !== null || old('reschedule_note') !== null;
    $loanStatusLabel = str($loan->status)->replace('_', ' ')->headline()->toString();
    $loanStatusClass = match ($loan->status) {
        'active', 'disbursed', 'completed' => 'text-bg-success',
        'approved' => 'text-bg-primary',
        'rejected' => 'text-bg-danger',
        'under_review' => 'text-bg-info',
        default => 'text-bg-secondary',
    };
    $feeTimingLabel = $loan->processingFeeTimingLabel();
    $netDisbursement = $loan->netDisbursementAmount();
    $canApproveRepayments = auth()->user()->hasPermission('repayments.approve');
    $canCancelRepayments = $canApproveRepayments;
    $paymentStatusClass = fn ($status) => match ($status ?? 'posted') {
        'posted' => 'text-bg-success',
        'pending' => 'text-bg-warning',
        'rejected' => 'text-bg-danger',
        'canceled' => 'text-bg-secondary',
        default => 'text-bg-light text-dark',
    };
@endphp

<section class="loan-progress-hero mb-4">
    <div class="loan-progress-copy">
        <div class="d-flex flex-wrap gap-2 align-items-center mb-2">
            <span class="badge text-bg-light text-dark">{{ $loan->product?->name ?? 'Loan' }}</span>
            <span class="badge text-bg-secondary">{{ ucfirst(str_replace('_', ' ', $loan->status)) }}</span>
        </div>
        <h2>{{ $loan->loan_number }}</h2>
        <p>{{ $loan->purpose ?: 'Loan application and repayment tracking for '.$loan->customer?->fullName().'.' }}</p>
        <div class="loan-plan-strip">
            <div><span>Principal</span><strong>{{ $money($loan->principal) }}</strong></div>
            <div><span>Total payable</span><strong>{{ $money($loan->total_payable) }}</strong></div>
            <div><span>First repayment</span><strong>{{ app_date($loan->first_repayment_date) ?? '-' }}</strong></div>
            <div><span>Period</span><strong>{{ $repaymentFrequency }}</strong></div>
        </div>
    </div>

    <div class="loan-progress-visual">
        <div class="loan-progress-ring" style="--progress: {{ $paidPercent }}%;">
            <div>
                <strong>{{ number_format($paidPercent, $paidPercent == (int) $paidPercent ? 0 : 1) }}%</strong>
                <span>repaid</span>
            </div>
        </div>
        <div class="loan-progress-bar">
            <div class="d-flex justify-content-between small mb-2">
                <span>Repayment progress</span>
                <strong>{{ $money($currentSchedulePaidAmount) }} paid</strong>
            </div>
            <div class="progress">
                <div class="progress-bar" style="width: {{ $paidPercent }}%"></div>
            </div>
            <div class="d-flex justify-content-between small mt-2 text-muted">
                <span>Balance {{ $money($remainingBalance) }}</span>
                <span>{{ $paidScheduleCount }}/{{ $scheduleCount }} schedules paid</span>
            </div>
        </div>
    </div>
</section>

<div class="row g-3 mb-4">
    <div class="col-md-3"><div class="loan-metric-card"><span>Current paid</span><strong>{{ $money($currentSchedulePaidAmount) }}</strong><small>Total paid {{ $money($lifetimePaidAmount) }}</small></div></div>
    <div class="col-md-3"><div class="loan-metric-card"><span>Outstanding balance</span><strong>{{ $money($remainingBalance) }}</strong></div></div>
    <div class="col-md-3"><div class="loan-metric-card"><span>Next due</span><strong>{{ app_date($nextSchedule?->due_date) ?? '-' }}</strong><small>{{ $nextSchedule ? $money(max(0, (float) $nextSchedule->total_due - (float) $nextSchedule->paid_amount)) : 'No open schedule' }}</small></div></div>
    <div class="col-md-3"><div class="loan-metric-card"><span>Schedule progress</span><strong>{{ number_format($schedulePercent, $schedulePercent == (int) $schedulePercent ? 0 : 1) }}%</strong><small>{{ $paidScheduleCount }} of {{ $scheduleCount }} paid</small></div></div>
</div>

<div class="row g-4">
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm h-100 loan-breakdown-card">
            <div class="card-body">
                <div class="loan-breakdown-head">
                    <div>
                        <span>Loan breakdown</span>
                        <h2>{{ $loan->product?->name ?? 'Loan account' }}</h2>
                    </div>
                    <span class="badge {{ $loanStatusClass }}">{{ $loanStatusLabel }}</span>
                </div>

                <div class="loan-balance-focus">
                    <span>Outstanding balance</span>
                    <strong>{{ $money($loan->balance) }}</strong>
                    <small>{{ $paidScheduleCount }} of {{ $scheduleCount }} schedule{{ $scheduleCount === 1 ? '' : 's' }} paid</small>
                </div>

                <div class="loan-breakdown-stack" aria-label="Loan amount breakdown">
                    <div class="loan-breakdown-principal" style="width: {{ $principalPercent }}%"></div>
                    <div class="loan-breakdown-interest" style="width: {{ $interestPercent }}%"></div>
                    <div class="loan-breakdown-fee" style="width: {{ $feePercent }}%"></div>
                </div>

                <div class="loan-breakdown-legend">
                    <span><i class="bi bi-square-fill text-primary"></i>Principal</span>
                    <span><i class="bi bi-square-fill text-warning"></i>Interest</span>
                    <span><i class="bi bi-square-fill text-success"></i>Processing fee</span>
                </div>

                <div class="loan-amount-grid">
                    <div><span>Principal</span><strong>{{ $money($loan->principal) }}</strong></div>
                    <div><span>Interest</span><strong>{{ $money($loan->interest_amount) }}</strong></div>
                    <div><span>Processing fee</span><strong>{{ $money($loan->processing_fee) }}</strong><small>{{ $feeTimingLabel }}</small></div>
                    <div><span>Total payable</span><strong>{{ $money($loan->total_payable) }}</strong><small>Excludes fee</small></div>
                    <div><span>Net disbursement</span><strong>{{ $money($loan->amount_disbursed ?: $netDisbursement) }}</strong><small>{{ ($loan->processing_fee_timing ?? 'before_disbursement') === 'deduct_from_disbursement' ? 'After fee deduction' : 'Full principal' }}</small></div>
                </div>

                <div class="loan-info-section">
                    <h3>Repayment plan</h3>
                    <div class="loan-info-row"><span>{{ $repaymentFrequency }} repayment</span><strong>{{ $repaymentAmount ?? '-' }}</strong></div>
                    <div class="loan-info-row"><span>First repayment</span><strong>{{ app_date($loan->first_repayment_date) ?? '-' }}</strong></div>
                    <div class="loan-info-row"><span>Loan term</span><strong>{{ $loan->term_value }} {{ $loan->term_unit }}</strong></div>
                </div>

                <div class="loan-info-section">
                    <h3>Workflow</h3>
                    <div class="loan-info-row"><span>Initiated by</span><strong>{{ $loan->creator?->name ?? 'System / member' }}</strong></div>
                    <div class="loan-info-row"><span>Approved by</span><strong>{{ $loan->approver?->name ?? 'Not approved yet' }}</strong></div>
                    <div class="loan-info-row"><span>Disbursed by</span><strong>{{ $loan->disburser?->name ?? ($loan->disbursed_at ? 'Unknown user' : 'Not disbursed yet') }}</strong></div>
                </div>

                <div class="loan-breakdown-actions">
                    @if(in_array($loan->status, ['applied','under_review']) && auth()->user()->hasPermission('loans.approve'))
                        <form method="POST" action="{{ route('tenant.loans.approve', $loan) }}">@csrf<button class="btn btn-success btn-sm">Approve</button></form>
                    @endif
                    @if($loan->status === 'approved' && auth()->user()->hasPermission('loans.disburse'))
                        <form method="POST" action="{{ route('tenant.loans.disburse', $loan) }}">@csrf<button class="btn btn-primary btn-sm">Disburse</button></form>
                    @endif
                    @if(in_array($loan->status, ['applied','under_review']) && auth()->user()->hasPermission('loans.approve'))
                        <form method="POST" action="{{ route('tenant.loans.reject', $loan) }}">@csrf<input type="hidden" name="rejected_reason" value="Rejected after review."><button class="btn btn-outline-danger btn-sm">Reject</button></form>
                    @endif
                    @if($canEditBeforeDisbursement && auth()->user()->hasPermission('loans.create'))
                        <a class="btn btn-outline-secondary btn-sm" href="{{ route('tenant.loans.edit', $loan) }}">Edit loan</a>
                    @endif
                    @if(in_array($loan->status, ['active','disbursed']) && auth()->user()->hasPermission('loans.approve'))
                        <button
                            class="btn btn-outline-primary btn-sm"
                            type="button"
                            data-bs-toggle="collapse"
                            data-bs-target="#loanReschedulePanel"
                            aria-expanded="{{ $reschedulePanelOpen ? 'true' : 'false' }}"
                            aria-controls="loanReschedulePanel"
                        >
                            Reschedule loan
                        </button>
                    @endif
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <h2 class="h5 mb-3">Record repayment</h2>
                @if(in_array($loan->status, ['active','disbursed']) && auth()->user()->hasPermission('repayments.record'))
                    <form method="POST" action="{{ route('tenant.loans.payments.store', $loan) }}" class="row g-2">
                        @csrf
                        <div class="col-md-4"><input name="amount" value="{{ old('amount', number_format($nextPaymentAmount ?? 0, 2, '.', '')) }}" type="number" step="0.01" min="0.01" max="{{ $loan->balance }}" class="form-control" placeholder="Amount" required></div>
                        <div class="col-md-3"><select name="method" class="form-select"><option value="cash">Cash</option><option value="transfer">Transfer</option><option value="pos">POS</option></select></div>
                        <div class="col-md-3"><input name="notes" class="form-control" placeholder="Notes"></div>
                        <div class="col-md-2 d-grid"><button class="btn btn-primary">Submit</button></div>
                    </form>
                @else
                    <div class="text-muted small">Repayment can be recorded after the loan is disbursed.</div>
                @endif
            </div>
            <div class="table-responsive">
                <table class="table mb-0">
                    <thead><tr><th>Date</th><th>Reference</th><th>Status</th><th>Initiated by</th><th>Approved by</th><th>Amount</th><th>Balance</th><th></th></tr></thead>
                    <tbody>
                        @foreach($loan->payments as $payment)
                            <tr>
                                <td>{{ app_date($payment->paid_at) }}</td>
                                <td>{{ $payment->reference }}</td>
                                <td><span class="badge {{ $paymentStatusClass($payment->status) }}">{{ ucfirst($payment->status ?? 'posted') }}</span></td>
                                <td>{{ $payment->receiver?->name ?? 'System / member' }}</td>
                                <td>{{ $payment->approver?->name ?? '-' }}</td>
                                <td>{{ $money($payment->amount) }}</td>
                                <td>{{ $money($payment->balance_after) }}</td>
                                <td class="text-end">
                                    <div class="dropdown">
                                        <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Actions</button>
                                        <ul class="dropdown-menu dropdown-menu-end">
                                            @if(in_array($payment->status ?? 'posted', ['posted', 'canceled'], true))
                                                <li><a href="{{ route('tenant.loan-payments.receipt', $payment) }}" class="dropdown-item"><i class="bi bi-receipt me-2"></i>Receipt</a></li>
                                            @endif
                                            @if($canApproveRepayments && $payment->status === 'pending')
                                                <li>
                                                    <form method="POST" action="{{ route('tenant.loan-payments.approve', $payment) }}">
                                                        @csrf
                                                        <button class="dropdown-item text-success"><i class="bi bi-check2-circle me-2"></i>Approve</button>
                                                    </form>
                                                </li>
                                                <li><button class="dropdown-item text-danger" type="button" data-bs-toggle="modal" data-bs-target="#rejectLoanPayment{{ $payment->id }}"><i class="bi bi-x-circle me-2"></i>Reject</button></li>
                                            @endif
                                            @if($canCancelRepayments && ($payment->status ?? 'posted') === 'posted')
                                                <li><button class="dropdown-item text-danger" type="button" data-bs-toggle="modal" data-bs-target="#cancelLoanPayment{{ $payment->id }}"><i class="bi bi-slash-circle me-2"></i>Cancel</button></li>
                                            @endif
                                        </ul>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                        @if($loan->payments->isEmpty())
                            <tr><td colspan="8" class="text-center text-muted py-4">No repayments recorded yet.</td></tr>
                        @endif
                    </tbody>
                </table>
            </div>
            @if($canCancelRepayments)
                @foreach($loan->payments->where('status', 'posted') as $payment)
                    <div class="modal fade" id="cancelLoanPayment{{ $payment->id }}" tabindex="-1" aria-labelledby="cancelLoanPayment{{ $payment->id }}Label" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered">
                            <div class="modal-content border-0 shadow">
                                <form method="POST" action="{{ route('tenant.loan-payments.cancel', $payment) }}">
                                    @csrf
                                    <div class="modal-header">
                                        <div>
                                            <h2 class="modal-title h5" id="cancelLoanPayment{{ $payment->id }}Label">Cancel loan repayment</h2>
                                            <div class="text-muted small">{{ $payment->reference }} | {{ $money($payment->amount) }}</div>
                                        </div>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body">
                                        <label class="form-label">Cancellation reason</label>
                                        <textarea name="canceled_reason" class="form-control" rows="3" required></textarea>
                                        <div class="form-text">The repayment schedule, loan balance, and accounting entries will be reversed.</div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                                        <button class="btn btn-danger">Cancel repayment</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                @endforeach
            @endif
            @if($canApproveRepayments)
                @foreach($loan->payments->where('status', 'pending') as $payment)
                    <div class="modal fade" id="rejectLoanPayment{{ $payment->id }}" tabindex="-1" aria-labelledby="rejectLoanPayment{{ $payment->id }}Label" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered">
                            <div class="modal-content border-0 shadow">
                                <form method="POST" action="{{ route('tenant.loan-payments.reject', $payment) }}">
                                    @csrf
                                    <div class="modal-header">
                                        <div>
                                            <h2 class="modal-title h5" id="rejectLoanPayment{{ $payment->id }}Label">Reject loan repayment</h2>
                                            <div class="text-muted small">{{ $payment->reference }} | {{ $money($payment->amount) }}</div>
                                        </div>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body">
                                        <label class="form-label">Rejection reason</label>
                                        <textarea name="rejected_reason" class="form-control" rows="3" required></textarea>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                                        <button class="btn btn-danger">Reject repayment</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                @endforeach
            @endif
        </div>
    </div>

    @if(in_array($loan->status, ['active','disbursed']) && auth()->user()->hasPermission('loans.approve'))
        <div class="col-12 collapse {{ $reschedulePanelOpen ? 'show' : '' }}" id="loanReschedulePanel">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex flex-column flex-lg-row justify-content-between gap-3 mb-3">
                        <div>
                            <h2 class="h5 mb-1">Reschedule loan</h2>
                            <div class="text-muted small">Use the current remaining balance and spread it over a new remaining term. Paid repayment history is kept.</div>
                        </div>
                        <span class="badge text-bg-light align-self-start">Open schedules: {{ $openScheduleCount }}</span>
                    </div>
                    <form method="POST" action="{{ route('tenant.loans.reschedule', $loan) }}" class="row g-3 align-items-end">
                        @csrf
                        <div class="col-12">
                            <div class="reschedule-summary">
                                <div>
                                    <span>Outstanding balance to reschedule</span>
                                    <strong>{{ $money($remainingBalance) }}</strong>
                                </div>
                                <p class="mb-0">The unpaid balance will be shared across the new remaining payments. Use adjustments only when you need to add or reduce principal, interest, or penalty before the new schedule is created.</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Remaining payments</label>
                            <input name="remaining_term_value" type="number" min="1" max="240" value="{{ old('remaining_term_value', $openScheduleCount) }}" class="form-control" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Period</label>
                            <select name="repayment_frequency" class="form-select">
                                @foreach(\App\Services\LoanCalculator::CUSTOM_REPAYMENT_FREQUENCIES as $value => $label)
                                    <option value="{{ $value }}" @selected(old('repayment_frequency', $loan->repayment_frequency) === $value)>{{ $label }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">First due date</label>
                            <input name="first_repayment_date" type="date" value="{{ old('first_repayment_date') }}" class="form-control">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Principal adjustment</label>
                            <input name="principal_adjustment" type="number" step="0.01" value="{{ old('principal_adjustment', 0) }}" class="form-control">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Interest adjustment</label>
                            <input name="interest_adjustment" type="number" step="0.01" value="{{ old('interest_adjustment', 0) }}" class="form-control">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Penalty adjustment</label>
                            <input name="penalty_adjustment" type="number" step="0.01" value="{{ old('penalty_adjustment', 0) }}" class="form-control">
                        </div>
                        <div class="col-lg-9">
                            <label class="form-label">Reschedule note</label>
                            <textarea name="reschedule_note" rows="2" class="form-control" placeholder="Reason or approval note">{{ old('reschedule_note') }}</textarea>
                            <div class="form-text">Positive values add to the balance. Negative values reduce that component.</div>
                        </div>
                        <div class="col-md-3 d-grid">
                            <button class="btn btn-outline-primary">Reschedule</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    @endif

    <div class="col-12">
        <div class="card border-0 shadow-sm repayment-schedule-card" id="repayment-schedule">
            <div class="card-header bg-white border-0">
                <div class="d-flex flex-column flex-lg-row justify-content-between gap-3 align-items-lg-center">
                    <div>
                        <h2 class="h5 mb-0">Repayment Schedule</h2>
                    </div>
                    <div class="d-flex flex-wrap gap-2">
                        <button class="btn btn-outline-primary schedule-action-btn" type="button" data-schedule-copy>Copy</button>
                        <button class="btn btn-outline-primary schedule-action-btn" type="button" data-schedule-excel>Excel</button>
                        <button class="btn btn-outline-primary schedule-action-btn" type="button" data-schedule-pdf>PDF</button>
                        <button class="btn btn-outline-primary schedule-action-btn" type="button" data-schedule-print>Print</button>
                    </div>
                </div>
                @if($hasArchivedSchedules)
                    <ul class="nav nav-pills schedule-version-tabs mt-3" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="current-schedule-tab" data-bs-toggle="pill" data-bs-target="#current-schedule-pane" type="button" role="tab" aria-controls="current-schedule-pane" aria-selected="true">Current schedule</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="old-schedule-tab" data-bs-toggle="pill" data-bs-target="#old-schedule-pane" type="button" role="tab" aria-controls="old-schedule-pane" aria-selected="false">Old schedule</button>
                        </li>
                    </ul>
                @endif
                <div class="d-flex justify-content-end align-items-center gap-2 mt-3">
                    <label class="form-label mb-0">Search</label>
                    <input class="form-control schedule-search" data-schedule-search>
                </div>
            </div>

            <div class="{{ $hasArchivedSchedules ? 'tab-content' : '' }}">
                <div class="{{ $hasArchivedSchedules ? 'tab-pane fade show active' : '' }}" id="current-schedule-pane" role="tabpanel" aria-labelledby="current-schedule-tab">
                    @if($schedules->isEmpty())
                        <div class="card-body">
                            <div class="alert alert-warning mb-0">
                                No repayment schedule is available for this loan yet.
                                @if(auth()->user()->hasPermission('loans.approve'))
                                    Use <strong>Reschedule loan</strong> above to create a repayment plan.
                                @endif
                            </div>
                        </div>
                    @else
                        <div class="table-responsive">
                            <table class="table table-bordered repayment-schedule-table mb-0" data-repayment-table data-export-name="{{ $loan->loan_number }}-repayment-schedule">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th class="text-end">Amount to Pay</th>
                                        <th class="text-end">Paid Amount</th>
                                        <th class="text-end">Principal Amount</th>
                                        <th class="text-end">Interest</th>
                                        <th class="text-end">Late Penalty</th>
                                        <th class="text-end">Balance</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($schedules as $schedule)
                                        @php
                                            $amountToPay = max(0, (float) $schedule->total_due - (float) $schedule->paid_amount);
                                            $scheduleBalance = max(0, $scheduleBalance - $amountToPay);
                                            $statusLabel = match ($schedule->status) {
                                                'paid' => 'Paid',
                                                'partial' => 'Partial',
                                                'overdue' => 'Overdue',
                                                default => 'Unpaid',
                                            };
                                            $statusClass = match ($schedule->status) {
                                                'paid' => 'text-bg-success',
                                                'partial' => 'text-bg-info',
                                                'overdue' => 'text-bg-danger',
                                                default => 'text-bg-warning',
                                            };
                                        @endphp
                                        <tr data-searchable="{{ strtolower(app_date($schedule->due_date).' '.$statusLabel.' '.$money($amountToPay).' '.$money($schedule->paid_amount)) }}">
                                            <td>{{ app_date($schedule->due_date) }}</td>
                                            <td class="text-end">{{ $money($amountToPay) }}</td>
                                            <td class="text-end text-success">{{ $money($schedule->paid_amount) }}</td>
                                            <td class="text-end">{{ $money($schedule->principal_due) }}</td>
                                            <td class="text-end">{{ $money($schedule->interest_due) }}</td>
                                            <td class="text-end">{{ $money($schedule->penalty_due) }}</td>
                                            <td class="text-end">{{ $money($scheduleBalance) }}</td>
                                            <td><span class="badge {{ $statusClass }}">{{ $statusLabel }}</span></td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @endif
                </div>

                @if($hasArchivedSchedules)
                    <div class="tab-pane fade" id="old-schedule-pane" role="tabpanel" aria-labelledby="old-schedule-tab">
                        <div class="archived-schedule-stack">
                            @foreach($archivedScheduleVersions as $version => $versionSchedules)
                                @php
                                    $versionRows = $versionSchedules->sortBy('installment_no')->values();
                                    $versionBalance = (float) $versionRows->sum(fn ($schedule) => max(0, (float) $schedule->total_due - (float) $schedule->paid_amount));
                                    $versionMeta = $versionRows->first(fn ($schedule) => $schedule->archived_at || $schedule->rescheduler || $schedule->reschedule_note) ?? $versionRows->first();
                                @endphp
                                <div class="archived-schedule-version">
                                    <div class="archived-schedule-heading">
                                        <div>
                                            <h3 class="h6 mb-1">Old schedule version {{ $version }}</h3>
                                            <div class="text-muted small">
                                                Archived {{ app_datetime($versionMeta?->archived_at) ?? '-' }}
                                                by {{ $versionMeta?->rescheduler?->name ?? 'System' }}
                                            </div>
                                        </div>
                                        <span class="badge text-bg-secondary">{{ $versionRows->count() }} installment{{ $versionRows->count() === 1 ? '' : 's' }}</span>
                                    </div>
                                    @if(filled($versionMeta?->reschedule_note))
                                        <div class="archived-note">{{ $versionMeta->reschedule_note }}</div>
                                    @endif
                                    <div class="table-responsive">
                                        <table class="table table-bordered repayment-schedule-table archived-repayment-table mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th class="text-end">Amount to Pay</th>
                                                    <th class="text-end">Paid Amount</th>
                                                    <th class="text-end">Principal Amount</th>
                                                    <th class="text-end">Interest</th>
                                                    <th class="text-end">Late Penalty</th>
                                                    <th class="text-end">Balance</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @foreach($versionRows as $schedule)
                                                    @php
                                                        $amountToPay = max(0, (float) $schedule->total_due - (float) $schedule->paid_amount);
                                                        $versionBalance = max(0, $versionBalance - $amountToPay);
                                                        $statusLabel = match ($schedule->status) {
                                                            'paid' => 'Paid',
                                                            'partial' => 'Partial',
                                                            'overdue' => 'Overdue',
                                                            default => 'Unpaid',
                                                        };
                                                        $statusClass = match ($schedule->status) {
                                                            'paid' => 'text-bg-success',
                                                            'partial' => 'text-bg-info',
                                                            'overdue' => 'text-bg-danger',
                                                            default => 'text-bg-warning',
                                                        };
                                                    @endphp
                                                    <tr>
                                                        <td>{{ app_date($schedule->due_date) ?? '-' }}</td>
                                                        <td class="text-end">{{ $money($amountToPay) }}</td>
                                                        <td class="text-end text-success">{{ $money($schedule->paid_amount) }}</td>
                                                        <td class="text-end">{{ $money($schedule->principal_due) }}</td>
                                                        <td class="text-end">{{ $money($schedule->interest_due) }}</td>
                                                        <td class="text-end">{{ $money($schedule->penalty_due) }}</td>
                                                        <td class="text-end">{{ $money($versionBalance) }}</td>
                                                        <td><span class="badge {{ $statusClass }}">{{ $statusLabel }}</span></td>
                                                    </tr>
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    </div>
                @endif
            </div>
        </div>
    </div>
</div>

<style>
.loan-progress-hero {
    display: grid;
    grid-template-columns: minmax(0, 1.6fr) minmax(280px, .9fr);
    gap: 1rem;
    padding: 1.2rem;
    border-radius: 12px;
    color: #fff;
    background: linear-gradient(135deg, #1d4ed8, #0f766e);
    overflow: hidden;
}
.loan-progress-copy h2 {
    margin: 0;
    font-size: clamp(1.4rem, 2vw, 2.1rem);
}
.loan-progress-copy p {
    max-width: 680px;
    color: rgba(255, 255, 255, .82);
}
.loan-plan-strip {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: .75rem;
    margin-top: 1rem;
}
.loan-plan-strip div,
.loan-progress-visual {
    border: 1px solid rgba(255, 255, 255, .18);
    background: rgba(255, 255, 255, .1);
    border-radius: 8px;
    padding: .8rem;
}
.loan-plan-strip span {
    display: block;
    color: rgba(255, 255, 255, .72);
    font-size: .78rem;
}
.loan-plan-strip strong {
    display: block;
    margin-top: .18rem;
}
.loan-progress-visual {
    display: grid;
    align-items: center;
    justify-items: center;
    gap: 1rem;
}
.loan-progress-ring {
    width: 150px;
    aspect-ratio: 1;
    border-radius: 50%;
    display: grid;
    place-items: center;
    background: conic-gradient(#facc15 var(--progress), rgba(255, 255, 255, .22) 0);
}
.loan-progress-ring > div {
    width: 108px;
    aspect-ratio: 1;
    border-radius: 50%;
    display: grid;
    place-items: center;
    align-content: center;
    background: #fff;
    color: #1e3a8a;
}
.loan-progress-ring strong {
    font-size: 1.6rem;
}
.loan-progress-ring span {
    font-size: .78rem;
    color: #64748b;
}
.loan-progress-bar {
    width: 100%;
}
.loan-progress-bar .progress {
    height: 12px;
    background: rgba(255, 255, 255, .22);
}
.loan-progress-bar .progress-bar {
    background: #facc15;
}
.loan-progress-visual .text-muted {
    color: rgba(255, 255, 255, .78) !important;
}
.loan-metric-card {
    min-height: 96px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 1rem;
    background: #fff;
    box-shadow: 0 .5rem 1rem rgba(15, 23, 42, .04);
}
.loan-metric-card span,
.loan-metric-card small {
    display: block;
    color: #64748b;
    font-size: .82rem;
}
.loan-metric-card strong {
    display: block;
    margin-top: .35rem;
    font-size: 1.15rem;
}
.loan-breakdown-card .card-body {
    padding: 1.15rem;
}
.loan-breakdown-head {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: .75rem;
}
.loan-breakdown-head span:first-child {
    display: block;
    color: #64748b;
    font-size: .78rem;
    font-weight: 700;
    text-transform: uppercase;
}
.loan-breakdown-head h2 {
    margin: .18rem 0 0;
    color: #0f172a;
    font-size: 1.1rem;
}
.loan-balance-focus {
    margin-top: 1rem;
    padding: .95rem;
    border-radius: 8px;
    color: #fff;
    background: linear-gradient(135deg, #0f172a, #14532d);
}
.loan-balance-focus span,
.loan-balance-focus small {
    display: block;
    color: rgba(255, 255, 255, .76);
    font-size: .8rem;
}
.loan-balance-focus strong {
    display: block;
    margin: .25rem 0;
    font-size: 1.45rem;
}
.loan-breakdown-stack {
    display: flex;
    height: 14px;
    margin-top: 1rem;
    overflow: hidden;
    border-radius: 999px;
    background: #e2e8f0;
}
.loan-breakdown-principal {
    background: #0d6efd;
}
.loan-breakdown-interest {
    background: #ffc107;
}
.loan-breakdown-fee {
    background: #198754;
}
.loan-breakdown-legend {
    display: flex;
    flex-wrap: wrap;
    gap: .65rem;
    margin-top: .55rem;
    color: #64748b;
    font-size: .78rem;
}
.loan-breakdown-legend span {
    display: inline-flex;
    align-items: center;
    gap: .3rem;
}
.loan-amount-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: .55rem;
    margin-top: 1rem;
}
.loan-amount-grid div {
    min-width: 0;
    padding: .72rem;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    background: #f8fafc;
}
.loan-amount-grid span,
.loan-amount-grid small {
    display: block;
    color: #64748b;
    font-size: .76rem;
}
.loan-amount-grid strong {
    display: block;
    margin-top: .2rem;
    color: #0f172a;
    font-size: .95rem;
    overflow-wrap: anywhere;
}
.loan-info-section {
    margin-top: 1rem;
    padding-top: 1rem;
    border-top: 1px solid #e2e8f0;
}
.loan-info-section h3 {
    margin: 0 0 .65rem;
    color: #334155;
    font-size: .82rem;
    font-weight: 800;
    text-transform: uppercase;
}
.loan-info-row {
    display: flex;
    justify-content: space-between;
    gap: .75rem;
    padding: .45rem 0;
    color: #475569;
    border-bottom: 1px dashed #e2e8f0;
    font-size: .86rem;
}
.loan-info-row:last-child {
    border-bottom: 0;
}
.loan-info-row strong {
    color: #0f172a;
    text-align: right;
    overflow-wrap: anywhere;
}
.loan-breakdown-actions {
    display: flex;
    flex-wrap: wrap;
    gap: .5rem;
    margin-top: 1rem;
    padding-top: 1rem;
    border-top: 1px solid #e2e8f0;
}
.loan-breakdown-actions .btn {
    min-height: 34px;
}
.reschedule-summary {
    display: grid;
    grid-template-columns: minmax(180px, .6fr) minmax(0, 1.4fr);
    gap: 1rem;
    padding: .9rem;
    border: 1px solid #bfdbfe;
    border-radius: 8px;
    background: #eff6ff;
}
.reschedule-summary span {
    display: block;
    color: #475569;
    font-size: .8rem;
}
.reschedule-summary strong {
    display: block;
    color: #1d4ed8;
    font-size: 1.2rem;
}
.reschedule-summary p {
    color: #475569;
}
.repayment-schedule-card .schedule-action-btn {
    min-width: 96px;
}
.repayment-schedule-card .schedule-search {
    max-width: 320px;
}
.schedule-version-tabs {
    gap: .5rem;
}
.schedule-version-tabs .nav-link {
    border: 1px solid #dbeafe;
    color: #1d4ed8;
}
.schedule-version-tabs .nav-link.active {
    color: #fff;
    background: #1d4ed8;
}
.archived-schedule-stack {
    display: grid;
    gap: 1rem;
    padding: 1rem;
    background: #f8fafc;
}
.archived-schedule-version {
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    background: #fff;
    overflow: hidden;
}
.archived-schedule-heading {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    align-items: center;
    padding: 1rem;
    border-bottom: 1px solid #e2e8f0;
}
.archived-note {
    margin: .75rem 1rem 0;
    padding: .75rem;
    border-radius: 8px;
    color: #475569;
    background: #fff7ed;
    border: 1px solid #fed7aa;
}
.repayment-schedule-table th {
    background: #f8fafc;
    color: #343a40;
    font-weight: 700;
    white-space: nowrap;
}
.repayment-schedule-table td {
    vertical-align: middle;
    white-space: nowrap;
}
@media (max-width: 991.98px) {
    .loan-progress-hero {
        grid-template-columns: 1fr;
    }
    .loan-plan-strip {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }
    .reschedule-summary {
        grid-template-columns: 1fr;
    }
}
@media (max-width: 575.98px) {
    .loan-plan-strip {
        grid-template-columns: 1fr;
    }
}
@media print {
    body * {
        visibility: hidden;
    }
    .repayment-schedule-card, .repayment-schedule-card * {
        visibility: visible;
    }
    .repayment-schedule-card {
        position: absolute;
        inset: 0 auto auto 0;
        width: 100%;
        box-shadow: none !important;
    }
    .schedule-action-btn, .schedule-search, .repayment-schedule-card label {
        display: none !important;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const table = document.querySelector('[data-repayment-table]');
    const search = document.querySelector('[data-schedule-search]');
    const copyButton = document.querySelector('[data-schedule-copy]');
    const excelButton = document.querySelector('[data-schedule-excel]');
    const pdfButton = document.querySelector('[data-schedule-pdf]');
    const printButton = document.querySelector('[data-schedule-print]');

    if (!table) return;

    const visibleRows = () => Array.from(table.querySelectorAll('tbody tr'))
        .filter((row) => row.style.display !== 'none');

    const tableMatrix = () => {
        const headers = Array.from(table.querySelectorAll('thead th')).map((cell) => cell.innerText.trim());
        const rows = visibleRows().map((row) => Array.from(row.children).map((cell) => cell.innerText.trim()));

        return [headers, ...rows];
    };

    search?.addEventListener('input', () => {
        const term = search.value.trim().toLowerCase();

        table.querySelectorAll('tbody tr').forEach((row) => {
            row.style.display = !term || row.dataset.searchable.includes(term) ? '' : 'none';
        });
    });

    copyButton?.addEventListener('click', async () => {
        const text = tableMatrix().map((row) => row.join('\t')).join('\n');

        try {
            await navigator.clipboard.writeText(text);
            copyButton.textContent = 'Copied';
            setTimeout(() => copyButton.textContent = 'Copy', 1200);
        } catch (error) {
            const area = document.createElement('textarea');
            area.value = text;
            document.body.appendChild(area);
            area.select();
            document.execCommand('copy');
            area.remove();
        }
    });

    excelButton?.addEventListener('click', () => {
        const csv = tableMatrix()
            .map((row) => row.map((cell) => `"${cell.replaceAll('"', '""')}"`).join(','))
            .join('\n');
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `${table.dataset.exportName || 'repayment-schedule'}.csv`;
        link.click();
        URL.revokeObjectURL(link.href);
    });

    pdfButton?.addEventListener('click', () => window.print());
    printButton?.addEventListener('click', () => window.print());
});
</script>
@endsection
