{% extends 'base.html' %}

{% block title %}Loan {{ loan.loan_number }} - Haven Grazuri Investment Limited{% endblock %}

{% block content %}
<div>
    <!-- Loan Header -->
    <div class="sm:flex sm:items-center">
        <div class="sm:flex-auto">
            <div class="flex items-center gap-4">
                <h1 class="text-2xl font-semibold text-text-dark">Loan {{ loan.loan_number }}{% if loan.is_deleted %}DELETED{% endif %}</h1>
                {% if loan.is_deleted %}
                <span class="inline-flex rounded-full px-2 text-xs font-semibold leading-5 bg-red-100 text-red-800">
                    🗑️ DELETED
                </span>
                {% else %}
                <span class="inline-flex rounded-full px-2 text-xs font-semibold leading-5 
                    {% if loan.status == 'active' %}bg-green-100 text-green-800
                    {% elif loan.status == 'paid' %}bg-blue-100 text-blue-800
                    {% elif loan.status == 'defaulted' %}bg-red-100 text-red-800
                    {% elif loan.status == 'rolled_over' %}bg-green-100 text-green-800
                    {% else %}bg-gray-100 text-gray-800{% endif %}">
                    {% if loan.status == 'rolled_over' %}Active (Rolled Over){% else %}{{ loan.get_status_display }}{% endif %}
                </span>
                {% endif %}
            </div>
            <p class="mt-2 text-sm text-gray-700">
                {{ loan.application.loan_product.get_product_type_display }} - Disbursed on {{ loan.disbursement_date|date:"M d, Y" }}
            </p>
        </div>
        <div class="mt-4 sm:ml-16 sm:mt-0 sm:flex-none">
            <div class="flex gap-2">
                <!-- Enhanced Statement Options -->
                <div class="flex gap-1">
                    <a href="{% url 'users:client_complete_history' loan.borrower.id %}" 
                       class="rounded-md bg-indigo-600 px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-indigo-700">
                        <i class="fas fa-history mr-1"></i>Complete History
                    </a>
                    <a href="{% url 'utils:loan_statement_view' loan.id %}" 
                       class="rounded-md bg-blue-600 px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-blue-700">
                        <span>🧾</span>Statement
                    </a>
                    <a href="{% url 'loans:loan_amortization' pk=loan.pk %}" 
                       class="rounded-md bg-purple-600 px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-purple-700">
                        <span>🧮</span>Amortization
                    </a>
                    <div class="relative inline-block text-left">
                        <button type="button" onclick="toggleDownloadMenu('loan-download-menu')" 
                                class="rounded-md bg-green-600 px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-green-700">
                            <span>⬇️</span>Download <span>﹀</span>
                        </button>
                        <div id="loan-download-menu" class="hidden absolute right-0 z-10 mt-2 w-48 origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5">
                            <div class="py-1">
                                <a href="{% url 'utils:download_report' 'loan_statement' 'pdf' %}?loan_id={{ loan.id }}" 
                                   class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                    <span>📄</span>PDF Statement
                                </a>
                                <a href="{% url 'utils:download_report' 'loan_statement' 'excel' %}?loan_id={{ loan.id }}" 
                                   class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                    <span>📊</span>Excel Statement
                                </a>
                                <a href="{% url 'utils:download_report' 'loan_statement' 'csv' %}?loan_id={{ loan.id }}" 
                                   class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                    <i class="fas fa-file-csv mr-2 text-blue-600"></i>CSV Statement
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                
                {% if loan.status == 'active' or loan.status == 'rolled_over' %}
                <!-- Payment Actions -->
                <button onclick="showRepaymentModal('{{ loan.pk }}')" class="rounded-md bg-primary px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-secondary">
                    Record Payment
                </button>
                {% if loan.status == 'active' %}
                <button onclick="showRolloverModal('{{ loan.pk }}')" class="rounded-md bg-white px-3 py-2 text-center text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50">
                    Request Rollover
                </button>
                {% endif %}
                {% endif %}
                
                {% if user.is_admin %}
                <!-- Admin Actions -->
                {% if not loan.is_deleted %}
                <a href="{% url 'loans:edit_loan' pk=loan.pk %}" 
                   class="rounded-md bg-blue-600 px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-blue-700">
                    <span>✏️</span>Edit Loan
                </a>
                <a href="{% url 'loans:delete_loan' pk=loan.pk %}" 
                   class="rounded-md bg-orange-600 px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-orange-700">
                    <i class="fas fa-archive mr-1"></i>Move to Deleted
                </a>
                {% else %}
                <a href="{% url 'loans:restore_loan' pk=loan.pk %}" 
                   class="rounded-md bg-green-600 px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-green-700">
                    <span>↶</span>Restore Loan
                </a>
                <a href="{% url 'loans:permanently_delete_loan' pk=loan.pk %}" 
                   class="rounded-md bg-red-600 px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:bg-red-700">
                    <span>🗑️</span>Delete Permanently
                </a>
                {% endif %}
                {% endif %}
            </div>
        </div>
    </div>

    <!-- Deleted Loan Warning -->
    {% if loan.is_deleted %}
    <div class="mt-6 rounded-md bg-yellow-50 p-4">
        <div class="flex">
            <div class="flex-shrink-0">
                <span>⚠️</span>
            </div>
            <div class="ml-3">
                <h3 class="text-sm font-medium text-yellow-800">
                    This loan has been moved to deleted loans
                </h3>
                <div class="mt-2 text-sm text-yellow-700">
                    <p>This loan was deleted on {{ loan.deleted_at|date:"F d, Y H:i" }}{% if loan.deleted_by %} by {{ loan.deleted_by.get_full_name }}{% endif %}. You can restore it or permanently delete it using the buttons above.</p>
                </div>
            </div>
        </div>
    </div>
    {% endif %}

    <!-- Loan Summary Cards -->
    <div class="mt-6 grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-5">
        <div class="overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6 border-l-4 border-primary">
            <dt class="truncate text-sm font-medium text-gray-500">Total Amount</dt>
            <dd class="mt-1 text-3xl font-semibold tracking-tight text-primary">
                KES {{ loan.total_amount|floatformat:2 }}
            </dd>
            <dd class="mt-1 text-xs text-gray-500">
                Principal + Interest + Fee
            </dd>
        </div>
        <div class="overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6">
            <dt class="truncate text-sm font-medium text-gray-500">Principal Amount</dt>
            <dd class="mt-1 text-3xl font-semibold tracking-tight text-gray-900">
                KES {{ loan.principal_amount|floatformat:2 }}
            </dd>
        </div>
        <div class="overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6">
            <dt class="truncate text-sm font-medium text-gray-500">Amount Repaid</dt>
            <dd class="mt-1 text-3xl font-semibold tracking-tight text-gray-900">
                KES {{ loan.amount_paid|floatformat:2 }}
            </dd>
        </div>
        <div class="overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6">
            <dt class="truncate text-sm font-medium text-gray-500">Outstanding Balance</dt>
            <dd class="mt-1 text-3xl font-semibold tracking-tight text-gray-900">
                KES {{ remaining_amount|floatformat:2 }}
            </dd>
            {% if total_penalties > 0 %}
            <dd class="mt-1 text-sm text-red-600">
                Includes KES {{ total_penalties|floatformat:2 }} in penalties
            </dd>
            {% endif %}
        </div>
        <div class="overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6">
            <dt class="truncate text-sm font-medium text-gray-500">Due Date</dt>
            <dd class="mt-1 text-3xl font-semibold tracking-tight text-gray-900">
                {{ loan.due_date|date:"M d, Y" }}
            </dd>
            {% if loan.is_overdue %}
            <dd class="mt-2 text-sm font-medium text-red-600">
                {{ loan.days_overdue }} days overdue
            </dd>
            {% endif %}
        </div>
    </div>

    <!-- Loan Details and Repayment History -->
    <div class="mt-8 grid grid-cols-1 gap-6 lg:grid-cols-2">
        <!-- Loan Details -->
        <div class="rounded-lg bg-white shadow">
            <div class="px-4 py-5 sm:px-6">
                <h3 class="text-lg font-medium leading-6 text-gray-900">Loan Details</h3>
            </div>
            <div class="border-t border-gray-200 px-4 py-5 sm:px-6">
                <dl class="grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-2">
                    <div class="sm:col-span-2">
                        <dt class="text-sm font-medium text-gray-500 mb-2">Borrower</dt>
                        <dd class="mt-1 flex items-center gap-4">
                            <!-- Client Photo -->
                            <div class="flex-shrink-0">
                                {% if loan.borrower.selfie %}
                                <img src="{{ loan.borrower.selfie.url }}" 
                                     alt="{{ loan.borrower.get_full_name }}"
                                     class="h-16 w-16 rounded-full object-cover border-2 border-primary shadow-md">
                                {% else %}
                                <div class="h-16 w-16 rounded-full bg-primary flex items-center justify-center shadow-md">
                                    <span class="text-xl font-bold text-white">
                                        {{ loan.borrower.first_name|first }}{{ loan.borrower.last_name|first }}
                                    </span>
                                </div>
                                {% endif %}
                            </div>
                            <!-- Client Info -->
                            <div class="flex-1">
                                <p class="text-base font-semibold text-gray-900">
                                    {{ loan.borrower.get_full_name }}
                                </p>
                                <p class="text-sm text-gray-500">{{ loan.borrower.phone_number }}</p>
                                {% if loan.borrower.email %}
                                <p class="text-sm text-gray-500">{{ loan.borrower.email }}</p>
                                {% endif %}
                                <a href="{% url 'users:client_detail' loan.borrower.id %}" 
                                   class="text-sm text-blue-600 hover:text-blue-800 mt-1 inline-block">
                                    View Client Profile →
                                </a>
                            </div>
                        </dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Loan Product</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ loan.application.loan_product.name }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Interest Rate</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ loan.get_effective_interest_rate }}%</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Processing Fee</dt>
                        <dd class="mt-1 text-sm text-gray-900">KES {{ loan.processing_fee|floatformat:2 }} ({{ loan.get_effective_processing_fee_rate }}%)</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Principal Amount</dt>
                        <dd class="mt-1 text-sm text-gray-900">KES {{ loan.principal_amount|floatformat:2 }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Interest Amount</dt>
                        <dd class="mt-1 text-sm text-gray-900">KES {{ loan.interest_amount|floatformat:2 }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Total Amount</dt>
                        <dd class="mt-1 text-sm text-gray-900 font-semibold text-primary">KES {{ loan.total_amount|floatformat:2 }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Outstanding Balance</dt>
                        <dd class="mt-1 text-sm text-gray-900 font-semibold">KES {{ loan.outstanding_amount|floatformat:2 }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Duration</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ loan.duration_days }} days</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Late Payments</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ late_payments }}</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Penalty Rate</dt>
                        <dd class="mt-1 text-sm text-gray-900">{{ penalty_rate }}% monthly</dd>
                    </div>
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Total Penalties</dt>
                        <dd class="mt-1 text-sm text-gray-900">KES {{ total_penalties|floatformat:2 }}</dd>
                    </div>
                    {% if is_overdue %}
                    <div>
                        <dt class="text-sm font-medium text-gray-500">Current Penalty</dt>
                        <dd class="mt-1 text-sm text-red-600 font-medium">KES {{ current_penalty|floatformat:2 }}</dd>
                        <dd class="text-xs text-gray-500">For {{ days_overdue }} days overdue</dd>
                        {% if days_missed > 0 %}
                        <dd class="text-xs text-orange-600 font-medium mt-1">{{ days_missed }} days of payments missed</dd>
                        {% endif %}
                    </div>
                    {% endif %}
                </dl>
            </div>
        </div>

        <!-- Repayment History -->
        <div class="rounded-lg bg-white shadow">
            <div class="px-4 py-5 sm:px-6">
                <h3 class="text-lg font-medium leading-6 text-gray-900">Repayment History</h3>
            </div>
            <div class="bg-white shadow rounded-lg">
                <div class="px-4 py-5 sm:px-6 flex justify-between items-center">
                    <div>
                        <h3 class="text-lg font-medium leading-6 text-gray-900">Repayment History</h3>
                        <p class="mt-1 text-sm text-gray-500">All payments made towards this loan</p>
                    </div>
                    <div class="flex gap-2">
                        {% if user.is_staff %}
                        <a href="{% url 'utils:generate_receipt' loan.id %}" 
                           class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700">
                            <span>+</span>Generate Receipt
                        </a>
                        <button onclick="refreshLoanPayments('{{ loan.id }}')"
                                class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700">
                            <span>🔄</span>Refresh Payments
                        </button>
                        {% endif %}
                    </div>
                </div>
            <div class="border-t border-gray-200">
                <div class="flow-root">
                    <ul role="list" class="divide-y divide-gray-200">
                        {% for repayment in repayments %}
                        <li class="px-4 py-4 sm:px-6">
                            <div class="flex items-center justify-between">
                                <div class="flex flex-col">
                                    <p class="text-sm font-medium text-gray-900">
                                        KES {{ repayment.amount|floatformat:2 }}
                                    </p>
                                    <p class="text-sm text-gray-500">
                                        {{ repayment.get_payment_method_display }}
                                        {% if repayment.mpesa_transaction_id %}
                                        - {{ repayment.mpesa_transaction_id }}
                                        {% endif %}
                                    </p>
                                </div>
                                <div class="flex flex-col items-end">
                                    <p class="text-sm text-gray-500">
                                        {{ repayment.payment_date|date:"M d, Y H:i" }}
                                    </p>
                                    <p class="text-sm text-gray-500 mb-2">
                                        {{ repayment.receipt_number }}
                                    </p>
                                    <!-- Receipt Actions -->
                                    <div class="flex space-x-2">
                                        {% if repayment.receipt_set.first %}
                                        <a href="{% url 'utils:view_receipt' repayment.receipt_set.first.id %}" 
                                           target="_blank"
                                           class="inline-flex items-center px-2 py-1 border border-transparent text-xs font-medium rounded text-blue-700 bg-blue-100 hover:bg-blue-200">
                                            <i class="fas fa-eye mr-1"></i>View
                                        </a>
                                        <a href="{% url 'utils:download_receipt' repayment.receipt_set.first.id %}" 
                                           class="inline-flex items-center px-2 py-1 border border-transparent text-xs font-medium rounded text-green-700 bg-green-100 hover:bg-green-200">
                                            <span>⬇️</span>Download
                                        </a>
                                        {% else %}
                                        <span class="inline-flex items-center px-2 py-1 text-xs font-medium rounded text-gray-500 bg-gray-100">
                                            <span>⚠️</span>No Receipt
                                        </span>
                                        {% endif %}
                                        
                                        <!-- Edit and Delete Actions -->
                                        {% if user.is_staff %}
                                        <a href="{% url 'loans:edit_repayment' repayment.pk %}" 
                                           class="inline-flex items-center px-2 py-1 border border-transparent text-xs font-medium rounded text-indigo-700 bg-indigo-100 hover:bg-indigo-200"
                                           title="Edit Repayment">
                                            <span>✏️</span>Edit
                                        </a>
                                        <a href="{% url 'loans:delete_repayment' repayment.pk %}" 
                                           class="inline-flex items-center px-2 py-1 border border-transparent text-xs font-medium rounded text-red-700 bg-red-100 hover:bg-red-200"
                                           title="Delete Repayment">
                                            <span>🗑️</span>Delete
                                        </a>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </li>
                        {% empty %}
                        <li class="px-4 py-4 sm:px-6 text-center text-sm text-gray-500">
                            No repayments recorded yet.
                        </li>
                        {% endfor %}
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- Penalty Management Section -->
    {% include 'loans/penalty_section.html' %}

    <!-- Rollover History -->
    {% if rollovers %}
    <div class="mt-8">
        <div class="rounded-lg bg-white shadow">
            <div class="px-4 py-5 sm:px-6">
                <h3 class="text-lg font-medium leading-6 text-gray-900">Rollover History</h3>
            </div>
            <div class="border-t border-gray-200">
                <div class="flow-root">
                    <ul role="list" class="divide-y divide-gray-200">
                        {% for rollover in rollovers %}
                        <li class="px-4 py-4 sm:px-6">
                            <div class="flex items-center justify-between">
                                <div class="flex flex-col">
                                    <div class="flex items-center gap-2">
                                        <p class="text-sm font-medium text-gray-900">
                                            {{ rollover.requested_duration }} days extension
                                        </p>
                                        <span class="inline-flex rounded-full px-2 text-xs font-semibold leading-5 
                                            {% if rollover.status == 'approved' %}bg-green-100 text-green-800
                                            {% elif rollover.status == 'rejected' %}bg-red-100 text-red-800
                                            {% else %}bg-yellow-100 text-yellow-800{% endif %}">
                                            {{ rollover.get_status_display }}
                                        </span>
                                    </div>
                                    <p class="text-sm text-gray-500">
                                        Rollover Fee: KES {{ rollover.rollover_fee|floatformat:2 }}
                                    </p>
                                    <p class="text-sm text-gray-500">
                                        Reason: {{ rollover.reason }}
                                    </p>
                                </div>
                                <div class="flex flex-col items-end">
                                    <p class="text-sm text-gray-500">
                                        Requested: {{ rollover.requested_at|date:"M d, Y" }}
                                    </p>
                                    {% if rollover.reviewed_at %}
                                    <p class="text-sm text-gray-500">
                                        Reviewed: {{ rollover.reviewed_at|date:"M d, Y" }}
                                    </p>
                                    {% endif %}
                                    {% if rollover.status == 'pending' and user.is_admin %}
                                    <div class="flex gap-2 mt-2">
                                        <button onclick="approveRollover('{{ rollover.pk }}')"
                                                class="inline-flex items-center px-2 py-1 border border-transparent text-xs font-medium rounded text-white bg-green-600 hover:bg-green-700">
                                            <span>✓</span>Approve
                                        </button>
                                        <button onclick="rejectRollover('{{ rollover.pk }}')"
                                                class="inline-flex items-center px-2 py-1 border border-transparent text-xs font-medium rounded text-white bg-red-600 hover:bg-red-700">
                                            <span>✕</span>Reject
                                        </button>
                                    </div>
                                    {% endif %}
                                </div>
                            </div>
                        </li>
                        {% endfor %}
                    </ul>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
