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

{% block title %}Loans - Haven Grazuri Investment Limited{% endblock %}

{% block content %}
<div>
    <!-- Summary Statistics -->
    <div class="mb-8 grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
        <a href="{% url 'loans:loans' %}" class="overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6 hover:shadow-lg transition-shadow cursor-pointer block">
            <dt class="truncate text-sm font-medium text-gray-500">Total Loans</dt>
            <dd class="mt-1 text-3xl font-semibold tracking-tight text-gray-900">{{ total_loans }}</dd>
            <p class="mt-2 text-sm text-gray-600">Average Amount: KES {{ advanced_stats.avg_loan_amount|floatformat:2 }}</p>
        </a>
        <a href="{% url 'loans:filtered_loans' %}?status=active" class="overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6 hover:shadow-lg transition-shadow cursor-pointer block">
            <dt class="truncate text-sm font-medium text-gray-500">Active Loans</dt>
            <dd class="mt-1 text-3xl font-semibold tracking-tight text-gray-900">{{ active_loans }}</dd>
            <p class="mt-2 text-sm text-gray-600">Overdue: {{ advanced_stats.overdue_loans }}</p>
        </a>
        <a href="{% url 'reports:portfolio_details' %}" class="overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6 hover:shadow-lg transition-shadow cursor-pointer block">
            <dt class="truncate text-sm font-medium text-gray-500">Total Disbursed</dt>
            <dd class="mt-1 text-3xl font-semibold tracking-tight text-gray-900">KES {{ total_disbursed|floatformat:2 }}</dd>
            <p class="mt-2 text-sm text-gray-600">Default Rate: {{ advanced_stats.default_rate|percentage }}</p>
        </a>
        <a href="{% url 'reports:collection_details' %}" class="overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6 hover:shadow-lg transition-shadow cursor-pointer block">
            <dt class="truncate text-sm font-medium text-gray-500">Total Collected</dt>
            <dd class="mt-1 text-3xl font-semibold tracking-tight text-gray-900">KES {{ total_collected|floatformat:2 }}</dd>
            {% with collection_rate=total_collected|divide:total_disbursed|multiply:100 %}
            <p class="mt-2 text-sm text-gray-600">Collection Rate: {{ collection_rate|percentage }}</p>
            {% endwith %}
        </a>
    </div>

    <!-- Advanced Statistics -->
    <div class="mb-8 grid grid-cols-1 gap-5 lg:grid-cols-2">
        <!-- Loan Distribution by Product -->
        <div class="overflow-hidden rounded-lg bg-white shadow">
            <div class="p-6">
                <h3 class="text-lg font-medium text-gray-900">Loan Distribution by Product</h3>
                <div class="mt-4">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead>
                            <tr>
                                <th class="px-4 py-2 text-left text-sm font-medium text-gray-500">Product Type</th>
                                <th class="px-4 py-2 text-right text-sm font-medium text-gray-500">Count</th>
                                <th class="px-4 py-2 text-right text-sm font-medium text-gray-500">Total Amount</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            {% for product in advanced_stats.loans_by_product %}
                            <tr>
                                <td class="px-4 py-2 text-sm text-gray-900">{{ product.loan_product__product_type }}</td>
                                <td class="px-4 py-2 text-right text-sm text-gray-900">{{ product.count }}</td>
                                <td class="px-4 py-2 text-right text-sm text-gray-900">KES {{ product.total_amount|floatformat:2 }}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Top Borrowers -->
        <div class="overflow-hidden rounded-lg bg-white shadow">
            <div class="p-6">
                <h3 class="text-lg font-medium text-gray-900">Top Borrowers</h3>
                <div class="mt-4">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead>
                            <tr>
                                <th class="px-4 py-2 text-left text-sm font-medium text-gray-500">Client</th>
                                <th class="px-4 py-2 text-right text-sm font-medium text-gray-500">Total Loans</th>
                                <th class="px-4 py-2 text-right text-sm font-medium text-gray-500">Active Loans</th>
                                <th class="px-4 py-2 text-right text-sm font-medium text-gray-500">Total Amount</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            {% for client in advanced_stats.client_summary %}
                            <tr>
                                <td class="px-4 py-2 text-sm text-gray-900">{{ client.borrower__first_name }} {{ client.borrower__last_name }}</td>
                                <td class="px-4 py-2 text-right text-sm text-gray-900">{{ client.total_loans }}</td>
                                <td class="px-4 py-2 text-right text-sm text-gray-900">{{ client.active_loans }}</td>
                                <td class="px-4 py-2 text-right text-sm text-gray-900">KES {{ client.total_amount|floatformat:2 }}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="sm:flex sm:items-center">
        <div class="sm:flex-auto">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-2xl font-semibold text-text-dark">Loan Administration</h1>
                    <p class="mt-2 text-sm text-gray-700">
                        Monitor and manage all client loans, process payments, and handle loan status updates.
                    </p>
                </div>
                <div class="flex gap-4">
                    {% if user.is_staff %}
                    <a href="{% url 'loans:new_application' %}" 
                       class="inline-flex items-center rounded-md bg-primary px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-primary-dark focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary">
                        <span>+</span> New Loan Application
                    </a>
                    {% endif %}
                    <a href="?{{ request.GET.urlencode }}&generate_report=true" 
                       class="inline-flex items-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">
                        <span>⬇️</span> Download Report
                    </a>
                    <button onclick="generateDashboardPDF('loans')" 
                       class="inline-flex items-center rounded-md bg-primary px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-primary-dark">
                        <span>📄</span> Generate PDF
                    </button>
                    {% if user.is_admin %}
                    <a href="{% url 'loans:deleted_loans' %}" 
                       class="inline-flex items-center rounded-md bg-gray-100 px-3 py-2 text-sm font-semibold text-gray-600 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-200">
                        <span>🗑️</span> Deleted Loans
                    </a>
                    {% endif %}
                    
                    <a href="{% url 'loans:completed_loans' %}" 
                       class="inline-flex items-center rounded-md bg-green-100 px-3 py-2 text-sm font-semibold text-green-700 shadow-sm ring-1 ring-inset ring-green-300 hover:bg-green-200">
                        <span>✓</span> Completed Loans
                    </a>
                    
                    <a href="{% url 'loans:rolled_over_loans' %}" 
                       class="inline-flex items-center rounded-md bg-yellow-100 px-3 py-2 text-sm font-semibold text-yellow-700 shadow-sm ring-1 ring-inset ring-yellow-300 hover:bg-yellow-200">
                        <span>🔄</span> Rolled Over Loans
                    </a>
                </div>
            </div>
        </div>
    </div>
    <!-- Filters and Search -->
    <div class="mt-6">
        <form method="get" class="space-y-4">
            <div class="flex flex-col sm:flex-row gap-4">
                <!-- Search Input -->
                <div class="relative flex-1">
                    <div class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
                        <span>🔍</span>
                    </div>
                    <input
                        type="text"
                        name="search"
                        id="loans-search"
                        value="{{ request.GET.search|default:'' }}"
                        class="block w-full rounded-md border-0 py-1.5 pl-10 text-gray-900 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="Search by client name, loan number, or business..."
                    />
                </div>
                
                <div class="flex flex-wrap items-center gap-4">
                    <!-- Status Filter -->
                    <div class="flex items-center gap-2">
                        <span>🔍</span>
                        <select
                            name="status"
                            id="loans-status"
                            class="rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary sm:text-sm sm:leading-6"
                        >
                            <option value="">All Status</option>
                            <option value="pending" {% if request.GET.status == 'pending' %}selected{% endif %}>Pending</option>
                            <option value="under_review" {% if request.GET.status == 'under_review' %}selected{% endif %}>Under Review</option>
                            <option value="approved" {% if request.GET.status == 'approved' %}selected{% endif %}>Approved</option>
                            <option value="active" {% if request.GET.status == 'active' %}selected{% endif %}>Active (Collections)</option>
                            <option value="overdue" {% if request.GET.status == 'overdue' %}selected{% endif %}>Overdue</option>
                            <option value="paid" {% if request.GET.status == 'paid' %}selected{% endif %}>Paid</option>
                            <option value="defaulted" {% if request.GET.status == 'defaulted' %}selected{% endif %}>Defaulted</option>
                            <option value="rolled_over" {% if request.GET.status == 'rolled_over' %}selected{% endif %}>Rolled Over</option>
                        </select>
                    </div>

                    <!-- Product Type Filter -->
                    <div class="flex items-center gap-2">
                        <span>💵</span>
                        <select
                            name="product_type"
                            id="loans-product-type"
                            class="rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary sm:text-sm sm:leading-6"
                        >
                            <option value="">All Products</option>
                            <option value="boost" {% if request.GET.product_type == 'boost' %}selected{% endif %}>Boost</option>
                            <option value="boost_plus" {% if request.GET.product_type == 'boost_plus' %}selected{% endif %}>Boost Plus</option>
                            <option value="mwamba" {% if request.GET.product_type == 'mwamba' %}selected{% endif %}>Mwamba</option>
                            <option value="imara" {% if request.GET.product_type == 'imara' %}selected{% endif %}>Imara</option>
                        </select>
                    </div>

                    <!-- Date Range Filters -->
                    <div class="flex items-center gap-2">
                        <span>📅</span>
                        <input
                            type="date"
                            name="date_from"
                            id="loans-date-from"
                            value="{{ request.GET.date_from|default:'' }}"
                            class="rounded-md border-0 py-1.5 pl-3 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary sm:text-sm sm:leading-6"
                            placeholder="From Date"
                        />
                        <span class="text-gray-500">to</span>
                        <input
                            type="date"
                            name="date_to"
                            id="loans-date-to"
                            value="{{ request.GET.date_to|default:'' }}"
                            class="rounded-md border-0 py-1.5 pl-3 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary sm:text-sm sm:leading-6"
                            placeholder="To Date"
                        />
                    </div>

                    <!-- Search Button -->
                    <button type="submit" 
                            class="rounded-md bg-primary px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-primary-dark focus:ring-2 focus:ring-primary focus:ring-offset-2 flex items-center gap-2">
                        <span>🔍</span>
                        Search
                    </button>

                    <!-- Clear Filters -->
                    <a href="{% url 'loans:loans' %}" 
                       class="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 flex items-center gap-2">
                        <span>✕</span>
                        Clear Filters
                    </a>
                </div>
            </div>
        </form>

        <!-- Active Filters Display -->
        {% if request.GET.search or request.GET.status or request.GET.product_type or request.GET.date_from or request.GET.date_to %}
        <div class="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-md">
            <div class="flex items-center justify-between">
                <div class="text-sm text-blue-700">
                    <span>🔍</span>
                    <span>
                        {% if request.GET.search %}Search: "{{ request.GET.search }}"{% endif %}
                        {% if request.GET.status %}{% if request.GET.search %}, {% endif %}Status: {{ request.GET.status|title }}{% endif %}
                        {% if request.GET.product_type %}{% if request.GET.search or request.GET.status %}, {% endif %}Product: {{ request.GET.product_type|title }}{% endif %}
                        {% if request.GET.date_from or request.GET.date_to %}{% if request.GET.search or request.GET.status or request.GET.product_type %}, {% endif %}Date Range: {{ request.GET.date_from|default:"Start" }} to {{ request.GET.date_to|default:"End" }}{% endif %}
                    </span>
                </div>
                <a href="{% url 'loans:loans' %}" class="text-blue-600 hover:text-blue-800 text-sm">
                    <span>✕</span>Clear all
                </a>
            </div>
        </div>
        {% endif %}
    </div>
    </div>

    <!-- Loans Table -->
    <div class="mt-8 flow-root">
        <div class="-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
            <div class="inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8">
                <div class="overflow-hidden shadow ring-1 ring-black ring-opacity-5 sm:rounded-lg">
                    <div id="loans-table-container">
                        {% include 'loans/loans_table.html' %}
                                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Pagination -->
    {% if loans.paginator.num_pages > 1 %}
    <div class="mt-4 flex items-center justify-between border-t border-gray-200 bg-white px-4 py-3 sm:px-6">
        <div class="flex flex-1 justify-between sm:hidden">
            {% if loans.has_previous %}
            <a href="?page={{ loans.previous_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if selected_status %}&status={{ selected_status }}{% endif %}{% if selected_product_type %}&product_type={{ selected_product_type }}{% endif %}{% if date_from %}&date_from={{ date_from }}{% endif %}{% if date_to %}&date_to={{ date_to }}{% endif %}" 
               class="relative inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">
                Previous
            </a>
            {% endif %}
            {% if loans.has_next %}
            <a href="?page={{ loans.next_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if selected_status %}&status={{ selected_status }}{% endif %}{% if selected_product_type %}&product_type={{ selected_product_type }}{% endif %}{% if date_from %}&date_from={{ date_from }}{% endif %}{% if date_to %}&date_to={{ date_to }}{% endif %}" 
               class="relative ml-3 inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">
                Next
            </a>
            {% endif %}
        </div>
        <div class="hidden sm:flex sm:flex-1 sm:items-center sm:justify-between">
            <div>
                <p class="text-sm text-gray-700">
                    Showing <span class="font-medium">{{ loans.start_index }}</span> to
                    <span class="font-medium">{{ loans.end_index }}</span> of
                    <span class="font-medium">{{ loans.paginator.count }}</span> results
                </p>
            </div>
            <div>
                <nav class="isolate inline-flex -space-x-px rounded-md shadow-sm" aria-label="Pagination">
                    {% if loans.has_previous %}
                    <a href="?page={{ loans.previous_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if selected_status %}&status={{ selected_status }}{% endif %}{% if selected_product_type %}&product_type={{ selected_product_type }}{% endif %}{% if date_from %}&date_from={{ date_from }}{% endif %}{% if date_to %}&date_to={{ date_to }}{% endif %}"
                       class="relative inline-flex items-center rounded-l-md px-2 py-2 text-gray-400 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0">
                        <span class="sr-only">Previous</span>
                        <span>‹</span>
                    </a>
                    {% endif %}
                    
                    {% for i in loans.paginator.page_range %}
                        {% if loans.number == i %}
                        <span class="relative z-10 inline-flex items-center bg-primary px-4 py-2 text-sm font-semibold text-white focus:z-20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary">
                            {{ i }}
                        </span>
                        {% else %}
                        <a href="?page={{ i }}{% if search_query %}&search={{ search_query }}{% endif %}{% if selected_status %}&status={{ selected_status }}{% endif %}{% if selected_product_type %}&product_type={{ selected_product_type }}{% endif %}{% if date_from %}&date_from={{ date_from }}{% endif %}{% if date_to %}&date_to={{ date_to }}{% endif %}"
                           class="relative inline-flex items-center px-4 py-2 text-sm font-semibold text-gray-900 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0">
                            {{ i }}
                        </a>
                        {% endif %}
                    {% endfor %}
                    
                    {% if loans.has_next %}
                    <a href="?page={{ loans.next_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if selected_status %}&status={{ selected_status }}{% endif %}{% if selected_product_type %}&product_type={{ selected_product_type }}{% endif %}{% if date_from %}&date_from={{ date_from }}{% endif %}{% if date_to %}&date_to={{ date_to }}{% endif %}"
                       class="relative inline-flex items-center rounded-r-md px-2 py-2 text-gray-400 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0">
                        <span class="sr-only">Next</span>
                        <span>›</span>
                    </a>
                    {% endif %}
                </nav>
            </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="">
                    {% 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="">
                    {% 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">
                                    </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">
                                    </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">
                                    </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">
                            <span>🔄</span>
                            Submit Rollover 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>

<!-- Status Update Modal (Admin Only) -->
<div id="statusUpdateModal" 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 transition-all sm:my-8 sm:w-full sm:max-w-lg sm:p-6">
                <form id="statusUpdateForm" method="post">
                    {% csrf_token %}
                    <div>
                        <div class="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-purple-100">
                            <span>✏️</span>
                        </div>
                        <div class="mt-3 text-center sm:mt-5">
                            <h3 class="text-base font-semibold leading-6 text-gray-900">Update Loan Status</h3>
                            <div class="mt-2">
                                <p class="text-sm text-gray-500">
                                    Update the status for loan <strong id="statusUpdateLoanNumber"></strong>
                                </p>
                                <p class="text-sm text-gray-500 mt-1">
                                    Current status: <span class="font-medium" id="currentStatus"></span>
                                </p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mt-5 space-y-4">
                        <div>
                            <label for="newStatus" class="block text-sm font-medium text-gray-700">New Status</label>
                            <select id="newStatus" name="status" required
                                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-purple-500 focus:ring-purple-500">
                                <option value="">Select new status</option>
                            </select>
                        </div>
                        
                        <div>
                            <label for="statusReason" class="block text-sm font-medium text-gray-700">Reason</label>
                            <textarea id="statusReason" name="reason" rows="3"
                                      class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-purple-500 focus:ring-purple-500"
                                      placeholder="Enter reason for status change..."></textarea>
                        </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-purple-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-purple-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-purple-600 sm:col-start-2">
                            Update Status
                        </button>
                        <button type="button" onclick="hideStatusUpdateModal()" 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>
    // Simple form-based search and filtering for loans
    document.addEventListener('DOMContentLoaded', function() {
        // Auto-submit form when search input changes (with debounce)
        const searchInput = document.getElementById('loans-search');
        let searchTimeout;
        
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    this.closest('form').submit();
                }, 500); // 500ms delay
            });
        }
        
        // Auto-submit form when select filters change
        const statusSelect = document.getElementById('loans-status');
        const productTypeSelect = document.getElementById('loans-product-type');
        const dateFromInput = document.getElementById('loans-date-from');
        const dateToInput = document.getElementById('loans-date-to');
        
        if (statusSelect) {
            statusSelect.addEventListener('change', function() {
                this.closest('form').submit();
            });
        }
        
        if (productTypeSelect) {
            productTypeSelect.addEventListener('change', function() {
                this.closest('form').submit();
            });
        }
        
        if (dateFromInput) {
            dateFromInput.addEventListener('change', function() {
                this.closest('form').submit();
            });
        }
        
        if (dateToInput) {
            dateToInput.addEventListener('change', function() {
                this.closest('form').submit();
            });
        }
    });

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

    // Modal functions
    function showRepaymentModal(loanId) {
        const modal = document.getElementById('repaymentModal');
        const form = document.getElementById('repaymentForm');
        form.action = `/loans/${loanId}/repay/`;
        
        // 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;
        }
        
        modal.classList.remove('hidden');
    }

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

    function showRolloverModal(loanId) {
        const modal = document.getElementById('rolloverModal');
        const form = document.getElementById('rolloverForm');
        form.action = `/loans/${loanId}/rollover/`;
        modal.classList.remove('hidden');
    }

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

    function showStatusUpdateModal(loanId, currentStatus, loanNumber) {
        const modal = document.getElementById('statusUpdateModal');
        const form = document.getElementById('statusUpdateForm');
        const loanNumberSpan = document.getElementById('statusUpdateLoanNumber');
        const currentStatusSpan = document.getElementById('currentStatus');
        const statusSelect = document.getElementById('newStatus');
        
        form.action = `/loans/${loanId}/update-status/`;
        loanNumberSpan.textContent = loanNumber;
        currentStatusSpan.textContent = currentStatus;
        
        // Populate status options based on current status
        statusSelect.innerHTML = '';
        const validTransitions = {
            'active': [
                {value: 'paid', text: 'Paid'},
                {value: 'defaulted', text: 'Defaulted'},
                {value: 'rolled_over', text: 'Rolled Over'},
                {value: 'written_off', text: 'Written Off'}
            ],
            'defaulted': [
                {value: 'written_off', text: 'Written Off'}
            ],
            'paid': [],
            'rolled_over': [],
            'written_off': []
        };
        
        const transitions = validTransitions[currentStatus] || [];
        if (transitions.length === 0) {
            statusSelect.innerHTML = '<option value="">No status changes allowed</option>';
            statusSelect.disabled = true;
        } else {
            statusSelect.innerHTML = '<option value="">Select new status</option>';
            transitions.forEach(transition => {
                const option = document.createElement('option');
                option.value = transition.value;
                option.textContent = transition.text;
                statusSelect.appendChild(option);
            });
            statusSelect.disabled = false;
        }
        
        modal.classList.remove('hidden');
    }

    function hideStatusUpdateModal() {
        document.getElementById('statusUpdateModal').classList.add('hidden');
    }

    // PDF Generation Functions
    function generateDashboardPDF(dashboardType) {
        const button = event.target.closest('button');
        const originalText = button.innerHTML;
        
        // Show loading state
        button.innerHTML = '<span>⟳</span>Generating PDF...';
        button.disabled = true;
        
        // Determine the correct URL based on dashboard type
        let pdfUrl;
        switch(dashboardType) {
            case 'loans':
                pdfUrl = '{% url "loans:generate_loans_dashboard_pdf" %}';
                break;
            case 'clients':
                pdfUrl = '{% url "loans:generate_clients_dashboard_pdf" %}';
                break;
            case 'payments':
                pdfUrl = '{% url "loans:generate_payments_dashboard_pdf" %}';
                break;
            case 'reports':
                pdfUrl = '{% url "loans:generate_reports_dashboard_pdf" %}';
                break;
            case 'portfolio':
                pdfUrl = '{% url "loans:generate_portfolio_dashboard_pdf" %}';
                break;
            default:
                pdfUrl = '{% url "loans:generate_loans_dashboard_pdf" %}';
        }
        
        // Create a temporary link to download the PDF
        const link = document.createElement('a');
        link.href = pdfUrl;
        link.download = `${dashboardType}_dashboard_report_${new Date().toISOString().slice(0,10)}.pdf`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // Reset button after a delay
        setTimeout(() => {
            button.innerHTML = originalText;
            button.disabled = false;
        }, 3000);
    }
</script>
{% endblock %}