{% extends 'base.html' %}
{% load static %}
{% load humanize %}

{% block title %}All Repayments{% endblock %}

{% block extra_css %}
<style>
    .repayments-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 10px 10px 0 0;
        padding: 20px;
        margin-bottom: 0;
    }

    .stats-card {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 8px;
        padding: 15px;
        margin: 10px;
        text-align: center;
        backdrop-filter: blur(10px);
    }

    .stats-number {
        font-size: 2rem;
        font-weight: bold;
        display: block;
    }

    .stats-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }

    .filter-section {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .table-container {
        background: white;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }

    .table thead th {
        background: #495057;
        color: white;
        border: none;
        font-weight: 600;
        text-transform: uppercase;
        font-size: 0.85rem;
        letter-spacing: 0.5px;
    }

    .table tbody tr {
        transition: all 0.3s ease;
    }

    .table tbody tr:hover {
        background-color: #f8f9fa;
        transform: translateY(-1px);
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .badge-modern {
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 0.75rem;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .btn-action {
        margin: 2px;
        border-radius: 20px;
        padding: 5px 12px;
        font-size: 0.75rem;
        font-weight: 500;
        transition: all 0.3s ease;
    }

    .btn-action:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    .thermal-btn {
        background: linear-gradient(45deg, #ff6b6b, #ee5a24);
        border: none;
        color: white;
    }

    .thermal-btn:hover {
        background: linear-gradient(45deg, #ee5a24, #ff6b6b);
        color: white;
    }

    .pagination {
        margin-top: 30px;
    }

    .pagination .page-link {
        border-radius: 20px;
        margin: 0 2px;
        border: none;
        color: #667eea;
    }

    .pagination .page-item.active .page-link {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
    }

    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #6c757d;
    }

    .empty-state i {
        font-size: 4rem;
        margin-bottom: 20px;
        opacity: 0.5;
    }

    /* Fix for loan ID visibility */
    .badge-outline-primary {
        color: #007bff !important;
        background-color: #ffffff !important;
        border: 1px solid #007bff !important;
        text-decoration: none !important;
    }

    .badge-outline-primary:hover {
        color: #ffffff !important;
        background-color: #007bff !important;
        border: 1px solid #007bff !important;
        text-decoration: none !important;
    }

    /* Ensure loan number links are always visible */
    td a.badge {
        color: #007bff !important;
        background-color: #e3f2fd !important;
        border: 1px solid #007bff !important;
        padding: 4px 8px !important;
        border-radius: 4px !important;
        text-decoration: none !important;
        font-weight: 500 !important;
    }

    td a.badge:hover {
        color: #ffffff !important;
        background-color: #007bff !important;
        text-decoration: none !important;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card border-0">
                <!-- Enhanced Header -->
                <div class="repayments-header">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <h2 class="mb-0">
                                <span>💵</span>
                                All Loan Repayments
                            </h2>
                            <p class="mb-0 mt-2 opacity-75">Comprehensive view of all loan repayments</p>
                            <!-- Quick action buttons (admin only) -->
                            {% if user.role == 'admin' %}
                            <div class="mt-3 d-flex flex-wrap" style="gap: 8px;">
                                <a href="{% url 'payments:unconfirmed_payments' %}" 
                                   class="btn btn-sm" 
                                   style="background: rgba(255,193,7,0.25); color: white; border: 1px solid rgba(255,255,255,0.5); border-radius: 20px; font-size: 0.8rem; padding: 4px 12px; backdrop-filter: blur(4px);">
                                    ⚠️ Unconfirmed Payments
                                </a>
                                <a href="{% url 'payments:callbacks' %}" 
                                   class="btn btn-sm" 
                                   style="background: rgba(255,255,255,0.15); color: white; border: 1px solid rgba(255,255,255,0.5); border-radius: 20px; font-size: 0.8rem; padding: 4px 12px; backdrop-filter: blur(4px);">
                                    📋 M-Pesa Callbacks
                                </a>
                                <a href="{% url 'payments:sasapay_dashboard' %}" 
                                   class="btn btn-sm" 
                                   style="background: rgba(17,153,142,0.4); color: white; border: 1px solid rgba(255,255,255,0.5); border-radius: 20px; font-size: 0.8rem; padding: 4px 12px; backdrop-filter: blur(4px);">
                                    💳 SasaPay
                                </a>
                                <a href="{% url 'payments:sms_logs' %}" 
                                   class="btn btn-sm" 
                                   style="background: rgba(56,239,125,0.25); color: white; border: 1px solid rgba(255,255,255,0.5); border-radius: 20px; font-size: 0.8rem; padding: 4px 12px; backdrop-filter: blur(4px);">
                                    � SMS Logs
                                </a>
                            </div>
                            {% endif %}
                        </div>
                        <div class="col-md-6">
                            <div class="row">
                                <div class="col-4">
                                    <div class="stats-card">
                                        <span class="stats-number">{{ total_repayments }}</span>
                                        <span class="stats-label">Total Repayments</span>
                                    </div>
                                </div>
                                <div class="col-4">
                                    <div class="stats-card">
                                        <span class="stats-number">{{ total_amount|floatformat:0|intcomma }}</span>
                                        <span class="stats-label">Total Amount (KSh)</span>
                                    </div>
                                </div>
                                <div class="col-4 d-flex align-items-center justify-content-end">
                                    <div class="btn-group" role="group">
                                        <button onclick="exportToExcel()" class="btn btn-success btn-sm mr-2">
                                            <span>📊</span>Export Excel
                                        </button>
                                        <button onclick="exportToPDF()" class="btn btn-danger btn-sm mr-2">
                                            <span>📄</span>Export PDF
                                        </button>
                                        {% if user.is_admin %}
                                        <button onclick="refreshAllPayments()" class="btn btn-warning btn-sm">
                                            <span>🔄</span>Refresh All
                                        </button>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card-body">
                    <!-- SasaPay Auto-Payment Info Banner (admin only) -->
                    {% if user.role == 'admin' or user.role == 'team_leader' %}
                    <div class="mb-4 p-3 rounded" style="background: linear-gradient(135deg, #e8f7fa 0%, #f0fff4 100%); border-left: 4px solid #11998e;">
                        <div class="d-flex align-items-start">
                            <span style="font-size: 1.6rem; margin-right: 12px; line-height: 1;">⚡</span>
                            <div class="flex-grow-1">
                                <strong style="color: #0a5c52; font-size: 0.95rem;">Auto-payments are active.</strong>
                                <p class="mb-2 mt-1" style="font-size: 0.85rem; color: #444; line-height: 1.5;">
                                    When a customer pays via M-Pesa paybill, SasaPay sends the payment here automatically — 
                                    it is matched to their loan, a repayment is recorded, and a confirmation SMS is sent to 
                                    the customer + all admin numbers. Payments marked 
                                    <span class="badge" style="background: #28a745; color: white; font-size: 0.75rem;">⚡ Auto (SasaPay)</span> 
                                    were received this way.
                                </p>
                                <div class="d-flex flex-wrap" style="gap: 8px;">
                                    <a href="{% url 'payments:sasapay_dashboard' %}" 
                                       class="btn btn-sm" 
                                       style="background: #11998e; color: white; border-radius: 20px; font-size: 0.8rem; font-weight: 600; padding: 5px 14px; text-decoration: none;">
                                        💳 SasaPay Dashboard
                                    </a>
                                    <a href="{% url 'payments:sms_logs' %}" 
                                       class="btn btn-sm" 
                                       style="background: #28a745; color: white; border-radius: 20px; font-size: 0.8rem; font-weight: 600; padding: 5px 14px; text-decoration: none;">
                                        📱 SMS Logs
                                    </a>
                                    <a href="{% url 'payments:sasapay_unknown_payments' %}" 
                                       class="btn btn-sm" 
                                       style="background: #ffc107; color: #212529; border-radius: 20px; font-size: 0.8rem; font-weight: 600; padding: 5px 14px; text-decoration: none;">
                                        ⚠️ Unknown Payments
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endif %}

                    <!-- Enhanced Search and Filter Form -->
                    <div class="filter-section">
                        <form method="get">
                            <div class="row">
                                <div class="col-md-3">
                                    <label class="form-label"><span>🔍</span>Search</label>
                                    <input type="text" name="search" class="form-control"
                                        placeholder="Borrower, phone, loan ID..." value="{{ search_query }}">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label"><span>📅</span>Start Date</label>
                                    <input type="date" name="start_date" class="form-control" value="{{ start_date }}">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label"><span>📅</span>End Date</label>
                                    <input type="date" name="end_date" class="form-control" value="{{ end_date }}">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label"><span>💳</span>Payment
                                        Method</label>
                                    <select name="payment_method" class="form-control">
                                        <option value="">All Methods</option>
                                        {% for method in payment_methods %}
                                        <option value="{{ method }}" {% if method == payment_method %}selected{% endif %}>
                                            {{ method }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label"><i class="fas fa-robot mr-1"></i>Payment Source</label>
                                    <select name="payment_source" class="form-control">
                                        <option value="">All Sources</option>
                                        {% for value, label in payment_sources %}
                                        <option value="{{ value }}" {% if value == payment_source %}selected{% endif %}>
                                            {{ label }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label"><span>🧾</span>Receipt Status</label>
                                    <select name="receipt_status" class="form-control">
                                        <option value="">All Receipts</option>
                                        <option value="with_receipt" {% if receipt_status == 'with_receipt' %}selected{%
                                            endif %}>With Receipt</option>
                                        <option value="without_receipt" {% if receipt_status == 'without_receipt'
                                            %}selected{% endif %}>Without Receipt</option>
                                    </select>
                                </div>
                                <div class="col-md-1 d-flex align-items-end">
                                    <button type="submit" class="btn btn-primary btn-block">
                                        <span>🔍</span> Filter
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Top Pagination Controls -->
                    {% if repayments.has_other_pages %}
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <nav aria-label="Repayments pagination">
                            <ul class="pagination mb-0">
                                {% if repayments.has_previous %}
                                <li class="page-item">
                                    <a class="page-link"
                                        href="?{% if search_query %}search={{ search_query }}&{% endif %}{% if start_date %}start_date={{ start_date }}&{% endif %}{% if end_date %}end_date={{ end_date }}&{% endif %}{% if payment_method %}payment_method={{ payment_method }}&{% endif %}{% if receipt_status %}receipt_status={{ receipt_status }}&{% endif %}page={{ repayments.previous_page_number }}">
                                        <span>‹</span> Previous
                                    </a>
                                </li>
                                {% endif %}

                                {% for num in repayments.paginator.page_range %}
                                {% if repayments.number == num %}
                                <li class="page-item active">
                                    <span class="page-link">{{ num }}</span>
                                </li>
                                {% elif num > repayments.number|add:'-3' and num < repayments.number|add:'3' %}
                                <li class="page-item">
                                    <a class="page-link"
                                        href="?{% if search_query %}search={{ search_query }}&{% endif %}{% if start_date %}start_date={{ start_date }}&{% endif %}{% if end_date %}end_date={{ end_date }}&{% endif %}{% if payment_method %}payment_method={{ payment_method }}&{% endif %}{% if receipt_status %}receipt_status={{ receipt_status }}&{% endif %}page={{ num }}">{{ num }}</a>
                                </li>
                                {% endif %}
                                {% endfor %}

                                {% if repayments.has_next %}
                                <li class="page-item">
                                    <a class="page-link"
                                        href="?{% if search_query %}search={{ search_query }}&{% endif %}{% if start_date %}start_date={{ start_date }}&{% endif %}{% if end_date %}end_date={{ end_date }}&{% endif %}{% if payment_method %}payment_method={{ payment_method }}&{% endif %}{% if receipt_status %}receipt_status={{ receipt_status }}&{% endif %}page={{ repayments.next_page_number }}">
                                        Next <span>›</span>
                                    </a>
                                </li>
                                {% endif %}
                            </ul>
                        </nav>

                        <!-- Custom Page Selector -->
                        <div class="d-flex align-items-center">
                            <label class="mb-0 mr-2" style="white-space: nowrap;">Go to page:</label>
                            <input type="number" id="pageJump" class="form-control form-control-sm" 
                                   style="width: 80px;" min="1" max="{{ repayments.paginator.num_pages }}" 
                                   placeholder="{{ repayments.number }}">
                            <button onclick="jumpToPage()" class="btn btn-sm btn-primary ml-2">Go</button>
                            <span class="ml-2 text-muted" style="white-space: nowrap;">of {{ repayments.paginator.num_pages }}</span>
                        </div>
                    </div>
                    {% endif %}

                    <!-- Enhanced Repayments Table -->
                    <div class="table-container">
                        <table class="table table-hover mb-0">
                            <thead>
                                <tr>
                                    <th><span>📅</span>Date</th>
                                    <th><span>👤</span>Borrower</th>
                                    <th><i class="fas fa-hashtag mr-1"></i>Loan ID</th>
                                    <th><span>🏷️</span>Product</th>
                                    <th><span>💵</span>Amount</th>
                                    <th><span>💳</span>Method</th>
                                    <th><i class="fas fa-robot mr-1"></i>Source</th>
                                    <th><span>ℹ️</span>Status</th>
                                    <th><span>🧾</span>Receipt</th>
                                    <th><span>⚙️</span>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for repayment in repayments %}
                                <tr>
                                    <td>
                                        <strong>{{ repayment.payment_date|date:"M d, Y" }}</strong>
                                        <br><small class="text-muted">{{ repayment.payment_date|date:"H:i" }}</small>
                                    </td>
                                    <td>
                                        <a href="{% url 'users:client_detail' repayment.loan.borrower.pk %}"
                                            class="text-decoration-none">
                                            <strong>{{ repayment.loan.borrower.get_full_name }}</strong>
                                        </a>
                                        <br><small class="text-muted"><span>📞</span>{{repayment.loan.borrower.phone_number }}</small>
                                    </td>
                                    <td>
                                        <a href="{% url 'loans:loan_detail' repayment.loan.pk %}" class="badge"
                                            style="color: #007bff !important; background-color: #e3f2fd !important; border: 1px solid #007bff !important; padding: 4px 8px !important; border-radius: 4px !important; text-decoration: none !important; font-weight: 500 !important;">
                                            {{ repayment.loan.loan_number }}
                                        </a>
                                    </td>
                                    <td>{{ repayment.loan.application.loan_product.name }}</td>
                                    <td>
                                        <strong class="text-success">KSh {{ repayment.amount|floatformat:2|intcomma}}</strong>
                                    </td>
                                    <td>
                                        <span class="badge badge-modern"
                                            style="background-color: #17a2b8; color: white;">{{ repayment.payment_method}}</span>
                                    </td>
                                    <td>
                                        {% if repayment.payment_source == 'automatic' %}
                                        <span class="badge badge-modern"
                                            style="background-color: #28a745; color: white;">
                                            ⚡ Auto (SasaPay)
                                        </span>
                                        {% else %}
                                        <span class="badge badge-modern"
                                            style="background-color: #ffc107; color: #212529;">Manual</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if repayment.loan.status == 'active' %}
                                        <span class="badge badge-modern"
                                            style="background-color: #28a745; color: white;">Active</span>
                                        {% elif repayment.loan.status == 'completed' %}
                                        <span class="badge badge-modern"
                                            style="background-color: #007bff; color: white;">Completed</span>
                                        {% elif repayment.loan.status == 'overdue' %}
                                        <span class="badge badge-modern"
                                            style="background-color: #dc3545; color: white;">Overdue</span>
                                        {% else %}
                                        <span class="badge badge-modern"
                                            style="background-color: #6c757d; color: white;">{{repayment.loan.status|title }}</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if repayment.receipt %}
                                        <span class="badge badge-modern"
                                            style="background-color: #28a745; color: white;"><i
                                                class="fas fa-check mr-1"></i>Generated</span>
                                        {% else %}
                                        <span class="badge badge-modern"
                                            style="background-color: #ffc107; color: #212529;"><i
                                                class="fas fa-exclamation mr-1"></i>Missing</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="btn-group-vertical btn-group-sm">
                                            {% if repayment.receipt %}
                                            <a href="{% url 'utils:view_receipt' repayment.receipt.pk %}"
                                                class="btn btn-info btn-action" title="View Standard Receipt">
                                                <i class="fas fa-eye"></i> View
                                            </a>
                                            <a href="{% url 'utils:view_receipt' repayment.receipt.pk %}?thermal=true"
                                                class="btn thermal-btn btn-action" title="View Thermal Receipt"
                                                target="_blank">
                                                <span>🖨️</span> Thermal
                                            </a>
                                            <a href="{% url 'utils:download_receipt' repayment.receipt.pk %}"
                                                class="btn btn-success btn-action" title="Download Receipt">
                                                <span>⬇️</span> Download
                                            </a>
                                            {% else %}
                                            <a href="{% url 'utils:generate_receipt' repayment.loan.pk %}"
                                                class="btn btn-warning btn-action" title="Generate Receipt">
                                                <span>+</span> Generate
                                            </a>
                                            {% endif %}
                                            
                                            <!-- Edit and Delete Actions -->
                                            {% if user.is_staff %}
                                            <a href="{% url 'loans:edit_repayment' repayment.pk %}"
                                                class="btn btn-primary btn-action" title="Edit Repayment">
                                                <span>✏️</span> Edit
                                            </a>
                                            <a href="{% url 'loans:delete_repayment' repayment.pk %}"
                                                class="btn btn-danger btn-action" title="Delete Repayment">
                                                <span>🗑️</span> Delete
                                            </a>
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% empty %}
                                <tr>
                                    <td colspan="9">
                                        <div class="empty-state">
                                            <span>📥</span>
                                            <h4>No Repayments Found</h4>
                                            <p>No repayments match your current filters. Try adjusting your search
                                                criteria.</p>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>

                    <!-- Enhanced Pagination -->
                    {% if repayments.has_other_pages %}
                    <div class="d-flex justify-content-between align-items-center">
                        <nav aria-label="Repayments pagination">
                            <ul class="pagination mb-0">
                                {% if repayments.has_previous %}
                                <li class="page-item">
                                    <a class="page-link"
                                        href="?{% if search_query %}search={{ search_query }}&{% endif %}{% if start_date %}start_date={{ start_date }}&{% endif %}{% if end_date %}end_date={{ end_date }}&{% endif %}{% if payment_method %}payment_method={{ payment_method }}&{% endif %}{% if receipt_status %}receipt_status={{ receipt_status }}&{% endif %}page={{ repayments.previous_page_number }}">
                                        <span>‹</span> Previous
                                    </a>
                                </li>
                                {% endif %}

                                {% for num in repayments.paginator.page_range %}
                                {% if repayments.number == num %}
                                <li class="page-item active">
                                    <span class="page-link">{{ num }}</span>
                                </li>
                                {% elif num > repayments.number|add:'-3' and num < repayments.number|add:'3' %}
                                <li class="page-item">
                                    <a class="page-link"
                                        href="?{% if search_query %}search={{ search_query }}&{% endif %}{% if start_date %}start_date={{ start_date }}&{% endif %}{% if end_date %}end_date={{ end_date }}&{% endif %}{% if payment_method %}payment_method={{ payment_method }}&{% endif %}{% if receipt_status %}receipt_status={{ receipt_status }}&{% endif %}page={{ num }}">{{ num }}</a>
                                </li>
                                {% endif %}
                                {% endfor %}

                                {% if repayments.has_next %}
                                <li class="page-item">
                                    <a class="page-link"
                                        href="?{% if search_query %}search={{ search_query }}&{% endif %}{% if start_date %}start_date={{ start_date }}&{% endif %}{% if end_date %}end_date={{ end_date }}&{% endif %}{% if payment_method %}payment_method={{ payment_method }}&{% endif %}{% if receipt_status %}receipt_status={{ receipt_status }}&{% endif %}page={{ repayments.next_page_number }}">
                                        Next <span>›</span>
                                    </a>
                                </li>
                                {% endif %}
                            </ul>
                        </nav>

                        <!-- Custom Page Selector -->
                        <div class="d-flex align-items-center">
                            <label class="mb-0 mr-2" style="white-space: nowrap;">Go to page:</label>
                            <input type="number" id="pageJumpBottom" class="form-control form-control-sm" 
                                   style="width: 80px;" min="1" max="{{ repayments.paginator.num_pages }}" 
                                   placeholder="{{ repayments.number }}">
                            <button onclick="jumpToPageBottom()" class="btn btn-sm btn-primary ml-2">Go</button>
                            <span class="ml-2 text-muted" style="white-space: nowrap;">of {{ repayments.paginator.num_pages }}</span>
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal for Receipt Preview -->
<div class="modal fade" id="receiptModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Receipt Preview</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <iframe id="receiptFrame" width="100%" height="600px" frameborder="0"></iframe>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // Jump to page function for top pagination
    function jumpToPage() {
        const pageInput = document.getElementById('pageJump');
        const pageNumber = parseInt(pageInput.value);
        const maxPages = {{ repayments.paginator.num_pages }};
        
        if (pageNumber && pageNumber >= 1 && pageNumber <= maxPages) {
            const urlParams = new URLSearchParams(window.location.search);
            urlParams.set('page', pageNumber);
            window.location.href = '?' + urlParams.toString();
        } else {
            alert('Please enter a valid page number between 1 and ' + maxPages);
        }
    }

    // Jump to page function for bottom pagination
    function jumpToPageBottom() {
        const pageInput = document.getElementById('pageJumpBottom');
        const pageNumber = parseInt(pageInput.value);
        const maxPages = {{ repayments.paginator.num_pages }};
        
        if (pageNumber && pageNumber >= 1 && pageNumber <= maxPages) {
            const urlParams = new URLSearchParams(window.location.search);
            urlParams.set('page', pageNumber);
            window.location.href = '?' + urlParams.toString();
        } else {
            alert('Please enter a valid page number between 1 and ' + maxPages);
        }
    }

    // Allow Enter key to trigger page jump
    document.addEventListener('DOMContentLoaded', function() {
        const pageJumpTop = document.getElementById('pageJump');
        const pageJumpBottom = document.getElementById('pageJumpBottom');
        
        if (pageJumpTop) {
            pageJumpTop.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    jumpToPage();
                }
            });
        }
        
        if (pageJumpBottom) {
            pageJumpBottom.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    jumpToPageBottom();
                }
            });
        }
    });

    // Export functions
    function exportToExcel() {
        const button = event.target;
        const originalText = button.innerHTML;
        button.innerHTML = '<span>⟳</span>Generating...';
        button.disabled = true;
        
        // Get current filter parameters
        const urlParams = new URLSearchParams(window.location.search);
        const exportUrl = `{% url 'loans:export_repayments_excel' %}?${urlParams.toString()}`;
        
        // Open in new window/tab to maintain authentication
        window.open(exportUrl, '_blank');
        
        // Reset button
        setTimeout(() => {
            button.innerHTML = originalText;
            button.disabled = false;
        }, 2000);
    }

    function exportToPDF() {
        const button = event.target;
        const originalText = button.innerHTML;
        button.innerHTML = '<span>⟳</span>Generating...';
        button.disabled = true;
        
        // Get current filter parameters
        const urlParams = new URLSearchParams(window.location.search);
        const exportUrl = `{% url 'loans:export_repayments_pdf' %}?${urlParams.toString()}`;
        
        // Open in new window/tab to maintain authentication
        window.open(exportUrl, '_blank');
        
        // Reset button
        setTimeout(() => {
            button.innerHTML = originalText;
            button.disabled = false;
        }, 2000);
    }


    // Enhanced receipt viewing functionality
    function viewReceipt(receiptId, thermal = false) {
        const url = thermal ?
            `/utils/receipts/${receiptId}/view/?thermal=true` :
            `/utils/receipts/${receiptId}/view/`;

        if (thermal) {
            // Open thermal receipt in new window
            window.open(url, '_blank', 'width=400,height=600,scrollbars=yes');
        } else {
            // Show in modal
            document.getElementById('receiptFrame').src = url;
            $('#receiptModal').modal('show');
        }
    }

    // Refresh all payments function
    function refreshAllPayments() {
        if (!confirm('This will sync all orphaned repayments across all loans. This may take a while. Continue?')) {
            return;
        }

        const button = event.target;
        const originalText = button.innerHTML;
        button.innerHTML = '<span>⟳</span>Refreshing...';
        button.disabled = true;

        fetch('/loans/refresh-all-payments/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(`Success! ${data.total_synced} payments synced across ${data.loans_updated} loans.`);
                    location.reload(); // Refresh the page to show updated payments
                } else {
                    alert('Error: ' + data.error);
                }
            })
            .catch(error => {
                alert('Error refreshing all payments: ' + error);
            })
            .finally(() => {
                button.innerHTML = originalText;
                button.disabled = false;
            });
    }

    // Add click handlers for enhanced UX
    $(document).ready(function () {
        // Add loading states to buttons
        $('.btn-action').click(function () {
            const btn = $(this);
            const originalText = btn.html();
            btn.html('<span>⟳</span> Loading...');

            setTimeout(function () {
                btn.html(originalText);
            }, 2000);
        });

        // Add tooltips
        $('[title]').tooltip();

        // Auto-refresh every 30 seconds if no filters are applied
        if (!window.location.search) {
            setInterval(function () {
                location.reload();
            }, 30000);
        }
    });
</script>
{% endblock %}