<?php $__env->startSection('title', 'Loan Details - ' . $loan->user->full_name); ?>

<?php $__env->startSection('content_header'); ?>
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h1 class="mb-0">Loan Details</h1>
            <p class="text-muted mb-0">Application #<?php echo e($loan->id); ?> - <?php echo e($loan->user->full_name); ?></p>
        </div>
        <div class="d-flex align-items-center">
            <a href="<?php echo e(route('loans.edit', $loan)); ?>" class="btn btn-outline-warning btn-sm mr-2" title="Edit Loan">
                <i class="fas fa-edit"></i>
            </a>
            <a href="<?php echo e(route('loans.download.details', $loan)); ?>" class="btn btn-outline-primary btn-sm mr-2" title="Download PDF">
                <i class="fas fa-download"></i>
            </a>
            <button onclick="window.print()" class="btn btn-outline-info btn-sm mr-2" title="Print Details">
                <i class="fas fa-print"></i>
            </button>
            <a href="<?php echo e(route('loans.index')); ?>" class="btn btn-secondary btn-sm" title="Back to Loans">
                <i class="fas fa-arrow-left"></i>
            </a>
        </div>
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid">
    <!-- Minimal Status Indicator -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="minimal-status d-flex align-items-center justify-content-between py-2 px-3">
                <div class="d-flex align-items-center">
                    <i class="fas <?php echo e($loan->status === 'approved' ? 'fa-check-circle text-success' : ($loan->status === 'pending' ? 'fa-clock text-warning' : ($loan->status === 'rejected' ? 'fa-times-circle text-danger' : ($loan->status === 'active' ? 'fa-play-circle text-info' : ($loan->status === 'defaulted' ? 'fa-exclamation-triangle text-danger' : 'fa-pause-circle text-secondary'))))); ?> mr-2"></i>
                    <span class="font-weight-medium"><?php echo e(ucfirst($loan->status)); ?></span>
                    <?php if($loan->approved_at): ?>
                        <small class="text-muted ml-2"><?php echo e($loan->approved_at->format('M j, Y')); ?></small>
                    <?php else: ?>
                        <small class="text-muted ml-2"><?php echo e($loan->created_at->format('M j, Y')); ?></small>
                    <?php endif; ?>
                </div>
                <small class="text-muted">#<?php echo e($loan->id); ?></small>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- Main Content -->
        <div class="col-lg-8 col-md-7">
            <!-- Member Information Card -->
            <div class="card shadow-sm mb-4">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="fas fa-user text-primary mr-2"></i>Member Information
                    </h5>
                </div>
                <div class="card-body py-3">
                    <div class="row align-items-center">
                        <div class="col-lg-2 col-md-3 col-sm-4 text-center">
                            <div class="avatar-initial rounded-circle bg-gradient-primary text-white mx-auto mb-2 shadow-sm" style="width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; font-size: 24px; font-weight: bold;">
                                <?php echo e(strtoupper(substr($loan->user->first_name, 0, 1))); ?><?php echo e(strtoupper(substr($loan->user->second_name, 0, 1))); ?>

                            </div>
                            <small class="text-muted d-block">ID: <?php echo e($loan->user->membership->membership_number ?? 'N/A'); ?></small>
                        </div>
                        <div class="col-lg-7 col-md-6 col-sm-8">
                            <h6 class="mb-2 font-weight-bold"><?php echo e($loan->user->full_name); ?></h6>
                            <div class="row">
                                <div class="col-sm-6">
                                    <small class="text-muted d-block">
                                        <i class="fas fa-phone text-success mr-1"></i><?php echo e($loan->user->phone_number); ?>

                                    </small>
                                    <small class="text-muted d-block">
                                        <i class="fas fa-envelope text-info mr-1"></i><?php echo e($loan->user->email); ?>

                                    </small>
                                </div>
                                <div class="col-sm-6">
                                    <small class="text-muted d-block">
                                        <i class="fas fa-id-card text-primary mr-1"></i><?php echo e($loan->user->id_number); ?>

                                    </small>
                                    <small class="text-muted d-block">
                                        <i class="fas fa-building text-warning mr-1"></i><?php echo e($loan->user->branch->name ?? 'N/A'); ?>

                                    </small>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-3 text-center text-md-right mt-2 mt-md-0">
                            <div class="mb-1">
                                <small class="text-muted d-block">Application Date</small>
                                <span class="font-weight-medium"><?php echo e($loan->created_at->format('d M Y')); ?></span>
                            </div>
                            <span class="badge badge-<?php echo e($loan->status === 'approved' ? 'success' : ($loan->status === 'pending' ? 'warning' : ($loan->status === 'rejected' ? 'danger' : ($loan->status === 'active' ? 'info' : ($loan->status === 'defaulted' ? 'danger' : 'secondary'))))); ?> px-2 py-1">
                                <?php echo e(ucfirst($loan->status)); ?>

                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Loan Financial Summary -->
            <div class="card shadow-sm mb-4">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="fas fa-chart-line text-primary mr-2"></i>Loan Financial Summary
                    </h5>
                </div>
                <div class="card-body py-3">
                    <?php
                        $interestAmount = $loan->total_amount - $loan->amount;
                        $principalPercentage = $loan->total_amount > 0 ? ($loan->amount / $loan->total_amount) * 100 : 0;
                        $interestPercentage = $loan->total_amount > 0 ? ($interestAmount / $loan->total_amount) * 100 : 0;
                        $progressPercentage = $loan->total_amount > 0 ? (($loan->total_amount - $loan->balance) / $loan->total_amount) * 100 : 0;
                        $daysRemaining = $loan->status !== 'paid' && $loan->approved_at ? max(0, $loan->approved_at->copy()->addMonths($loan->term_months)->diffInDays(now())) : 0;
                        $nextPaymentDate = $loan->approved_at ? $loan->approved_at->copy()->addMonths(ceil($loan->approved_at->diffInMonths(now(), false))) : null;
                    ?>

                    <!-- Primary Metrics Row -->
                    <div class="row text-center mb-3">
                        <div class="col-lg-3 col-md-6 col-sm-6 col-12 mb-3">
                            <div class="stat-widget-compact">
                                <div class="widget-icon-compact">
                                    <i class="fas fa-coins text-primary"></i>
                                </div>
                                <div class="widget-content-compact">
                                    <div class="widget-value-compact text-primary"><?php echo e(number_format($loan->amount, 0)); ?></div>
                                    <div class="widget-label-compact">Principal</div>
                                    <div class="widget-subtext-compact"><?php echo e(number_format($principalPercentage, 1)); ?>%</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6 col-sm-6 col-12 mb-3">
                            <div class="stat-widget-compact">
                                <div class="widget-icon-compact">
                                    <i class="fas fa-percentage text-warning"></i>
                                </div>
                                <div class="widget-content-compact">
                                    <div class="widget-value-compact text-warning"><?php echo e($loan->interest_rate); ?>%</div>
                                    <div class="widget-label-compact">Rate</div>
                                    <div class="widget-subtext-compact">Annual</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6 col-sm-6 col-12 mb-3">
                            <div class="stat-widget-compact">
                                <div class="widget-icon-compact">
                                    <i class="fas fa-calendar-alt text-info"></i>
                                </div>
                                <div class="widget-content-compact">
                                    <div class="widget-value-compact text-info"><?php echo e($loan->term_months); ?></div>
                                    <div class="widget-label-compact">Term</div>
                                    <div class="widget-subtext-compact">Months</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-6 col-sm-6 col-12 mb-3">
                            <div class="stat-widget-compact">
                                <div class="widget-icon-compact">
                                    <i class="fas fa-chart-pie text-danger"></i>
                                </div>
                                <div class="widget-content-compact">
                                    <div class="widget-value-compact text-danger"><?php echo e(number_format($interestAmount, 0)); ?></div>
                                    <div class="widget-label-compact">Interest</div>
                                    <div class="widget-subtext-compact"><?php echo e(number_format($interestPercentage, 1)); ?>%</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Financial Summary Row -->
                    <div class="row text-center mb-3">
                        <div class="col-lg-4 col-md-4 col-12 mb-3">
                            <div class="summary-widget-compact">
                                <div class="summary-header-compact">
                                    <i class="fas fa-calculator text-primary mr-1"></i>
                                    <span class="summary-title-compact">Total Amount</span>
                                </div>
                                <div class="summary-value-compact text-primary"><?php echo e(number_format($loan->total_amount, 0)); ?></div>
                                <div class="summary-breakdown-compact">
                                    <small class="text-muted">Principal: <?php echo e(number_format($principalPercentage, 1)); ?>% | Interest: <?php echo e(number_format($interestPercentage, 1)); ?>%</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-4 col-md-4 col-12 mb-3">
                            <div class="summary-widget-compact">
                                <div class="summary-header-compact">
                                    <i class="fas fa-money-bill-wave text-info mr-1"></i>
                                    <span class="summary-title-compact">Monthly Payment</span>
                                </div>
                                <div class="summary-value-compact text-info"><?php echo e(number_format($loan->monthly_payment, 0)); ?></div>
                                <div class="summary-breakdown-compact">
                                    <small class="text-muted">Next: <?php echo e($nextPaymentDate ? $nextPaymentDate->format('M j') : 'N/A'); ?></small>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-4 col-md-4 col-12 mb-3">
                            <div class="summary-widget-compact">
                                <div class="summary-header-compact">
                                    <i class="fas fa-balance-scale text-secondary mr-1"></i>
                                    <span class="summary-title-compact">Outstanding</span>
                                </div>
                                <div class="summary-value-compact text-secondary"><?php echo e(number_format($loan->balance, 0)); ?></div>
                                <div class="summary-breakdown-compact">
                                    <small class="text-muted">Progress: <?php echo e(number_format($progressPercentage, 1)); ?>% | Days: <?php echo e($daysRemaining); ?></small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Enhanced Repayment Progress -->
                    <?php if($loan->status !== 'paid'): ?>
                    <div class="progress-container-modern">
                        <div class="progress-header">
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="progress-title">
                                    <i class="fas fa-chart-line text-success mr-2"></i>
                                    <span>Repayment Progress</span>
                                </div>
                                <div class="progress-percentage">
                                    <span class="badge badge-success badge-sm"><?php echo e(number_format($progressPercentage, 1)); ?>%</span>
                                </div>
                            </div>
                        </div>
                        <div class="progress-modern">
                            <div class="progress-bar-modern bg-success" style="width: <?php echo e($progressPercentage); ?>%"
                                 title="Paid: <?php echo e(number_format($loan->paid_amount, 0)); ?> | Remaining: <?php echo e(number_format($loan->balance, 0)); ?>"></div>
                        </div>
                        <div class="progress-details">
                            <div class="detail-item">
                                <i class="fas fa-check-circle text-success mr-1"></i>
                                <span>Paid: <strong><?php echo e(number_format($loan->paid_amount, 0)); ?></strong></span>
                            </div>
                            <div class="detail-item">
                                <i class="fas fa-clock text-warning mr-1"></i>
                                <span>Remaining: <strong><?php echo e(number_format($loan->balance, 0)); ?></strong></span>
                            </div>
                            <div class="detail-item">
                                <i class="fas fa-calendar text-info mr-1"></i>
                                <span>Next Payment: <strong><?php echo e($nextPaymentDate ? $nextPaymentDate->format('M j, Y') : 'N/A'); ?></strong></span>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>


            <!-- Repayment History -->
            <?php if($loan->repayments->count() > 0): ?>
            <div class="card shadow-sm mb-3">
                <div class="card-header py-2">
                    <h6 class="card-title mb-0">
                        <i class="fas fa-history text-primary mr-2"></i>Recent Payments
                    </h6>
                </div>
                <div class="card-body py-2">
                    <div class="table-responsive">
                        <table class="table table-sm mb-0">
                            <thead class="bg-light">
                                <tr>
                                    <th class="py-1">Date</th>
                                    <th class="py-1">Amount</th>
                                    <th class="py-1">Method</th>
                                    <th class="py-1">Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $__currentLoopData = $loan->repayments->sortByDesc('created_at')->take(5); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $repayment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <tr>
                                    <td class="py-1"><?php echo e($repayment->created_at->format('d M')); ?></td>
                                    <td class="py-1 text-success font-weight-bold"><?php echo e(number_format($repayment->amount, 0)); ?></td>
                                    <td class="py-1">
                                        <?php if($repayment->payment_method === 'mpesa_stk'): ?>
                                            <span class="badge badge-primary badge-sm">STK</span>
                                        <?php elseif($repayment->payment_method === 'mpesa_manual'): ?>
                                            <span class="badge badge-info badge-sm">Manual</span>
                                        <?php else: ?>
                                            <span class="badge badge-secondary badge-sm"><?php echo e(ucfirst(substr($repayment->payment_method ?? 'cash', 0, 4))); ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="py-1">
                                        <span class="badge badge-<?php echo e($repayment->status === 'completed' ? 'success' : 'warning'); ?> badge-sm">
                                            <?php echo e($repayment->status === 'completed' ? '✓' : '○'); ?>

                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </tbody>
                        </table>
                        <?php if($loan->repayments->count() > 5): ?>
                        <div class="text-center mt-2">
                            <small class="text-muted">... and <?php echo e($loan->repayments->count() - 5); ?> more payments</small>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Loan Notes -->
            <?php if($loan->notes): ?>
            <div class="card shadow-sm">
                <div class="card-header">
                    <h5 class="card-title mb-0">
                        <i class="fas fa-sticky-note text-primary mr-2"></i>Additional Notes
                    </h5>
                </div>
                <div class="card-body">
                    <div class="bg-light p-3 rounded">
                        <?php echo e($loan->notes); ?>

                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-4 col-md-5">
            <!-- Loan Security/Guarantees -->
            <?php if($loan->guarantees->count() > 0): ?>
            <div class="card shadow-sm mb-4">
                <div class="card-header py-2">
                    <h6 class="card-title mb-0">
                        <i class="fas fa-shield-alt text-primary mr-2"></i>Loan Security & Guarantees
                    </h6>
                </div>
                <div class="card-body py-2">
                    <?php $__currentLoopData = $loan->guarantees; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $guarantee): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <div class="guarantee-item mb-3 pb-3 border-bottom">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <div>
                                <h6 class="mb-1">
                                    <i class="fas fa-<?php echo e($guarantee->guarantee_type === 'salary' ? 'briefcase' : ($guarantee->guarantee_type === 'collateral' ? 'home' : 'users')); ?> mr-2"></i>
                                    <?php echo e($guarantee->type_label); ?>

                                </h6>
                                <span class="badge badge-<?php echo e($guarantee->status_color); ?> badge-sm">
                                    <?php echo e(ucfirst($guarantee->status)); ?>

                                </span>
                            </div>
                            <?php if($guarantee->status === 'pending'): ?>
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-success btn-sm" onclick="approveGuarantee(<?php echo e($guarantee->id); ?>)">
                                    <i class="fas fa-check"></i>
                                </button>
                                <button class="btn btn-danger btn-sm" onclick="rejectGuarantee(<?php echo e($guarantee->id); ?>)">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                            <?php endif; ?>
                        </div>

                        <?php if($guarantee->guarantee_type === 'guarantor'): ?>
                            <?php $__currentLoopData = $guarantee->guarantors; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $guarantor): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <div class="guarantee-summary pl-3 border-left">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <strong class="text-primary"><?php echo e($guarantor->guarantor->full_name); ?></strong>
                                        <br><small class="text-muted">Guarantor</small>
                                    </div>
                                    <div class="text-right">
                                        <div class="font-weight-bold text-success">KSh <?php echo e(number_format($guarantor->guarantee_amount, 0)); ?></div>
                                        <small class="text-muted">Guarantee Amount</small>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        <?php elseif($guarantee->guarantee_type === 'collateral'): ?>
                            <?php $__currentLoopData = $guarantee->collateral; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <div class="guarantee-summary pl-3 border-left">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <strong class="text-primary"><?php echo e($item->item_description); ?></strong>
                                        <br><small class="text-muted"><?php echo e($item->item_type_label); ?></small>
                                    </div>
                                    <div class="text-right">
                                        <div class="font-weight-bold text-success">KSh <?php echo e(number_format($item->estimated_value, 0)); ?></div>
                                        <small class="text-muted">Item Worth</small>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        <?php elseif($guarantee->guarantee_type === 'salary'): ?>
                            <?php if($guarantee->salaryGuarantee): ?>
                            <div class="guarantee-summary pl-3 border-left">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <strong class="text-primary"><?php echo e($guarantee->salaryGuarantee->employer_name); ?></strong>
                                        <br><small class="text-muted">Employer</small>
                                    </div>
                                    <div class="text-right">
                                        <div class="font-weight-bold text-success">KSh <?php echo e(number_format($guarantee->salaryGuarantee->monthly_salary, 0)); ?>/month</div>
                                        <small class="text-muted">Monthly Salary</small>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        <?php endif; ?>

                        <?php if($guarantee->notes): ?>
                        <div class="mt-2">
                            <small class="text-muted"><strong>Notes:</strong> <?php echo e($guarantee->notes); ?></small>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Quick Actions -->
            <div class="card shadow-lg mb-4 border-0">
                <div class="card-header bg-gradient-success text-white py-2">
                    <h6 class="card-title mb-0 font-weight-bold">
                        <i class="fas fa-bolt mr-2"></i>Quick Actions
                    </h6>
                </div>
                <div class="card-body py-3">
                    <?php if($loan->status === 'pending'): ?>
                    <div class="d-flex gap-2 mb-3">
                        <form action="<?php echo e(route('loans.approve', $loan)); ?>" method="POST" class="flex-fill">
                            <?php echo csrf_field(); ?> <?php echo method_field('PATCH'); ?>
                            <button type="submit" class="btn btn-success btn-sm btn-minimal w-100" onclick="return confirm('Approve this loan?')">
                                <i class="fas fa-check mr-1"></i>Approve
                            </button>
                        </form>
                        <form action="<?php echo e(route('loans.reject', $loan)); ?>" method="POST" class="flex-fill">
                            <?php echo csrf_field(); ?> <?php echo method_field('PATCH'); ?>
                            <button type="submit" class="btn btn-danger btn-sm btn-minimal w-100" onclick="return confirm('Reject this loan?')">
                                <i class="fas fa-times mr-1"></i>Reject
                            </button>
                        </form>
                    </div>
                    <?php endif; ?>

                    <?php if(in_array($loan->status, ['approved', 'active'])): ?>
                    <!-- Loan Repayment Section -->
                    <div class="repayment-section-enhanced bg-gradient-success text-white mb-4">
                        <div class="repayment-header text-center mb-3">
                            <i class="fas fa-money-bill-wave fa-2x mb-2"></i>
                            <h6 class="font-weight-bold mb-0">Process Repayment</h6>
                        </div>
                        <form id="repayment-form" method="POST" action="<?php echo e(route('loans.repay', $loan)); ?>">
                            <?php echo csrf_field(); ?>
                            <div class="form-group mb-3">
                                <label class="text-white-50 small font-weight-bold">Repayment Amount (KSh)</label>
                                <input type="number" class="form-control form-control-sm bg-white" id="repayment-amount" name="amount"
                                        placeholder="Enter amount" min="0.01" step="0.01" required>
                                <small class="text-white-75">Outstanding: KSh <?php echo e(number_format($loan->balance, 0)); ?></small>
                            </div>
                            <div class="form-group mb-3">
                                <label class="text-white-50 small font-weight-bold">Payment Method</label>
                                <select class="form-control form-control-sm bg-white" id="payment-method" name="payment_method" required>
                                    <option value="cash">💵 Cash</option>
                                    <option value="bank_transfer">🏦 Bank Transfer</option>
                                    <option value="mpesa_stk">📱 M-Pesa STK Push</option>
                                    <option value="mpesa_manual">📱 M-Pesa Manual</option>
                                </select>
                            </div>
                            <div class="form-group mb-3" id="mpesa-phone-group" style="display: none;">
                                <label class="text-white-50 small font-weight-bold">Phone Number</label>
                                <input type="tel" class="form-control form-control-sm bg-white" id="mpesa-phone" name="mpesa_phone_number"
                                        placeholder="Phone number" value="<?php echo e($loan->user->phone_number); ?>">
                            </div>
                            <div class="form-group mb-3" id="mpesa-code-group" style="display: none;">
                                <label class="text-white-50 small font-weight-bold">Transaction Code</label>
                                <input type="text" class="form-control form-control-sm bg-white" id="mpesa-code" name="mpesa_transaction_id"
                                        placeholder="M-Pesa transaction code">
                            </div>
                            <button type="submit" class="btn btn-light btn-sm btn-block font-weight-bold" id="repay-btn">
                                <i class="fas fa-credit-card mr-2"></i>Process Repayment
                            </button>
                        </form>
                    </div>
                    <?php endif; ?>

                    <div class="d-flex gap-2">
                        <a href="<?php echo e(route('loans.edit', $loan)); ?>" class="btn btn-outline-warning btn-sm btn-minimal flex-fill" title="Edit Loan">
                            <i class="fas fa-edit mr-1"></i>Edit
                        </a>
                        <form action="<?php echo e(route('loans.destroy', $loan)); ?>" method="POST" onsubmit="return confirm('Delete this loan?')" class="flex-fill">
                            <?php echo csrf_field(); ?> <?php echo method_field('DELETE'); ?>
                            <button type="submit" class="btn btn-outline-danger btn-sm btn-minimal w-100" title="Delete Loan">
                                <i class="fas fa-trash mr-1"></i>Delete
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Detailed Payment Schedule -->
            <div class="card shadow-sm">
                <div class="card-header d-flex justify-content-between align-items-center py-2">
                    <h6 class="card-title mb-0">
                        <i class="fas fa-calendar-alt text-primary mr-2"></i>Payment Schedule
                    </h6>
                    <div class="btn-group btn-group-sm">
                        <button onclick="downloadPDF()" class="btn btn-outline-light btn-sm" title="Download PDF">
                            <i class="fas fa-download"></i>
                        </button>
                        <button onclick="printSchedule()" class="btn btn-outline-light btn-sm" title="Print Schedule">
                            <i class="fas fa-print"></i>
                        </button>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-sm mb-0 payment-schedule-table">
                            <thead class="bg-light">
                                <tr>
                                    <th class="text-center" style="width: 6%;">#</th>
                                    <th style="width: 16%;">Due Date</th>
                                    <th style="width: 19%;">Payment</th>
                                    <th style="width: 19%;">Principal</th>
                                    <th style="width: 19%;">Interest</th>
                                    <th style="width: 21%;">Balance</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                    $balance = $loan->amount;
                                    $monthlyPayment = $loan->monthly_payment;
                                    $totalAmount = $loan->total_amount;
                                    $interestAmount = $totalAmount - $loan->amount;
                                    $currentDate = $loan->approved_at ?? $loan->created_at;
                                    $maxRows = min($loan->term_months, 24); // Show up to 24 months for better visibility
                                ?>

                                <?php for($month = 1; $month <= $maxRows; $month++): ?>
                                <?php
                                    $interestPayment = $balance * ($loan->interest_rate / 100) / 12;
                                    $principalPayment = $monthlyPayment - $interestPayment;

                                    if($balance + $interestPayment < $monthlyPayment) {
                                        $monthlyPayment = $balance + $interestPayment;
                                        $principalPayment = $balance;
                                    }

                                    $balance -= $principalPayment;
                                    if($balance < 0.01) $balance = 0;

                                    $dueDate = $currentDate->copy()->addMonths($month - 1);
                                ?>
                                <tr>
                                    <td class="text-center"><?php echo e($month); ?></td>
                                    <td class="text-nowrap"><?php echo e($dueDate->format('M Y')); ?></td>
                                    <td class="text-primary font-weight-medium"><?php echo e(number_format($monthlyPayment, 0)); ?></td>
                                    <td class="text-muted"><?php echo e(number_format($principalPayment, 0)); ?></td>
                                    <td class="text-muted"><?php echo e(number_format($interestPayment, 0)); ?></td>
                                    <td class="<?php echo e($balance == 0 ? 'text-success font-weight-medium' : 'text-danger'); ?>"><?php echo e(number_format($balance, 0)); ?></td>
                                </tr>
                                <?php endfor; ?>

                                <?php if($loan->term_months > $maxRows): ?>
                                <tr>
                                    <td colspan="6" class="text-center text-muted py-2">
                                        <small>... and <?php echo e($loan->term_months - $maxRows); ?> more payments</small>
                                    </td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                            <tfoot class="bg-primary text-white">
                                <tr>
                                    <th colspan="2" class="text-right py-2">TOTALS:</th>
                                    <th class="py-2"><?php echo e(number_format($loan->total_amount, 0)); ?></th>
                                    <th class="py-2"><?php echo e(number_format($loan->amount, 0)); ?></th>
                                    <th class="py-2"><?php echo e(number_format($interestAmount, 0)); ?></th>
                                    <th class="py-2">0.00</th>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
                <div class="card-footer text-center py-2">
                    <small class="text-muted">
                        <i class="fas fa-info-circle mr-1"></i>
                        Showing <?php echo e(min($loan->term_months, $maxRows)); ?> of <?php echo e($loan->term_months); ?> payments
                    </small>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Global font size increase for the entire page */
