

<?php $__env->startSection('title', 'Loans'); ?>
<?php $__env->startSection('page-title', 'Loans'); ?>
<?php $__env->startSection('page-subtitle', 'Applications, approvals, disbursements, repayments, and products'); ?>

<?php $__env->startSection('content'); ?>
<?php
    $currency = auth()->user()->tenant->settings['currency'] ?? 'NGN';
    $compactNumber = function ($amount) {
        $amount = (float) $amount;
        $absolute = abs($amount);
        $format = fn ($value, $suffix) => rtrim(rtrim(number_format($value, 1), '0'), '.').$suffix;

        if ($absolute >= 1000000000) {
            return $format($amount / 1000000000, 'b');
        }

        if ($absolute >= 1000000) {
            return $format($amount / 1000000, 'm');
        }

        if ($absolute >= 1000) {
            return $format($amount / 1000, 'k');
        }

        return number_format($amount, 2);
    };
    $money = fn ($amount) => $currency.' '.number_format((float) $amount, 2);
    $compactMoney = fn ($amount) => $currency.' '.$compactNumber($amount);
    $compactCount = fn ($amount) => abs((float) $amount) >= 1000 ? $compactNumber($amount) : number_format((float) $amount, 0);
    $repaymentStatusLabel = fn ($status) => match ($status) {
        'paid' => 'Paid',
        'partial' => 'Partial',
        'overdue' => 'Overdue',
        default => ucfirst(str_replace('_', ' ', (string) $status)),
    };
    $repaymentStatusClass = fn ($status) => match ($status) {
        'paid' => 'status-completed',
        'partial' => 'status-approved',
        'overdue' => 'status-rejected',
        default => 'status-pending',
    };
    $loanMetricCards = [
        ['Repayments today', $compactMoney($loanStats['today_repayments'] ?? 0), 'Collected today', 'bi-arrow-repeat', 'blue'],
        ['Active loans', $compactCount($loanStats['active'] ?? 0), 'Currently running', 'bi-activity', 'green'],
        ['Portfolio balance', $compactMoney($loanStats['portfolio'] ?? 0), 'Outstanding principal and charges', 'bi-cash-coin', 'teal'],
        ['Due / overdue', $compactCount($loanStats['due_or_overdue'] ?? 0), 'Needs collection attention', 'bi-exclamation-triangle', 'amber'],
    ];
    $productPayload = $products->map(fn ($product) => [
        'id' => $product->id,
        'name' => $product->name,
        'description' => $product->description,
        'loan_number_prefix' => $product->loan_number_prefix ?? '',
        'interest_rate' => $product->interest_rate,
        'interest_method' => $product->interest_method,
        'repayment_frequency' => $product->repayment_frequency,
        'term_value' => $product->term_value ?: max(1, (int) ceil(((int) $product->term_days ?: 30) / 30)),
        'term_unit' => match ($product->repayment_frequency) {
            'daily' => 'days',
            'weekly', 'biweekly' => 'weeks',
            'yearly' => 'years',
            default => 'months',
        },
        'penalty_type' => $product->penalty_type ?? 'percentage',
        'penalty_rate' => $product->penalty_rate,
        'processing_fee_type' => $product->processing_fee_type ?? 'fixed',
        'processing_fee_value' => $product->processing_fee_value ?? 0,
        'processing_fee_timing' => $product->processing_fee_timing ?? 'before_disbursement',
        'processing_fee_timing_label' => $product->processingFeeTimingLabel(),
        'minimum_amount' => $product->minimum_amount,
        'maximum_amount' => $product->maximum_amount,
        'guarantor_requirement' => $product->guarantor_requirement ?? 'optional',
        'collateral_requirement' => $product->collateral_requirement ?? 'optional',
        'show_on_member_portal' => $product->show_on_member_portal ? '1' : '0',
        'show_on_public_website' => $product->show_on_public_website ? '1' : '0',
        'is_active' => $product->is_active ? '1' : '0',
        'update_route' => route('tenant.loan-products.update', $product),
        'delete_route' => route('tenant.loan-products.destroy', $product),
    ])->values();
?>

<section class="finance-hero finance-hero-loans mb-4">
    <div class="finance-hero-copy">
        <span>Loan center</span>
        <h2>Manage applications, products, approvals, and collections.</h2>
        <p>Track loan performance, find due accounts quickly, and keep product pricing rules visible for staff and member self-service.</p>
    </div>
    <div class="finance-metric-grid">
        <?php $__currentLoopData = $loanMetricCards; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as [$label, $value, $hint, $icon, $tone]): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <div class="finance-metric-card <?php echo e($tone); ?>">
                <i class="bi <?php echo e($icon); ?>"></i>
                <span><?php echo e($label); ?></span>
                <strong><?php echo e($value); ?></strong>
                <small><?php echo e($hint); ?></small>
            </div>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
    </div>