</div>

<!-- Repayment Modal -->
<div id="repaymentModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-gray-500 bg-opacity-75"></div>
    <div class="fixed inset-0 z-10 overflow-y-auto">
        <div class="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
            <div class="relative transform overflow-hidden rounded-lg bg-white px-4 pb-4 pt-5 text-left shadow-xl sm:my-8 sm:w-full sm:max-w-lg sm:p-6">
                <form id="repaymentForm" method="post" action="{% url 'loans:record_repayment' pk=loan.pk %}">
                    {% csrf_token %}
                    <div>
                        <div class="mt-3 text-center sm:mt-5">
                            <h3 class="text-lg font-semibold leading-6 text-gray-900">Record Payment</h3>
                            <div class="mt-2">
                                <div class="mb-4">
                                    <label for="amount" class="block text-sm font-medium text-gray-700">Amount</label>
                                    <div class="mt-1">
                                        <input type="number" name="amount" id="amount" step="0.01" required
                                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6">
                                    </div>
                                </div>
                                <div class="mb-4">
                                    <label for="payment_method" class="block text-sm font-medium text-gray-700">Payment Method</label>
                                    <div class="mt-1">
                                        <select name="payment_method" id="payment_method" required
                                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6">
                                            <option value="mpesa">M-Pesa</option>
                                            <option value="bank">Bank Transfer</option>
                                            <option value="cash">Cash</option>
                                            <option value="cheque">Cheque</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="mb-4">
                                    <label for="payment_date" class="block text-sm font-medium text-gray-700">Payment Date</label>
                                    <div class="mt-1">
                                        <input type="datetime-local" name="payment_date" id="payment_date" required
                                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6">
                                    </div>
                                    <p class="mt-1 text-xs text-gray-500">Select when the payment was actually made</p>
                                </div>
                                <div id="mpesaFields" class="mb-4">
                                    <label for="mpesa_phone" class="block text-sm font-medium text-gray-700">M-Pesa Phone Number</label>
                                    <div class="mt-1">
                                        <input type="tel" name="mpesa_phone" id="mpesa_phone"
                                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
                        <button type="submit" class="inline-flex w-full justify-center rounded-md bg-primary px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-secondary sm:col-start-2">
                            Record Payment
                        </button>
                        <button type="button" onclick="hideRepaymentModal()" class="mt-3 inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:col-start-1 sm:mt-0">
                            Cancel
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Enhanced Rollover Modal -->
<div id="rolloverModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-gray-500 bg-opacity-75"></div>
    <div class="fixed inset-0 z-10 overflow-y-auto">
        <div class="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
            <div class="relative transform overflow-hidden rounded-lg bg-white px-4 pb-4 pt-5 text-left shadow-xl sm:my-8 sm:w-full sm:max-w-2xl sm:p-6">
                <form id="rolloverForm" method="post" action="{% url 'loans:request_rollover' pk=loan.pk %}">
                    {% csrf_token %}
                    <div>
                        <div class="mt-3 text-center sm:mt-5">
                            <h3 class="text-lg font-semibold leading-6 text-gray-900">Request Enhanced Loan Rollover</h3>
                            <p class="text-sm text-gray-600 mt-2">Create a new loan with updated terms (like applying for a new loan)</p>
                            <div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                                <!-- New Loan Amount -->
                                <div class="mb-4">
                                    <label for="requested_amount" class="block text-sm font-medium text-gray-700">New Loan Amount (KES)</label>
                                    <div class="mt-1">
                                        <input type="number" name="requested_amount" id="requested_amount" step="0.01" min="1" required
                                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6"
                                            placeholder="Enter new loan amount" value="{{ loan.principal_amount }}">
                                    </div>
                                    <p class="text-xs text-gray-500 mt-1">Amount for the new loan</p>
                                </div>
                                
                                <!-- New Duration -->
                                <div class="mb-4">
                                    <label for="requested_duration" class="block text-sm font-medium text-gray-700">New Duration (Days)</label>
                                    <div class="mt-1">
                                        <input type="number" name="requested_duration" id="requested_duration" min="1" required
                                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6"
                                            placeholder="Enter loan duration" value="{{ loan.duration_days }}">
                                    </div>
                                    <p class="text-xs text-gray-500 mt-1">Duration for the new loan</p>
                                </div>
                                
                                <!-- Custom Interest Rate (Optional) -->
                                <div class="mb-4">
                                    <label for="interest_rate" class="block text-sm font-medium text-gray-700">Custom Interest Rate (%) <span class="text-gray-400">(Optional)</span></label>
                                    <div class="mt-1">
                                        <input type="number" name="interest_rate" id="interest_rate" step="0.01" min="0"
                                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6"
                                            placeholder="Leave blank for default" value="{{ loan.interest_rate }}">
                                    </div>
                                    <p class="text-xs text-gray-500 mt-1">Leave blank to use product default</p>
                                </div>
                                
                                <!-- Custom Processing Fee (Optional) -->
                                <div class="mb-4">
                                    <label for="processing_fee" class="block text-sm font-medium text-gray-700">Custom Processing Fee (KES) <span class="text-gray-400">(Optional)</span></label>
                                    <div class="mt-1">
                                        <input type="number" name="processing_fee" id="processing_fee" step="0.01" min="0"
                                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6"
                                            placeholder="Leave blank for default">
                                    </div>
                                    <p class="text-xs text-gray-500 mt-1">Leave blank to use product default</p>
                                </div>
                                
                                <!-- Rollover Date -->
                                <div class="mb-4">
                                    <label for="rollover_date" class="block text-sm font-medium text-gray-700">Rollover Date <span class="text-gray-400">(Optional)</span></label>
                                    <div class="mt-1">
                                        <input type="date" name="rollover_date" id="rollover_date"
                                            class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6">
                                    </div>
                                    <p class="text-xs text-gray-500 mt-1">Leave blank to use current date</p>
                                </div>
                            </div>
                            
                            <!-- Reason -->
                            <div class="mb-4 col-span-2">
                                <label for="reason" class="block text-sm font-medium text-gray-700">Reason for Rollover</label>
                                <div class="mt-1">
                                    <textarea name="reason" id="reason" rows="3" required
                                        class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-primary sm:text-sm sm:leading-6"
                                        placeholder="Explain why this loan needs to be rolled over..."></textarea>
                                </div>
                            </div>
                            
                            <!-- Information Box -->
                            <div class="bg-blue-50 border border-blue-200 rounded-md p-3 mt-4">
                                <div class="flex">
                                    <div class="flex-shrink-0">
                                        <span>ℹ️</span>
                                    </div>
                                    <div class="ml-3">
                                        <h4 class="text-sm font-medium text-blue-800">How Rollover Works</h4>
                                        <div class="mt-1 text-sm text-blue-700">
                                            <p>• The current loan will be marked as "Rolled Over"</p>
                                            <p>• A new active loan will be created with your specified terms</p>
                                            <p>• The new loan will appear in active loans for collections</p>
                                            <p>• A rollover fee may apply based on the loan product</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
                        <button type="submit" class="inline-flex w-full justify-center rounded-md bg-primary px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-secondary sm:col-start-2">
                            Submit Request
                        </button>
                        <button type="button" onclick="hideRolloverModal()" class="mt-3 inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:col-start-1 sm:mt-0">
                            Cancel
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    // Show/hide M-Pesa fields based on payment method
    document.getElementById('payment_method').addEventListener('change', function() {
        const mpesaFields = document.getElementById('mpesaFields');
        mpesaFields.style.display = this.value === 'mpesa' ? 'block' : 'none';
    });

    // Modal functions
    function showRepaymentModal() {
        // Set default payment date to current time
        const paymentDateInput = document.getElementById('payment_date');
        if (paymentDateInput) {
            const now = new Date();
            const localDateTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
            paymentDateInput.value = localDateTime;
        }
        
        document.getElementById('repaymentModal').classList.remove('hidden');
    }

    function hideRepaymentModal() {
        document.getElementById('repaymentModal').classList.add('hidden');
    }

    function showRolloverModal() {
        document.getElementById('rolloverModal').classList.remove('hidden');
    }

    function hideRolloverModal() {
        document.getElementById('rolloverModal').classList.add('hidden');
    }

    // Refresh loan payments function
    function refreshLoanPayments(loanId) {
        if (!confirm('This will sync orphaned repayments with this loan. Continue?')) {
            return;
        }
        
        const button = event.target;
        const originalText = button.innerHTML;
        button.innerHTML = '<span>⟳</span>Refreshing...';
        button.disabled = true;
        
        fetch(`/loans/${loanId}/refresh-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.synced_count} payments synced, ${data.updated_count} records updated.`);
                location.reload(); // Refresh the page to show updated payments
            } else {
                alert('Error: ' + data.error);
            }
        })
        .catch(error => {
            alert('Error refreshing payments: ' + error);
        })
        .finally(() => {
            button.innerHTML = originalText;
            button.disabled = false;
        });
    }

    // Enhanced statement download menu
    function toggleDownloadMenu(menuId) {
        const menu = document.getElementById(menuId);
        menu.classList.toggle('hidden');
        
        // Close menu when clicking outside
        document.addEventListener('click', function(event) {
            if (!event.target.closest(`#${menuId}`) && !event.target.closest('button')) {
                menu.classList.add('hidden');
            }
        });
    }

    // Rollover approval functions
    function approveRollover(rolloverPk) {
        if (confirm('Are you sure you want to approve this rollover request?')) {
            // Create a form and submit it
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = `/loans/rollovers/${rolloverPk}/approve/`;
            
            // Add CSRF token
            const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
            const csrfInput = document.createElement('input');
            csrfInput.type = 'hidden';
            csrfInput.name = 'csrfmiddlewaretoken';
            csrfInput.value = csrfToken;
            form.appendChild(csrfInput);
            
            document.body.appendChild(form);
            form.submit();
        }
    }

    function rejectRollover(rolloverPk) {
        const reason = prompt('Please provide a reason for rejecting this rollover request:');
        if (reason !== null && reason.trim() !== '') {
            // Create a form and submit it
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = `/loans/rollovers/${rolloverPk}/reject/`;
            
            // Add CSRF token
            const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
            const csrfInput = document.createElement('input');
            csrfInput.type = 'hidden';
            csrfInput.name = 'csrfmiddlewaretoken';
            csrfInput.value = csrfToken;
            form.appendChild(csrfInput);
            
            // Add rejection reason
            const reasonInput = document.createElement('input');
            reasonInput.type = 'hidden';
            reasonInput.name = 'notes';
            reasonInput.value = reason;
            form.appendChild(reasonInput);
            
            document.body.appendChild(form);
            form.submit();
        }
    }
</script>
{% endblock %}