body {
    font-size: 16px !important;
}

/* Minimal Status Indicator */
.minimal-status {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 6px;
    font-size: 0.875rem;
    transition: all 0.2s ease;
}

.minimal-status:hover {
    background: #ffffff;
    border-color: #dee2e6;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

/* Compact Stat Cards */
.stat-card-compact {
    border-radius: 8px;
    padding: 1rem;
    text-align: center;
    margin-bottom: 0.5rem;
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    transition: all 0.2s ease;
}

.stat-card-compact:hover {
    background: #ffffff;
    border-color: #dee2e6;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.stat-value-compact {
    font-size: 1.1rem;
    font-weight: 600;
    margin-bottom: 0.25rem;
    display: block;
}

.stat-label-compact {
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    font-weight: 500;
}

/* Compact Summary Cards */
.summary-card-compact {
    border-radius: 8px;
    padding: 1.25rem;
    text-align: center;
    margin-bottom: 0.5rem;
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    transition: all 0.2s ease;
}

.summary-card-compact:hover {
    background: #ffffff;
    border-color: #dee2e6;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.summary-value-compact {
    font-size: 1.3rem;
    font-weight: 600;
    margin-bottom: 0.25rem;
    display: block;
}

.summary-label-compact {
    font-size: 0.8rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    font-weight: 500;
}

/* Compact Statistics Widgets */
.stat-widget-compact {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    border: 1px solid #e9ecef;
    border-radius: 10px;
    padding: 1rem 0.75rem;
    text-align: center;
    transition: all 0.3s ease;
    box-shadow: 0 2px 6px rgba(0,0,0,0.06);
    position: relative;
    overflow: hidden;
    height: 100%;
}

.stat-widget-compact::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, #007bff 0%, #0056b3 100%);
}