</section>

<div class="card border-0 shadow-sm finance-workspace loan-tab-workspace">
    <div class="finance-tabbar">
        <ul class="nav nav-pills finance-tabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#loan-register-pane" type="button" role="tab" aria-controls="loan-register-pane" aria-selected="true">
                    <i class="bi bi-journal-text me-1"></i> Loan register
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" data-bs-toggle="tab" data-bs-target="#upcoming-repayments-pane" type="button" role="tab" aria-controls="upcoming-repayments-pane" aria-selected="false">
                    <i class="bi bi-calendar2-week me-1"></i> Upcoming repayment
                    <?php if(($loanStats['upcoming_repayments'] ?? 0) > 0): ?>
                        <span class="badge text-bg-info ms-1"><?php echo e($compactCount($loanStats['upcoming_repayments'])); ?></span>
                    <?php endif; ?>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" data-bs-toggle="tab" data-bs-target="#missed-repayments-pane" type="button" role="tab" aria-controls="missed-repayments-pane" aria-selected="false">
                    <i class="bi bi-calendar-x me-1"></i> Missed repayment
                    <?php if(($loanStats['missed_repayments'] ?? 0) > 0): ?>
                        <span class="badge text-bg-danger ms-1"><?php echo e($compactCount($loanStats['missed_repayments'])); ?></span>
                    <?php endif; ?>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" data-bs-toggle="tab" data-bs-target="#loan-products-pane" type="button" role="tab" aria-controls="loan-products-pane" aria-selected="false">
                    <i class="bi bi-sliders me-1"></i> Loan products
                </button>
            </li>
        </ul>
    </div>

    <div class="tab-content">
        <div class="tab-pane fade show active" id="loan-register-pane" role="tabpanel" tabindex="0">
            <div class="card-body">
                <div class="finance-pane-title p-0 mb-3">
                    <div>
                        <span>Register</span>
                        <h3>Loan register</h3>
                        <p>Search by member, loan number, phone, product, status, or due state.</p>
                    </div>
                    <?php if(auth()->user()->hasPermission('loans.create')): ?>
                        <a href="<?php echo e(route('tenant.loans.create')); ?>" class="btn btn-primary align-self-start"><i class="bi bi-plus-lg me-1"></i> New loan</a>
                    <?php endif; ?>
                </div>
                <form method="GET" class="row g-2 align-items-end finance-filter-panel" data-auto-loan-filter>
                    <div class="col-lg-4">
                        <label class="form-label">Search loans</label>
                        <input name="q" value="<?php echo e($search); ?>" class="form-control" placeholder="Loan no, member, account no, phone..." data-loan-search autocomplete="off">
                    </div>
                    <div class="col-sm-6 col-lg-2">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select" data-loan-select>
                        <option value="">All loans</option>
                        <?php $__currentLoopData = ['applied','approved','active','completed','rejected','defaulted']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $loanStatus): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option <?php if($status === $loanStatus): echo 'selected'; endif; ?> value="<?php echo e($loanStatus); ?>"><?php echo e(ucfirst($loanStatus)); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                    <div class="col-sm-6 col-lg-2">
                        <label class="form-label">Product</label>
                        <select name="product_id" class="form-select" data-loan-select>
                            <option value="">All products</option>
                            <?php $__currentLoopData = $products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($product->id); ?>" <?php if((string) $productId === (string) $product->id): echo 'selected'; endif; ?>><?php echo e($product->name); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                    <div class="col-sm-6 col-lg-2">
                        <label class="form-label">Due state</label>
                        <select name="due_state" class="form-select" data-loan-select>
                            <option value="">Any due state</option>
                            <option value="due_today" <?php if($dueState === 'due_today'): echo 'selected'; endif; ?>>Due today</option>
                            <option value="overdue" <?php if($dueState === 'overdue'): echo 'selected'; endif; ?>>Overdue</option>
                            <option value="due_or_overdue" <?php if($dueState === 'due_or_overdue'): echo 'selected'; endif; ?>>Due / overdue</option>
                        </select>
                    </div>
                    <div class="col-sm-6 col-lg-2">
                        <?php if($search !== '' || $status || $productId || $dueState): ?>
                            <a href="<?php echo e(route('tenant.loans.index')); ?>" class="btn btn-outline-secondary w-100">Clear</a>
                        <?php else: ?>
                            <div class="small text-muted">Filters apply automatically.</div>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
            <div class="table-responsive finance-table-shell">
                <table class="table mb-0 align-middle finance-table">
                    <thead>
                        <tr>
                            <th>Loan</th>
                            <th>Member</th>
                            <th>Status</th>
                            <th>Principal</th>
                            <th>Balance</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $__currentLoopData = $loans; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $loan): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <tr>
                                <td><span class="finance-id-pill"><?php echo e($loan->loan_number); ?></span></td>
                                <td><div class="fw-semibold"><?php echo e($loan->customer?->fullName()); ?></div><small class="text-muted"><?php echo e($loan->customer?->account_number); ?></small></td>
                                <td><span class="finance-soft-badge status-<?php echo e($loan->status); ?>"><?php echo e(ucfirst(str_replace('_', ' ', $loan->status))); ?></span></td>
                                <td><?php echo e($money($loan->principal)); ?></td>
                                <td class="fw-semibold"><?php echo e($money($loan->balance)); ?></td>
                                <td><a class="btn btn-sm btn-outline-primary" href="<?php echo e(route('tenant.loans.show', $loan)); ?>">Open</a></td>
                            </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        <?php if($loans->isEmpty()): ?>
                            <tr><td colspan="6" class="text-center text-muted py-4">No loans found.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <div class="card-body"><?php echo e($loans->links()); ?></div>
        </div>

        <div class="tab-pane fade" id="upcoming-repayments-pane" role="tabpanel" tabindex="0">
            <div class="card-body">
                <div class="finance-pane-title p-0 mb-3">
                    <div>
                        <span>Collection watch</span>
                        <h3>Upcoming repayments</h3>
                        <p>Unpaid repayment schedules due from today through the next 30 days.</p>
                    </div>
                    <div class="loan-pane-count info">
                        <strong><?php echo e($compactCount($loanStats['upcoming_repayments'] ?? 0)); ?></strong>
                        <span><?php echo e($compactMoney($loanStats['upcoming_repayment_amount'] ?? 0)); ?></span>
                    </div>
                </div>
            </div>

            <?php if($upcomingRepayments->isNotEmpty()): ?>
                <div class="table-responsive finance-table-shell">
                    <table class="table mb-0 align-middle finance-table">
                        <thead>
                            <tr>
                                <th>Due date</th>
                                <th>Loan</th>
                                <th>Member</th>
                                <th>Installment</th>
                                <th class="text-end">Amount due</th>
                                <th class="text-end">Paid</th>
                                <th class="text-end">Outstanding</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $__currentLoopData = $upcomingRepayments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $schedule): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <tr>
                                    <td>
                                        <div class="fw-semibold"><?php echo e(app_date($schedule->due_date)); ?></div>
                                        <small class="text-muted"><?php echo e((int) ($schedule->days_left ?? 0) === 0 ? 'Due today' : (int) ($schedule->days_left ?? 0).' day'.((int) ($schedule->days_left ?? 0) === 1 ? '' : 's').' left'); ?></small>
                                    </td>
                                    <td>
                                        <span class="finance-id-pill"><?php echo e($schedule->loan?->loan_number); ?></span>
                                        <div class="small text-muted mt-1"><?php echo e($schedule->loan?->product?->name ?? 'Loan'); ?></div>
                                    </td>
                                    <td>
                                        <div class="fw-semibold"><?php echo e($schedule->loan?->customer?->fullName()); ?></div>
                                        <small class="text-muted"><?php echo e($schedule->loan?->customer?->account_number); ?></small>
                                    </td>
                                    <td><span class="finance-soft-badge <?php echo e($repaymentStatusClass($schedule->status)); ?>">#<?php echo e($schedule->installment_no); ?> - <?php echo e($repaymentStatusLabel($schedule->status)); ?></span></td>
                                    <td class="text-end"><?php echo e($compactMoney($schedule->total_due)); ?></td>
                                    <td class="text-end text-success"><?php echo e($compactMoney($schedule->paid_amount)); ?></td>
                                    <td class="text-end fw-semibold"><?php echo e($compactMoney($schedule->outstanding_amount ?? 0)); ?></td>
                                    <td class="text-end">
                                        <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="modal" data-bs-target="#upcomingRepayment<?php echo e($schedule->id); ?>">View</button>
                                    </td>
                                </tr>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </tbody>
                    </table>
                </div>

                <?php $__currentLoopData = $upcomingRepayments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $schedule): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <div class="modal fade" id="upcomingRepayment<?php echo e($schedule->id); ?>" tabindex="-1" aria-labelledby="upcomingRepayment<?php echo e($schedule->id); ?>Label" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered modal-lg">
                            <div class="modal-content border-0 shadow">
                                <div class="modal-header">
                                    <div>
                                        <h2 class="modal-title h5" id="upcomingRepayment<?php echo e($schedule->id); ?>Label">Upcoming repayment details</h2>
                                        <div class="text-muted small"><?php echo e($schedule->loan?->loan_number); ?> - installment #<?php echo e($schedule->installment_no); ?></div>
                                    </div>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <div class="row g-3">
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Member</span><strong><?php echo e($schedule->loan?->customer?->fullName()); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Member account</span><strong><?php echo e($schedule->loan?->customer?->account_number ?? '-'); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Loan number</span><strong><?php echo e($schedule->loan?->loan_number ?? '-'); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Due date</span><strong><?php echo e(app_date($schedule->due_date) ?? '-'); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Status</span><strong><?php echo e($repaymentStatusLabel($schedule->status)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Outstanding</span><strong><?php echo e($money($schedule->outstanding_amount ?? 0)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Total due</span><strong><?php echo e($money($schedule->total_due)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Paid amount</span><strong><?php echo e($money($schedule->paid_amount)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Loan balance</span><strong><?php echo e($money($schedule->loan?->balance ?? 0)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Principal</span><strong><?php echo e($money($schedule->principal_due)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Interest</span><strong><?php echo e($money($schedule->interest_due)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Penalty</span><strong><?php echo e($money($schedule->penalty_due)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Initiated by</span><strong><?php echo e($schedule->loan?->creator?->name ?? 'System / member'); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Approved by</span><strong><?php echo e($schedule->loan?->approver?->name ?? 'Not approved yet'); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Disbursed by</span><strong><?php echo e($schedule->loan?->disburser?->name ?? ($schedule->loan?->disbursed_at ? 'Unknown user' : 'Not disbursed yet')); ?></strong></div></div>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Close</button>
                                    <a class="btn btn-primary btn-sm" href="<?php echo e(route('tenant.loans.show', $schedule->loan)); ?>">Open loan</a>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            <?php else: ?>
                <div class="loan-empty-state">
                    <i class="bi bi-calendar2-check"></i>
                    <strong>No upcoming repayments</strong>
                    <span>Repayments due within the next 30 days will appear here.</span>
                </div>
            <?php endif; ?>
        </div>

        <div class="tab-pane fade" id="missed-repayments-pane" role="tabpanel" tabindex="0">
            <div class="card-body">
                <div class="finance-pane-title p-0 mb-3">
                    <div>
                        <span>Overdue collection</span>
                        <h3>Missed repayments</h3>
                        <p>Past due repayment schedules that are still unpaid or partially paid.</p>
                    </div>
                    <div class="loan-pane-count danger">
                        <strong><?php echo e($compactCount($loanStats['missed_repayments'] ?? 0)); ?></strong>
                        <span><?php echo e($compactMoney($loanStats['missed_repayment_amount'] ?? 0)); ?></span>
                    </div>
                </div>
            </div>

            <?php if($missedRepayments->isNotEmpty()): ?>
                <div class="table-responsive finance-table-shell">
                    <table class="table mb-0 align-middle finance-table">
                        <thead>
                            <tr>
                                <th>Due date</th>
                                <th>Loan</th>
                                <th>Member</th>
                                <th>Days late</th>
                                <th class="text-end">Amount due</th>
                                <th class="text-end">Paid</th>
                                <th class="text-end">Outstanding</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $__currentLoopData = $missedRepayments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $schedule): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <tr>
                                    <td>
                                        <div class="fw-semibold"><?php echo e(app_date($schedule->due_date)); ?></div>
                                        <small class="text-danger"><?php echo e((int) ($schedule->days_late ?? 1)); ?> day<?php echo e((int) ($schedule->days_late ?? 1) === 1 ? '' : 's'); ?> late</small>
                                    </td>
                                    <td>
                                        <span class="finance-id-pill"><?php echo e($schedule->loan?->loan_number); ?></span>
                                        <div class="small text-muted mt-1"><?php echo e($schedule->loan?->product?->name ?? 'Loan'); ?></div>
                                    </td>
                                    <td>
                                        <div class="fw-semibold"><?php echo e($schedule->loan?->customer?->fullName()); ?></div>
                                        <small class="text-muted"><?php echo e($schedule->loan?->customer?->account_number); ?></small>
                                    </td>
                                    <td><span class="finance-soft-badge status-rejected"><?php echo e((int) ($schedule->days_late ?? 1)); ?></span></td>
                                    <td class="text-end"><?php echo e($compactMoney($schedule->total_due)); ?></td>
                                    <td class="text-end text-success"><?php echo e($compactMoney($schedule->paid_amount)); ?></td>
                                    <td class="text-end fw-semibold text-danger"><?php echo e($compactMoney($schedule->outstanding_amount ?? 0)); ?></td>
                                    <td class="text-end">
                                        <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="modal" data-bs-target="#missedRepayment<?php echo e($schedule->id); ?>">View</button>
                                    </td>
                                </tr>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </tbody>
                    </table>
                </div>

                <?php $__currentLoopData = $missedRepayments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $schedule): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <div class="modal fade" id="missedRepayment<?php echo e($schedule->id); ?>" tabindex="-1" aria-labelledby="missedRepayment<?php echo e($schedule->id); ?>Label" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered modal-lg">
                            <div class="modal-content border-0 shadow">
                                <div class="modal-header">
                                    <div>
                                        <h2 class="modal-title h5" id="missedRepayment<?php echo e($schedule->id); ?>Label">Missed repayment details</h2>
                                        <div class="text-muted small"><?php echo e($schedule->loan?->loan_number); ?> - installment #<?php echo e($schedule->installment_no); ?></div>
                                    </div>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <div class="row g-3">
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Member</span><strong><?php echo e($schedule->loan?->customer?->fullName()); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Member account</span><strong><?php echo e($schedule->loan?->customer?->account_number ?? '-'); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Loan number</span><strong><?php echo e($schedule->loan?->loan_number ?? '-'); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Due date</span><strong><?php echo e(app_date($schedule->due_date) ?? '-'); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Days late</span><strong><?php echo e((int) ($schedule->days_late ?? 1)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Outstanding</span><strong><?php echo e($money($schedule->outstanding_amount ?? 0)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Total due</span><strong><?php echo e($money($schedule->total_due)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Paid amount</span><strong><?php echo e($money($schedule->paid_amount)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Loan balance</span><strong><?php echo e($money($schedule->loan?->balance ?? 0)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Principal</span><strong><?php echo e($money($schedule->principal_due)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Interest</span><strong><?php echo e($money($schedule->interest_due)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Penalty</span><strong><?php echo e($money($schedule->penalty_due)); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Initiated by</span><strong><?php echo e($schedule->loan?->creator?->name ?? 'System / member'); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Approved by</span><strong><?php echo e($schedule->loan?->approver?->name ?? 'Not approved yet'); ?></strong></div></div>
                                        <div class="col-md-4"><div class="repayment-detail-tile"><span>Disbursed by</span><strong><?php echo e($schedule->loan?->disburser?->name ?? ($schedule->loan?->disbursed_at ? 'Unknown user' : 'Not disbursed yet')); ?></strong></div></div>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Close</button>
                                    <a class="btn btn-primary btn-sm" href="<?php echo e(route('tenant.loans.show', $schedule->loan)); ?>">Open loan</a>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            <?php else: ?>
                <div class="loan-empty-state">
                    <i class="bi bi-check2-circle"></i>
                    <strong>No missed repayments</strong>
                    <span>Past due unpaid repayment schedules will appear here automatically.</span>
                </div>
            <?php endif; ?>
        </div>

        <div class="tab-pane fade" id="loan-products-pane" role="tabpanel" tabindex="0">
            <div class="row g-4 p-3 p-lg-4 loan-products-tab-grid">
        <?php if(auth()->user()->hasPermission('loan_products.manage')): ?>
                <div class="col-xl-7">
            <div class="card border-0 shadow-sm loan-product-card finance-editor-card">
                <div class="card-body">
                    <div class="loan-product-hero d-flex justify-content-between gap-2 align-items-start mb-3">
                        <div>
                            <div class="small text-primary fw-bold text-uppercase">Product setup</div>
                            <h2 class="h5 mb-1">Loan Products</h2>
                            <div class="text-muted small">Pick a product, edit pricing, then manage rules from one compact screen.</div>
                        </div>
                        <button class="btn btn-sm btn-dark" type="button" data-product-new><i class="bi bi-plus-lg"></i></button>
                    </div>

                    <label class="form-label">Loan product to manage</label>
                    <select class="form-select mb-3" data-product-selector>
                        <option value="">Create new product</option>
                        <?php $__currentLoopData = $products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($product->id); ?>"><?php echo e($product->name); ?> <?php echo e($product->is_active ? '' : '(inactive)'); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>

                    <form method="POST" action="<?php echo e(route('tenant.loan-products.store')); ?>" class="vstack gap-3" data-product-form>
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="_method" value="PATCH" data-product-method disabled>

                        <div class="loan-product-section finance-product-section">
                            <div class="loan-product-section-title"><i class="bi bi-pencil-square"></i><span>Basics</span></div>
                            <label class="form-label">Product name</label>
                            <input name="name" class="form-control" placeholder="e.g. Market trader loan" required>

                            <div class="row g-2 mt-1">
                                <div class="col-6">
                                    <label class="form-label">Loan ID prefix</label>
                                    <input name="loan_number_prefix" class="form-control" maxlength="20">
                                </div>
                                <div class="col-6">
                                    <label class="form-label">Status</label>
                                    <select name="is_active" class="form-select">
                                        <option value="1">Active</option>
                                        <option value="0">Inactive</option>
                                    </select>
                                </div>
                            </div>

                            <label class="form-label mt-2">Description</label>
                            <textarea name="description" class="form-control" rows="2" placeholder="Short description"></textarea>
                        </div>

                        <div class="loan-product-section finance-product-section">
                            <div class="loan-product-section-title"><i class="bi bi-percent"></i><span>Pricing</span></div>
                            <div class="row g-2">
                                <div class="col-6">
                                    <label class="form-label">Interest rate (%)</label>
                                    <input name="interest_rate" type="number" step="0.01" min="0" class="form-control" required>
                                </div>
                                <div class="col-6">
                                    <label class="form-label">Interest type</label>
                                    <select name="interest_method" class="form-select">
                                        <?php $__currentLoopData = $interestMethods; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($value); ?>"><?php echo e($label); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                            </div>

                            <div class="row g-2 mt-1">
                                <div class="col-6">
                                    <label class="form-label">Period</label>
                                    <select name="repayment_frequency" class="form-select">
                                        <?php $__currentLoopData = $repaymentFrequencies; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($value); ?>"><?php echo e($label); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                                <div class="col-6">
                                    <label class="form-label">Term (payments)</label>
                                    <input name="term_value" type="number" min="1" class="form-control" value="1" required>
                                </div>
                                <input type="hidden" name="term_unit" value="months">
                            </div>

                            <div class="row g-2 mt-1">
                                <div class="col-6">
                                    <label class="form-label">Penalty type</label>
                                    <select name="penalty_type" class="form-select">
                                        <?php $__currentLoopData = $amountTypes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($value); ?>"><?php echo e($label); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                                <div class="col-6">
                                    <label class="form-label">Penalty value</label>
                                    <input name="penalty_rate" type="number" step="0.01" min="0" class="form-control" value="0" required>
                                </div>
                            </div>

                            <div class="row g-2 mt-1">
                                <div class="col-6">
                                    <label class="form-label">Fee type</label>
                                    <select name="processing_fee_type" class="form-select">
                                        <?php $__currentLoopData = $amountTypes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($value); ?>"><?php echo e($label); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                                <div class="col-6">
                                    <label class="form-label">Processing fee</label>
                                    <input name="processing_fee_value" type="number" step="0.01" min="0" class="form-control" value="0" required>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">When to deduct fee</label>
                                    <select name="processing_fee_timing" class="form-select">
                                        <?php $__currentLoopData = $processingFeeTimings; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($value); ?>"><?php echo e($label); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                    <div class="form-text">Choose whether the fee is collected before disbursement or deducted from the amount paid out to the member.</div>
                                </div>
                            </div>
                        </div>

                        <div class="loan-product-section finance-product-section">
                            <div class="loan-product-section-title"><i class="bi bi-shield-check"></i><span>Limits and rules</span></div>
                            <div class="row g-2">
                                <div class="col-6">
                                    <label class="form-label">Min Amount</label>
                                    <input name="minimum_amount" type="number" step="0.01" min="0" class="form-control" value="0" required>
                                </div>
                                <div class="col-6">
                                    <label class="form-label">Max Amount</label>
                                    <input name="maximum_amount" type="number" step="0.01" min="0" class="form-control" value="0" required>
                                </div>
                            </div>

                            <div class="row g-2 mt-1">
                                <div class="col-6">
                                    <label class="form-label">Guarantor</label>
                                    <select name="guarantor_requirement" class="form-select">
                                        <?php $__currentLoopData = $requirementOptions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($value); ?>"><?php echo e($label); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                                <div class="col-6">
                                    <label class="form-label">Collateral</label>
                                    <select name="collateral_requirement" class="form-select">
                                        <?php $__currentLoopData = $requirementOptions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($value); ?>"><?php echo e($label); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="loan-product-section finance-product-section">
                            <div class="loan-product-section-title"><i class="bi bi-eye"></i><span>Visibility</span></div>
                            <div class="row g-2">
                                <div class="col-6">
                                    <label class="form-label">Member portal</label>
                                    <select name="show_on_member_portal" class="form-select">
                                        <option value="1">Show</option>
                                        <option value="0">Hide</option>
                                    </select>
                                </div>
                                <div class="col-6">
                                    <label class="form-label">Tenant website</label>
                                    <select name="show_on_public_website" class="form-select">
                                        <option value="1">Show</option>
                                        <option value="0">Hide</option>
                                    </select>
                                </div>
                            </div>
                            <div class="small text-muted mt-2">Hidden products remain available to staff, but members and website visitors will not see them.</div>
                        </div>

                        <div class="d-flex flex-wrap gap-2">
                            <button class="btn btn-primary flex-grow-1" data-product-submit>Save product</button>
                            <button class="btn btn-outline-danger" type="submit" form="deleteLoanProductForm" data-product-delete disabled>Delete / disable</button>
                        </div>
                    </form>

                    <form method="POST" id="deleteLoanProductForm" data-product-delete-form>
                        <?php echo csrf_field(); ?>
                        <?php echo method_field('DELETE'); ?>
                    </form>
                </div>
            </div>
                </div>
        <?php endif; ?>

                <div class="<?php echo e(auth()->user()->hasPermission('loan_products.manage') ? 'col-xl-5' : 'col-12'); ?>">
        <div class="card border-0 shadow-sm product-summary-card finance-workspace h-100">
            <div class="finance-card-title"><span>Products</span><h3>Product summary</h3></div>
            <div class="list-group list-group-flush product-summary-list finance-list">
                <?php $__currentLoopData = $products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <div class="list-group-item">
                        <div class="d-flex justify-content-between gap-2">
                            <div class="fw-semibold"><?php echo e($product->name); ?></div>
                            <span class="badge <?php echo e($product->is_active ? 'text-bg-success' : 'text-bg-secondary'); ?>"><?php echo e($product->is_active ? 'Active' : 'Inactive'); ?></span>
                        </div>
                        <small class="text-muted">
                            <?php echo e($product->interest_method === 'custom' ? 'Custom interest' : $product->interest_rate.'%'); ?> | <?php echo e($repaymentFrequencies[$product->repayment_frequency] ?? ucfirst($product->repayment_frequency)); ?> | <?php echo e($product->term_value ?: $product->term_days); ?> <?php echo e($product->term_unit ?: 'days'); ?>

                        </small>
                        <div class="small text-muted mt-1">Fee timing: <strong><?php echo e($product->processingFeeTimingLabel()); ?></strong></div>
                        <div class="d-flex flex-wrap gap-1 mt-2">
                            <span class="badge <?php echo e($product->show_on_member_portal ? 'text-bg-info' : 'text-bg-light text-dark'); ?>">Member <?php echo e($product->show_on_member_portal ? 'visible' : 'hidden'); ?></span>
                            <span class="badge <?php echo e($product->show_on_public_website ? 'text-bg-primary' : 'text-bg-light text-dark'); ?>">Website <?php echo e($product->show_on_public_website ? 'visible' : 'hidden'); ?></span>
                        </div>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                <?php if($products->isEmpty()): ?>
                    <div class="list-group-item text-muted small">No loan products yet.</div>
                <?php endif; ?>
            </div>
        </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('[data-auto-loan-filter]').forEach((filterForm) => {
        const search = filterForm.querySelector('[data-loan-search]');
        const selects = filterForm.querySelectorAll('[data-loan-select]');
        let timer = null;
        const submit = () => filterForm.requestSubmit ? filterForm.requestSubmit() : filterForm.submit();

        search?.addEventListener('input', () => {
            clearTimeout(timer);
            timer = setTimeout(submit, 650);
        });

        selects.forEach((select) => select.addEventListener('change', submit));
    });

    const products = <?php echo json_encode($productPayload, 15, 512) ?>;
    const byId = new Map(products.map((product) => [String(product.id), product]));
    const selector = document.querySelector('[data-product-selector]');
    const form = document.querySelector('[data-product-form]');
    const methodInput = document.querySelector('[data-product-method]');
    const newButton = document.querySelector('[data-product-new]');
    const submitButton = document.querySelector('[data-product-submit]');
    const deleteButton = document.querySelector('[data-product-delete]');
    const deleteForm = document.querySelector('[data-product-delete-form]');
    const storeRoute = <?php echo json_encode(route('tenant.loan-products.store'), 15, 512) ?>;

    const setField = (name, value) => {
        const field = form?.querySelector(`[name="${name}"]`);
        if (field) field.value = value ?? '';
    };

    const resetForm = () => {
        if (!form) return;
        form.reset();
        form.action = storeRoute;
        methodInput.disabled = true;
        submitButton.textContent = 'Save product';
        deleteButton.disabled = true;
        deleteForm.removeAttribute('action');
        setField('loan_number_prefix', '');
        setField('term_value', '1');
        setField('term_unit', 'months');
        setField('penalty_rate', '0');
        setField('processing_fee_value', '0');
        setField('processing_fee_timing', 'before_disbursement');
        setField('minimum_amount', '0');
        setField('maximum_amount', '0');
        setField('show_on_member_portal', '1');
        setField('show_on_public_website', '1');
        setField('is_active', '1');
    };

    const loadProduct = (id) => {
        const product = byId.get(String(id));

        if (!product) {
            resetForm();
            return;
        }

        form.action = product.update_route;
        methodInput.disabled = false;
        submitButton.textContent = 'Update product';
        deleteButton.disabled = false;
        deleteForm.action = product.delete_route;

        Object.entries(product).forEach(([name, value]) => setField(name, value));
    };

    selector?.addEventListener('change', (event) => loadProduct(event.target.value));
    newButton?.addEventListener('click', () => {
        if (selector) selector.value = '';
        resetForm();
    });

    resetForm();
});
</script>

<style>
.loan-product-card {
    overflow: hidden;
}
.loan-product-hero {
    margin: -1rem -1rem 1rem;
    padding: 1rem;
    background: linear-gradient(135deg, #f8fafc, #e9fbf6);
    border-bottom: 1px solid #e2e8f0;
}
.loan-product-section {
    padding: .95rem;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    background: #fff;
}
.loan-product-section-title {
    display: flex;
    align-items: center;
    gap: .45rem;
    margin-bottom: .75rem;
    color: #0f766e;
    font-weight: 800;
}
.loan-product-section .form-label {
    margin-bottom: .25rem;
    font-size: .82rem;
    color: #475569;
}
.loan-product-section .form-control,
.loan-product-section .form-select {
    min-height: 38px;
}
.product-summary-list .list-group-item {
    border-left: 0;
    border-right: 0;
}
.loan-pane-count {
    display: grid;
    place-items: center;
    min-width: 104px;
    padding: .55rem .85rem;
    border: 1px solid #bae6fd;
    border-radius: 8px;
    background: #f0f9ff;
}
.loan-pane-count strong {
    color: #0369a1;
    font-size: 1.25rem;
    line-height: 1;
}
.loan-pane-count span {
    margin-top: .2rem;
    color: #0369a1;
    font-size: .72rem;
    font-weight: 900;
    text-transform: uppercase;
}
.loan-pane-count.danger {
    border-color: #fecaca;
    background: #fef2f2;
}
.loan-pane-count.danger strong,
.loan-pane-count.danger span {
    color: #b91c1c;
}
.repayment-detail-tile {
    height: 100%;
    padding: .8rem;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    background: #f8fafc;
}
.repayment-detail-tile span {
    display: block;
    margin-bottom: .25rem;
    color: #64748b;
    font-size: .76rem;
    font-weight: 800;
    text-transform: uppercase;
}
.repayment-detail-tile strong {
    display: block;
    color: #172033;
    font-size: .92rem;
    font-weight: 800;
    overflow-wrap: anywhere;
}
.loan-empty-state {
    display: grid;
    place-items: center;
    gap: .45rem;
    min-height: 230px;
    margin: 1rem;
    padding: 2rem;
    border: 1px dashed #cbd5e1;
    border-radius: 8px;
    background: #f8fafc;
    text-align: center;
}
.loan-empty-state i {
    display: grid;
    place-items: center;
    width: 52px;
    height: 52px;
    border-radius: 8px;
    background: #e0f2fe;
    color: #0369a1;
    font-size: 1.55rem;
}
.loan-empty-state strong {
    color: #172033;
    font-size: 1.05rem;
}
.loan-empty-state span {
    max-width: 420px;
    color: #64748b;
    font-weight: 700;
}
</style>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\Polite hp\Documents\Codex\2026-05-08\build-a-complete-production-ready-saas\microfinance-saas\resources\views\tenant\loans\index.blade.php ENDPATH**/ ?>