.stat-widget-compact:hover {
    transform: translateY(-1px);
    box-shadow: 0 3px 12px rgba(0,0,0,0.1);
    border-color: #dee2e6;
}

.widget-icon-compact {
    font-size: 1.5rem;
    margin-bottom: 0.5rem;
    opacity: 0.8;
}

.widget-content-compact {
    position: relative;
    z-index: 1;
}

.widget-value-compact {
    font-size: 1.2rem;
    font-weight: 700;
    margin-bottom: 0.15rem;
    display: block;
}

.widget-label-compact {
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 0.15rem;
    color: #495057;
}

.widget-subtext-compact {
    font-size: 0.65rem;
    color: #6c757d;
    font-weight: 500;
}

/* Compact Summary Widgets */
.summary-widget-compact {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    border: 1px solid #e9ecef;
    border-radius: 10px;
    padding: 1rem;
    text-align: center;
    transition: all 0.3s ease;
    box-shadow: 0 2px 6px rgba(0,0,0,0.06);
    position: relative;
    overflow: hidden;
    height: 100%;
}

.summary-widget-compact::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, #28a745 0%, #20c997 100%);
}

.summary-widget-compact:hover {
    transform: translateY(-1px);
    box-shadow: 0 3px 12px rgba(0,0,0,0.1);
    border-color: #dee2e6;
}

.summary-header-compact {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 0.5rem;
    font-size: 0.8rem;
    font-weight: 600;
    color: #495057;
}

.summary-title-compact {
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.summary-value-compact {
    font-size: 1.4rem;
    font-weight: 700;
    margin-bottom: 0.5rem;
    display: block;
}

.summary-breakdown-compact {
    font-size: 0.7rem;
    color: #6c757d;
}

/* Advanced Metric Widgets */
.metric-widget-advanced {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    border: 1px solid #e9ecef;
    border-radius: 12px;
    padding: 1.5rem 1rem;
    text-align: center;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    position: relative;
    overflow: hidden;
}

.metric-widget-advanced::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, #dc3545 0%, #bd2130 100%);
}

.metric-widget-advanced:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0,0,0,0.12);
    border-color: #dee2e6;
}

.metric-icon {
    font-size: 1.8rem;
    margin-bottom: 0.5rem;
    opacity: 0.8;
}

.metric-content {
    position: relative;
    z-index: 1;
}

.metric-value {
    font-size: 1.4rem;
    font-weight: 700;
    margin-bottom: 0.25rem;
    display: block;
}

.metric-label {
    font-size: 0.8rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 0.5rem;
    color: #495057;
}

.metric-progress {
    margin-top: 0.5rem;
}

.progress-mini {
    height: 4px;
    background-color: #e9ecef;
    border-radius: 2px;
    margin-bottom: 0.25rem;
    overflow: hidden;
}

.progress-bar-mini {
    height: 100%;
    border-radius: 2px;
    transition: width 0.3s ease;
}

/* Enhanced Repayment Section */
.repayment-section-enhanced {
    border-radius: 15px;
    padding: 2rem;
    background: linear-gradient(135deg, rgba(40, 167, 69, 0.5) 0%, rgba(32, 201, 151, 0.5) 100%);
    border: none;
    position: relative;
    overflow: hidden;
}

.repayment-section-enhanced::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 100%);
    pointer-events: none;
}

.repayment-header {
    position: relative;
    z-index: 1;
}

/* Gradient Backgrounds */
.bg-gradient-primary { background: linear-gradient(135deg, #007bff 0%, #0056b3 100%); }
.bg-gradient-warning { background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%); }
.bg-gradient-info { background: linear-gradient(135deg, #17a2b8 0%, #138496 100%); }
.bg-gradient-danger { background: linear-gradient(135deg, #dc3545 0%, #bd2130 100%); }
.bg-gradient-success { background: linear-gradient(135deg, #28a745 0%, #20c997 100%); }
.bg-gradient-secondary { background: linear-gradient(135deg, #6c757d 0%, #545b62 100%); }

.progress-container {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 0.75rem;
    margin-top: 0.5rem;
}

/* Modern Progress Container */
.progress-container-modern {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    border: 1px solid #e9ecef;
    border-radius: 12px;
    padding: 1.5rem;
    margin-top: 1rem;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    position: relative;
    overflow: hidden;
    font-size: 16px;
}

.progress-container-modern::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, #28a745 0%, #20c997 100%);
}

.progress-header {
    margin-bottom: 1rem;
}

.progress-title {
    font-weight: 600;
    color: #495057;
    font-size: 0.9rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.progress-percentage .badge {
    font-size: 0.75rem;
    padding: 0.25rem 0.5rem;
}

.progress-modern {
    height: 10px;
    background-color: #e9ecef;
    border-radius: 5px;
    margin-bottom: 1rem;
    overflow: hidden;
    box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
}

.progress-bar-modern {
    height: 100%;
    border-radius: 5px;
    background: linear-gradient(90deg, #28a745 0%, #20c997 100%);
    transition: width 0.4s ease;
    position: relative;
}

.progress-bar-modern::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(90deg, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 100%);
    border-radius: 5px;
}

.progress-details {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 1rem;
}

.detail-item {
    display: flex;
    align-items: center;
    font-size: 0.8rem;
    color: #6c757d;
}

.detail-item i {
    font-size: 0.7rem;
}

.detail-item strong {
    color: #495057;
    margin-left: 0.25rem;
}

.repayment-section {
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 0.75rem;
    background: #f8f9fa;
}

/* Enhanced card styling */
.card {
    border: none;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    margin-bottom: 1rem;
}

.card-header {
    background: transparent;
    border-bottom: 1px solid #f0f0f0;
    padding: 0.75rem 1rem;
    border-radius: 8px 8px 0 0 !important;
}

.card-body {
    padding: 1rem;
}

.card-footer {
    background: transparent;
    border-top: 1px solid #f0f0f0;
    padding: 0.5rem 1rem;
}

/* Progress bar styling */
.progress {
    border-radius: 4px;
    background-color: #e9ecef;
    height: 6px;
}

.progress-bar {
    background: linear-gradient(90deg, #28a745 0%, #20c997 100%);
    border-radius: 4px;
}

/* Badge styling */
.badge {
    font-weight: 500;
    border-radius: 12px;
    font-size: 0.7rem;
}

.badge-sm {
    font-size: 0.65rem;
    padding: 0.2rem 0.4rem;
}

/* Button styling */
.btn {
    border-radius: 6px;
    font-weight: 500;
    font-size: 0.85rem;
}

.btn-sm {
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
}

/* Minimal button styling */
.btn-minimal {
    padding: 0.375rem 0.5rem;
    font-size: 0.75rem;
    border-radius: 4px;
    min-height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 500;
    transition: all 0.2s ease;
}

.btn-minimal:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.15);
}

.btn-minimal i {
    font-size: 0.8rem;
}

/* Avatar styling */
.avatar-initial {
    font-family: 'Arial', sans-serif;
    border: 2px solid #fff;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* Responsive adjustments */
@media (max-width: 992px) {
    .container-fluid {
        padding-left: 15px;
        padding-right: 15px;
    }

    .stat-card, .summary-card {
        margin-bottom: 0.25rem;
        padding: 0.5rem;
    }

    .stat-value, .summary-value {
        font-size: 1rem;
    }

    .stat-label, .summary-label {
        font-size: 0.7rem;
    }
}

@media (max-width: 768px) {
    .card-body {
        padding: 0.75rem;
    }

    .card-header {
        padding: 0.5rem 0.75rem;
    }

    .stat-card, .summary-card {
        padding: 0.5rem;
        margin-bottom: 0.25rem;
    }

    .progress-container {
        padding: 0.5rem;
    }

    .repayment-section {
        padding: 0.5rem;
    }

    /* Stack columns vertically on mobile */
    .row.align-items-center > [class*="col-"] {
        margin-bottom: 0.5rem;
    }

    .row.align-items-center > [class*="col-"]:last-child {
        margin-bottom: 0;
    }
}

@media (max-width: 576px) {
    .container-fluid {
        padding-left: 10px;
        padding-right: 10px;
    }

    .card {
        margin-bottom: 0.75rem;
    }

    /* Make sidebar full width on very small screens */
    .col-lg-4.col-md-5 {
        flex: 0 0 100%;
        max-width: 100%;
        margin-top: 1rem;
    }

    .col-lg-8.col-md-7 {
        flex: 0 0 100%;
        max-width: 100%;
    }
}

/* Payment schedule table styling */
.payment-schedule-table {
    font-size: 0.75rem;
    margin-bottom: 0;
}

.payment-schedule-table th,
.payment-schedule-table td {
    padding: 0.5rem 0.25rem;
    vertical-align: middle;
    white-space: nowrap;
}

.payment-schedule-table th {
    font-weight: 600;
    font-size: 0.7rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border-bottom: 2px solid #dee2e6;
}

.payment-schedule-table tbody tr:nth-child(even) {
    background-color: #f8f9fa;
}

.payment-schedule-table tbody tr:hover {
    background-color: #e9ecef;
}

.payment-schedule-table tfoot th,
.payment-schedule-table tfoot td {
    border-top: 2px solid #495057;
    font-weight: 600;
}

/* Responsive payment schedule */
@media (max-width: 768px) {
    .payment-schedule-table {
        font-size: 0.7rem;
    }

    .payment-schedule-table th,
    .payment-schedule-table td {
        padding: 0.25rem;
    }

    .payment-schedule-table th:nth-child(4),
    .payment-schedule-table td:nth-child(4),
    .payment-schedule-table th:nth-child(5),
    .payment-schedule-table td:nth-child(5) {
        display: none;
    }
}

@media (max-width: 576px) {
    .payment-schedule-table th:not(:first-child):not(:nth-child(2)):not(:nth-child(3)):not(:last-child),
    .payment-schedule-table td:not(:first-child):not(:nth-child(2)):not(:nth-child(3)):not(:last-child) {
        display: none;
    }

    .payment-schedule-table th {
        font-size: 0.65rem;
    }
}

/* Guarantee approval/rejection visual feedback */
.guarantee-approved {
    background-color: rgba(40, 167, 69, 0.1) !important;
    border-left: 4px solid #28a745 !important;
    transition: all 0.3s ease;
}

.guarantee-rejected {
    background-color: rgba(220, 53, 69, 0.1) !important;
    border-left: 4px solid #dc3545 !important;
    transition: all 0.3s ease;
}

/* Print styles */
@media print {
    .card-header, .card-footer, .btn, .alert, .collapse {
        display: none !important;
    }
    .card {
        border: 1px solid #ddd !important;
        box-shadow: none !important;
        break-inside: avoid;
    }
    .card-body {
        padding: 1rem !important;
    }
    body {
        background: white !important;
    }
}
</style>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<script>
function downloadPDF() {
    window.location.href = '<?php echo e(route("loans.download.schedule", $loan)); ?>';
}

function printSchedule() {
    var printContent = document.getElementById('payment-schedule').innerHTML;
    var originalContent = document.body.innerHTML;

    document.body.innerHTML = `
        <div style="padding: 20px; font-family: Arial, sans-serif;">
            <h2 style="text-align: center; color: #247f1b; margin-bottom: 20px;">Morio Sacco - Loan Payment Schedule</h2>
            <div style="margin-bottom: 20px;">
                <strong>Loan Application #$<?php echo e($loan->id); ?></strong><br>
                <strong>Member:</strong> <?php echo e($loan->user->full_name); ?><br>
                <strong>Principal Amount:</strong> KSh <?php echo e(number_format($loan->amount, 2)); ?><br>
                <strong>Interest Rate:</strong> <?php echo e($loan->interest_rate); ?>%<br>
                <strong>Term:</strong> <?php echo e($loan->term_months); ?> months<br>
                <strong>Total Amount:</strong> KSh <?php echo e(number_format($loan->total_amount, 2)); ?><br>
                <strong>Monthly Payment:</strong> KSh <?php echo e(number_format($loan->monthly_payment, 2)); ?>

            </div>
            ${printContent}
            <div style="margin-top: 30px; text-align: center; font-size: 12px; color: #666;">
                <hr style="border: none; border-top: 1px solid #ddd; margin-bottom: 10px;">
                Generated on ${new Date().toLocaleDateString()} | Morio Sacco Management System
            </div>
        </div>
    `;

    window.print();
    document.body.innerHTML = originalContent;
}

// Repayment form handling and UI interactions
$(document).ready(function() {
    // Handle payment method change
    $('#payment-method').on('change', function() {
        const method = $(this).val();
        const mpesaPhoneGroup = $('#mpesa-phone-group');
        const mpesaCodeGroup = $('#mpesa-code-group');

        if (method === 'mpesa_stk') {
            mpesaPhoneGroup.show();
            mpesaCodeGroup.hide();
            $('#mpesa-code').val('');
        } else if (method === 'mpesa_manual') {
            mpesaPhoneGroup.hide();
            mpesaCodeGroup.show();
            $('#mpesa-phone').val('');
        } else {
            mpesaPhoneGroup.hide();
            mpesaCodeGroup.hide();
            $('#mpesa-phone').val('');
            $('#mpesa-code').val('');
        }

        // Update button text based on payment method
        const repayBtn = $('#repay-btn');
        if (method === 'mpesa_stk') {
            repayBtn.html('<i class="fas fa-mobile-alt mr-1"></i>STK Push');
        } else {
            repayBtn.html('<i class="fas fa-credit-card mr-1"></i>Repay');
        }
    });


    $('#repayment-form').on('submit', function(e) {
        e.preventDefault(); // Prevent default form submission

        const paymentMethod = $('#payment-method').val();
        const formData = new FormData(this);
        const repayBtn = $('#repay-btn');
        const originalText = repayBtn.html();

        // Disable button and show loading
        repayBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i>Processing...');

        let url;
        if (paymentMethod === 'mpesa_stk') {
            url = '<?php echo e(route("loans.repay.mpesa", $loan)); ?>';
        } else {
            url = '<?php echo e(route("loans.repay", $loan)); ?>';
        }

        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') || $('input[name="_token"]').val()
            },
            success: function(response) {
                if (response.success) {
                    toastr.success(response.message || 'Repayment processed successfully');

                    // Update loan data in the UI
                    if (response.loan) {
                        updateLoanData(response.loan);
                    }

                    // Reset form
                    $('#repayment-form')[0].reset();
                    $('#mpesa-phone-group').hide();
                    $('#mpesa-code-group').hide();

                    // Reset button text
                    repayBtn.html('<i class="fas fa-credit-card mr-1"></i>Process Repayment');

                    // For M-Pesa STK, show additional message
                    if (paymentMethod === 'mpesa_stk') {
                        toastr.info('M-Pesa STK Push initiated. Please check your phone and complete the payment.');
                    }
                }
            },
            error: function(xhr, status, error) {
                let errorMsg = 'An error occurred while processing the repayment.';

                if (xhr.responseJSON) {
                    if (xhr.responseJSON.error) {
                        errorMsg = xhr.responseJSON.error;
                    } else if (xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    }
                } else if (xhr.status === 419) {
                    errorMsg = 'Session expired. Please refresh the page and try again.';
                } else if (xhr.status === 422) {
                    errorMsg = 'Validation error. Please check your input.';
                } else if (xhr.status === 500) {
                    errorMsg = 'Server error. Please try again later.';
                }

                console.error('Repayment error:', xhr.responseText);
                toastr.error(errorMsg);
                repayBtn.prop('disabled', false).html(originalText);
            },
            complete: function() {
                // Re-enable button
                repayBtn.prop('disabled', false);
            }
        });
    });
});

function updateLoanData(loan) {
    // Update the outstanding balance in the repayment section
    $('small:contains("Outstanding:")').text('Outstanding: KSh ' + parseFloat(loan.balance).toLocaleString('en-KE', {minimumFractionDigits: 0}));
    // Don't set default value for repayment amount - let user enter custom amount

    // Update the outstanding balance card in financial summary
    $('.summary-value-compact:contains("Outstanding")').next().text('KSh ' + parseFloat(loan.balance).toLocaleString('en-KE', {minimumFractionDigits: 0}));

    // Update progress bar and percentage
    var progress = loan.total_amount > 0 ? ((loan.total_amount - loan.balance) / loan.total_amount) * 100 : 0;
    $('.progress-percentage .badge').text(progress.toFixed(1) + '%');
    $('.progress-bar-modern').css('width', progress + '%');

    // Update progress details
    $('.detail-item:contains("Paid:") strong').text('KSh ' + parseFloat(loan.paid_amount).toLocaleString('en-KE', {minimumFractionDigits: 0}));
    $('.detail-item:contains("Remaining:") strong').text('KSh ' + parseFloat(loan.balance).toLocaleString('en-KE', {minimumFractionDigits: 0}));

    // Update status if changed
    if (loan.status === 'paid') {
        $('.minimal-status .font-weight-medium').text('Paid');
        $('.minimal-status i').removeClass().addClass('fas fa-check-circle text-success');
        $('.badge:contains("Active")').removeClass('badge-info').addClass('badge-success').text('Paid');
    }

    // Add new repayment to history if it exists
    if (loan.latest_repayment) {
        var historyTable = $('.table-responsive tbody');
        if (historyTable.length) {
            var paymentMethodBadge = '';
            if (loan.latest_repayment.payment_method === 'mpesa_stk') {
                paymentMethodBadge = '<span class="badge badge-primary badge-sm">STK</span>';
            } else if (loan.latest_repayment.payment_method === 'mpesa_manual') {
                paymentMethodBadge = '<span class="badge badge-info badge-sm">Manual</span>';
            } else if (loan.latest_repayment.payment_method === 'bank_transfer') {
                paymentMethodBadge = '<span class="badge badge-secondary badge-sm">Bank</span>';
            } else {
                paymentMethodBadge = '<span class="badge badge-light badge-sm">Cash</span>';
            }

            var transactionInfo = loan.latest_repayment.mpesa_transaction_id || loan.latest_repayment.reference_number || 'N/A';

            var newRow = '<tr>' +
                '<td class="py-1">' + new Date().toLocaleDateString('en-GB', {day: '2-digit', month: 'short'}) + '</td>' +
                '<td class="py-1 text-success font-weight-bold">KSh ' + parseFloat(loan.latest_repayment.amount).toLocaleString('en-KE', {minimumFractionDigits: 0}) + '</td>' +
                '<td class="py-1">' + paymentMethodBadge + '</td>' +
                '<td class="py-1"><span class="badge badge-success badge-sm">✓</span></td>' +
                '</tr>';
            historyTable.prepend(newRow);

            // Remove oldest entry if more than 5
            if (historyTable.find('tr').length > 5) {
                historyTable.find('tr:last').remove();
            }
        }
    }
}

// Guarantee approval/rejection functions
function approveGuarantee(guaranteeId) {
    if (confirm('Are you sure you want to approve this guarantee? This will register the guarantee in all relevant reports.')) {
        // Find the guarantee item element
        const guaranteeItem = $('button[onclick*="approveGuarantee(' + guaranteeId + ')"]').closest('.guarantee-item');

        // Disable buttons during processing
        guaranteeItem.find('button').prop('disabled', true);

        $.ajax({
            url: '<?php echo e(route("loans.guarantees.approve", ":id")); ?>'.replace(':id', guaranteeId),
            type: 'PATCH',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                // Update UI dynamically
                const statusBadge = guaranteeItem.find('.badge');
                statusBadge.removeClass('badge-warning').addClass('badge-success').text('Approved');

                // Hide approve/reject buttons
                guaranteeItem.find('.btn-group').hide();

                // Add approval timestamp if available
                const approvalDate = new Date().toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric'
                });

                // Update any related statistics or counters
                updateGuaranteeStats();

                toastr.success('Guarantee approved and registered in reports successfully');

                // Optional: Add visual feedback
                guaranteeItem.addClass('guarantee-approved');
                setTimeout(() => {
                    guaranteeItem.removeClass('guarantee-approved');
                }, 2000);
            },
            error: function(xhr) {
                // Re-enable buttons on error
                guaranteeItem.find('button').prop('disabled', false);
                const errorMsg = xhr.responseJSON?.message || xhr.responseJSON?.error || 'Failed to approve guarantee';
                toastr.error(errorMsg);
            }
        });
    }
}

function updateGuaranteeStats() {
    // Update any guarantee statistics counters if they exist
    const approvedCount = $('.badge-success:contains("Approved")').length;
    const pendingCount = $('.badge-warning:contains("Pending")').length;

    // Update counters in the UI if they exist
    $('.guarantee-approved-count').text(approvedCount);
    $('.guarantee-pending-count').text(pendingCount);
}

function rejectGuarantee(guaranteeId) {
    var reason = prompt('Please provide a reason for rejection (this will be recorded in the reports):');
    if (reason !== null && reason.trim() !== '') {
        // Find the guarantee item element
        const guaranteeItem = $('button[onclick*="rejectGuarantee(' + guaranteeId + ')"]').closest('.guarantee-item');

        // Disable buttons during processing
        guaranteeItem.find('button').prop('disabled', true);

        $.ajax({
            url: '<?php echo e(route("loans.guarantees.reject", ":id")); ?>'.replace(':id', guaranteeId),
            type: 'PATCH',
            data: { reason: reason },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                // Update UI dynamically
                const statusBadge = guaranteeItem.find('.badge');
                statusBadge.removeClass('badge-warning').addClass('badge-danger').text('Rejected');

                // Hide approve/reject buttons
                guaranteeItem.find('.btn-group').hide();

                // Add rejection reason as a note
                guaranteeItem.append('<div class="mt-2"><small class="text-muted"><strong>Rejection Reason:</strong> ' + reason + '</small></div>');

                // Update any related statistics
                updateGuaranteeStats();

                toastr.success('Guarantee rejected and recorded in reports');

                // Optional: Add visual feedback
                guaranteeItem.addClass('guarantee-rejected');
                setTimeout(() => {
                    guaranteeItem.removeClass('guarantee-rejected');
                }, 2000);
            },
            error: function(xhr) {
                // Re-enable buttons on error
                guaranteeItem.find('button').prop('disabled', false);
                const errorMsg = xhr.responseJSON?.message || xhr.responseJSON?.error || 'Failed to reject guarantee';
                toastr.error(errorMsg);
            }
        });
    }
}
</script>
<?php $__env->stopSection(); ?>


<?php echo $__env->make('adminlte::page', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\morio_sacco\resources\views\adminlte\loans\show.blade.php ENDPATH**/ ?>