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

{% block title %}Approve Loan Application - Haven Grazuri Investment Limited{% endblock %}

{% block content %}
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="mb-8">
        <nav class="flex" aria-label="Breadcrumb">
            <ol role="list" class="flex items-center space-x-4">
                <li>
                    <div>
                        <a href="{% url 'loans:loans' %}" class="text-gray-400 hover:text-gray-500">
                            <span>🏠</span>
                            <span class="sr-only">Home</span>
                        </a>
                    </div>
                </li>
                <li>
                    <div class="flex items-center">
                        <span>›</span>
                        <a href="{% url 'loans:loans' %}"
                            class="ml-4 text-sm font-medium text-gray-500 hover:text-gray-700">Loans</a>
                    </div>
                </li>
                <li>
                    <div class="flex items-center">
                        <span>›</span>
                        <span class="ml-4 text-sm font-medium text-gray-500">Approve Application</span>
                    </div>
                </li>
            </ol>
        </nav>
    </div>

    <!-- Client Status Warning -->
    {% if application.borrower.status != 'active' %}
    <div class="mb-6 bg-red-50 border border-red-200 rounded-md p-4">
        <div class="flex">
            <div class="flex-shrink-0">
                <span>⚠️</span>
            </div>
            <div class="ml-3">
                <h3 class="text-sm font-medium text-red-800">
                    Client Status Warning
                </h3>
                <div class="mt-2 text-sm text-red-700">
                    <p>
                        This client is currently marked as <strong>{{ application.borrower.get_status_display
                            }}</strong>.
                        {% if application.borrower.status == 'blacklisted' %}
                        Blacklisted clients cannot receive loan approvals.
                        {% elif application.borrower.status == 'suspended' %}
                        Suspended clients cannot receive loan approvals.
                        {% elif application.borrower.status == 'inactive' %}
                        Inactive clients cannot receive loan approvals.
                        {% endif %}
                    </p>
                </div>
            </div>
        </div>
    </div>
    {% endif %}

    <div class="bg-white shadow overflow-hidden sm:rounded-lg">
        <div class="px-4 py-5 sm:px-6 border-b border-gray-200">
            <div class="flex justify-between items-center">
                <div>
                    <h3 class="text-lg leading-6 font-medium text-gray-900">Loan Application Review</h3>
                    <p class="mt-1 max-w-2xl text-sm text-gray-500">Application #{{ application.application_number }}
                    </p>
                </div>
                <div class="flex items-center space-x-4">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium 
                        {% if application.status == 'pending' %}bg-yellow-100 text-yellow-800
                        {% elif application.status == 'under_review' %}bg-blue-100 text-blue-800
                        {% elif application.status == 'approved' %}bg-green-100 text-green-800
                        {% elif application.status == 'rejected' %}bg-red-100 text-red-800
                        {% else %}bg-gray-100 text-gray-800{% endif %}">
                        {{ application.get_status_display }}
                    </span>
                    {% if application.auto_approved %}
                    <span
                        class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
                        <i class="fas fa-robot mr-2"></i> Auto-Approved
                    </span>
                    {% endif %}
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 p-6">
            <!-- Borrower Information -->
            <div class="bg-white rounded-lg border border-gray-200 overflow-hidden">
                <div class="px-4 py-5 sm:px-6 bg-gray-50 border-b border-gray-200">
                    <h3 class="text-lg leading-6 font-medium text-gray-900">
                        <span>👤</span> Borrower Information
                    </h3>
                </div>
                <div class="px-4 py-5 sm:p-6">
                    <dl class="grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-2">
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Full Name</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ application.borrower.get_full_name }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Phone Number</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ application.borrower.phone_number }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Email</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ application.borrower.email }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Business Name</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ application.borrower.business_name|default:"-" }}
                            </dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Credit Score</dt>
                            <dd class="mt-1 text-sm text-gray-900">
                                {% if application.credit_score %}
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                                    {% if application.credit_score >= 700 %}bg-green-100 text-green-800
                                    {% elif application.credit_score >= 600 %}bg-yellow-100 text-yellow-800
                                    {% else %}bg-red-100 text-red-800{% endif %}">
                                    {{ application.credit_score }}
                                </span>
                                {% else %}
                                <span class="text-gray-400">Not Available</span>
                                {% endif %}
                            </dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Previous Loans</dt>
                            <dd class="mt-1 text-sm text-gray-900">
                                {{ application.borrower.loans.count }}
                                {% with defaulted=defaulted_loans %}
                                {% if defaulted > 0 %}
                                <span class="text-red-600 ml-2">({{ defaulted }} defaulted)</span>
                                {% endif %}
                                {% endwith %}
                            </dd>
                        </div>
                    </dl>
                </div>
            </div>

            <!-- Loan Details (Editable) -->
            <div class="bg-white rounded-lg border border-gray-200 overflow-hidden">
                <div class="px-4 py-5 sm:px-6 bg-gray-50 border-b border-gray-200">
                    <h3 class="text-lg leading-6 font-medium text-gray-900">
                        <i class="fas fa-file-invoice-dollar mr-2"></i> Loan Details (Editable)
                    </h3>
                </div>
                <div class="px-4 py-5 sm:p-6">
                    <div class="grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-2">
                        <div>
                            <label class="block text-sm font-medium text-gray-500 mb-1">Loan Product</label>
                            <input type="text" value="{{ application.loan_product.name }}" readonly
                                class="mt-1 block w-full rounded-md border-gray-300 bg-gray-50 text-sm text-gray-900">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-500 mb-1">Product Type</label>
                            <input type="text" value="{{ application.loan_product.get_product_type_display }}" readonly
                                class="mt-1 block w-full rounded-md border-gray-300 bg-gray-50 text-sm text-gray-900">
                        </div>
                        <div>
                            <label for="edit_amount" class="block text-sm font-medium text-gray-700 mb-1">
                                Loan Amount <span class="text-red-500">*</span>
                            </label>
                            <div class="mt-1 relative rounded-md shadow-sm">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <span class="text-gray-500 sm:text-sm">KES</span>
                                </div>
                                <input type="number" id="edit_amount" name="edit_amount" step="0.01" min="0"
                                    value="{{ application.requested_amount }}"
                                    class="focus:ring-primary focus:border-primary block w-full pl-12 pr-12 sm:text-sm border-gray-300 rounded-md"
                                    {% if application.borrower.status != 'active' %}disabled{% endif %}
                                    onchange="calculateLoanTotals()">
                            </div>
                        </div>
                        <div>
                            <label for="edit_duration" class="block text-sm font-medium text-gray-700 mb-1">
                                Duration (days) <span class="text-red-500">*</span>
                            </label>
                            <input type="number" id="edit_duration" name="edit_duration" min="1"
                                value="{{ application.requested_duration }}"
                                class="mt-1 focus:ring-primary focus:border-primary block w-full sm:text-sm border-gray-300 rounded-md"
                                {% if application.borrower.status != 'active' %}disabled{% endif %}
                                onchange="calculateLoanTotals()">
                        </div>
                        <div>
                            <label for="edit_interest_rate" class="block text-sm font-medium text-gray-700 mb-1">
                                Interest Rate (%)
                            </label>
                            <input type="number" id="edit_interest_rate" name="edit_interest_rate" 
                                step="0.01" min="0" max="100"
                                value="{{ application.loan_product.interest_rate }}"
                                class="mt-1 focus:ring-primary focus:border-primary block w-full sm:text-sm border-gray-300 rounded-md"
                                {% if application.borrower.status != 'active' %}disabled{% endif %}
                                onchange="calculateLoanTotals()">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-500 mb-1">Interest Amount</label>
                            <div class="mt-1 relative rounded-md">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <span class="text-gray-500 sm:text-sm">KES</span>
                                </div>
                                <input type="text" id="display_interest" readonly
                                    value="{{ application.interest_amount|floatformat:2 }}"
                                    class="block w-full pl-12 pr-12 sm:text-sm border-gray-300 rounded-md bg-gray-50 text-gray-900">
                            </div>
                        </div>
                        <div>
                            <label for="edit_processing_fee_rate" class="block text-sm font-medium text-gray-700 mb-1">
                                Processing Fee (%)
                            </label>
                            <input type="number" id="edit_processing_fee_rate" name="edit_processing_fee_rate" 
                                step="0.01" min="0" max="100"
                                value="{{ application.loan_product.processing_fee }}"
                                class="mt-1 focus:ring-primary focus:border-primary block w-full sm:text-sm border-gray-300 rounded-md"
                                {% if application.borrower.status != 'active' %}disabled{% endif %}
                                onchange="calculateLoanTotals()">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-500 mb-1">Processing Fee Amount</label>
                            <div class="mt-1 relative rounded-md">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <span class="text-gray-500 sm:text-sm">KES</span>
                                </div>
                                <input type="text" id="display_processing_fee" readonly
                                    value="{{ application.processing_fee_amount|floatformat:2 }}"
                                    class="block w-full pl-12 pr-12 sm:text-sm border-gray-300 rounded-md bg-gray-50 text-gray-900">
                            </div>
                        </div>
                        <div>
                            <label for="edit_repayment_method" class="block text-sm font-medium text-gray-700 mb-1">
                                Repayment Method
                            </label>
                            <select id="edit_repayment_method" name="edit_repayment_method"
                                class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-primary focus:border-primary sm:text-sm rounded-md"
                                {% if application.borrower.status != 'active' %}disabled{% endif %}>
                                {% for method in application.loan_product.available_repayment_methods %}
                                <option value="{{ method }}" {% if application.repayment_method == method %}selected{% endif %}>
                                    {{ method|title }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="sm:col-span-2">
                            <label class="block text-sm font-medium text-gray-500 mb-1">Total Amount to Repay</label>
                            <div class="mt-1 relative rounded-md">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <span class="text-gray-700 font-semibold sm:text-sm">KES</span>
                                </div>
                                <input type="text" id="display_total" readonly
                                    value="{{ application.total_amount|floatformat:2 }}"
                                    class="block w-full pl-12 pr-12 text-lg font-semibold border-gray-300 rounded-md bg-blue-50 text-gray-900">
                            </div>
                        </div>
                        <div class="sm:col-span-2">
                            <label for="edit_purpose" class="block text-sm font-medium text-gray-700 mb-1">Purpose</label>
                            <textarea id="edit_purpose" name="edit_purpose" rows="3"
                                class="mt-1 focus:ring-primary focus:border-primary block w-full sm:text-sm border-gray-300 rounded-md"
                                {% if application.borrower.status != 'active' %}disabled{% endif %}>{{ application.purpose }}</textarea>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Supporting Documents -->
            <div class="bg-white rounded-lg border border-gray-200 overflow-hidden">
                <div class="px-4 py-5 sm:px-6 bg-gray-50 border-b border-gray-200">
                    <h3 class="text-lg leading-6 font-medium text-gray-900">
                        <span>📄</span> Supporting Documents
                    </h3>
                </div>
                <div class="px-4 py-5 sm:p-6">
                    {% if application.supporting_documents %}
                    <div class="space-y-4">
                        {% for document in application.supporting_documents.all %}
                        <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                            <div class="flex items-center">
                                <span>📄</span>
                                <div>
                                    <p class="text-sm font-medium text-gray-900">{{ document.filename }}</p>
                                    <p class="text-xs text-gray-500">{{ document.file.size|filesizeformat }}</p>
                                </div>
                            </div>
                            <a href="{{ document.file.url }}" target="_blank"
                                class="inline-flex items-center px-3 py-1 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                                <span>⬇️</span> View
                            </a>
                        </div>
                        {% endfor %}
                    </div>
                    {% else %}
                    <p class="text-sm text-gray-500">No supporting documents provided</p>
                    {% endif %}
                </div>
            </div>

            <!-- Risk Assessment -->
            <div class="bg-white rounded-lg border border-gray-200 overflow-hidden">
                <div class="px-4 py-5 sm:px-6 bg-gray-50 border-b border-gray-200">
                    <h3 class="text-lg leading-6 font-medium text-gray-900">
                        <span>📈</span> Risk Assessment
                    </h3>
                </div>
                <div class="px-4 py-5 sm:p-6">
                    <dl class="grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-2">
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Credit Score Rating</dt>
                            <dd class="mt-1">
                                {% if application.credit_score %}
                                <div class="flex items-center">
                                    {% if application.credit_score >= 700 %}
                                    <div class="text-green-500"><span>✓</span></div>
                                    <span class="ml-2 text-sm text-green-700">Excellent ({{ application.credit_score
                                        }})</span>
                                    {% elif application.credit_score >= 600 %}
                                    <div class="text-yellow-500"><span>⚠️</span></div>
                                    <span class="ml-2 text-sm text-yellow-700">Fair ({{ application.credit_score
                                        }})</span>
                                    {% else %}
                                    <div class="text-red-500"><span>✕</span></div>
                                    <span class="ml-2 text-sm text-red-700">Poor ({{ application.credit_score }})</span>
                                    {% endif %}
                                </div>
                                {% else %}
                                <span class="text-sm text-gray-500">Not Available</span>
                                {% endif %}
                            </dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Payment History</dt>
                            <dd class="mt-1">
                                {% with total_loans=application.borrower.loans.count %}
                                {% with paid_loans=paid_loans %}
                                {% if total_loans > 0 %}
                                <div class="flex items-center">
                                    {% if paid_loans == total_loans %}
                                    <div class="text-green-500"><span>✓</span></div>
                                    <span class="ml-2 text-sm text-green-700">Perfect Payment History</span>
                                    {% elif paid_loans >= total_loans|multiply:0.7 %}
                                    <div class="text-yellow-500"><span>⚠️</span></div>
                                    <span class="ml-2 text-sm text-yellow-700">Good Payment History</span>
                                    {% else %}
                                    <div class="text-red-500"><span>✕</span></div>
                                    <span class="ml-2 text-sm text-red-700">Poor Payment History</span>
                                    {% endif %}
                                </div>
                                {% else %}
                                <span class="text-sm text-gray-500">No Previous Loans</span>
                                {% endif %}
                                {% endwith %}
                                {% endwith %}
                            </dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Debt-to-Income Ratio</dt>
                            <dd class="mt-1">
                                {% if application.borrower.monthly_income %}
                                {% with dti_ratio=application.total_amount|divide:application.borrower.monthly_income|multiply:100 %}
                                <div class="flex items-center">
                                    {% if dti_ratio <= 40 %}
                                    <div class="text-green-500"><span>✓</span></div>
                                    <span class="ml-2 text-sm text-green-700">Good ({{ dti_ratio|floatformat:1 }}%)</span>
                                    {% elif dti_ratio <= 50 %}
                                    <div class="text-yellow-500"><span>⚠️</span></div>
                                    <span class="ml-2 text-sm text-yellow-700">Fair ({{ dti_ratio|floatformat:1 }}%)</span>
                                    {% else %}
                                    <div class="text-red-500"><span>✕</span></div>
                                    <span class="ml-2 text-sm text-red-700">High ({{ dti_ratio|floatformat:1 }}%)</span>
                                    {% endif %}
                                </div>
                                {% endwith %}
                                {% else %}
                                <span class="text-sm text-gray-500">Monthly income not provided</span>
                                {% endif %}
                </dd>
            </div>
            <div>
                <dt class="text-sm font-medium text-gray-500">Risk Level</dt>
                <dd class="mt-1">
                    {% with risk_score=application.calculate_risk_score %}
                    <div class="flex items-center">
                        {% if risk_score >= 80 %}
                        <div class="text-green-500"><i class="fas fa-shield-alt"></i></div>
                        <span class="ml-2 text-sm text-green-700">Low Risk</span>
                        {% elif risk_score >= 60 %}
                        <div class="text-yellow-500"><i class="fas fa-shield-alt"></i></div>
                        <span class="ml-2 text-sm text-yellow-700">Medium Risk</span>
                        {% else %}
                        <div class="text-red-500"><i class="fas fa-shield-alt"></i></div>
                        <span class="ml-2 text-sm text-red-700">High Risk</span>
                        {% endif %}
                    </div>
                    {% endwith %}
                </dd>
            </div>
            </dl>
        </div>
    </div>
    
    <!-- Loan History -->
    <div class="col-span-1 lg:col-span-2 bg-white rounded-lg border border-gray-200 overflow-hidden">
        <div class="px-4 py-5 sm:px-6 bg-gradient-to-r from-indigo-500 to-purple-600 border-b border-gray-200">
            <h3 class="text-lg leading-6 font-medium text-white">
                <i class="fas fa-history mr-2"></i> Previous Loans & Repayment History
            </h3>
        </div>
        <div class="px-4 py-5 sm:p-6">
            <!-- Statistics -->
            <div class="grid grid-cols-2 md:grid-cols-5 gap-4 mb-6">
                <div class="bg-gradient-to-br from-blue-50 to-blue-100 p-4 rounded-lg text-center">
                    <div class="text-xs text-gray-600 mb-1">Total Loans</div>
                    <div class="text-2xl font-bold text-gray-900">{{ previous_loans|length|default:0 }}</div>
                </div>
                <div class="bg-gradient-to-br from-green-50 to-green-100 p-4 rounded-lg text-center">
                    <div class="text-xs text-gray-600 mb-1">Active Loans</div>
                    <div class="text-2xl font-bold text-gray-900">{{ active_loans_count|default:0 }}</div>
                </div>
                <div class="bg-gradient-to-br from-purple-50 to-purple-100 p-4 rounded-lg text-center">
                    <div class="text-xs text-gray-600 mb-1">Completed</div>
                    <div class="text-2xl font-bold text-gray-900">{{ completed_loans_count|default:0 }}</div>
                </div>
                <div class="bg-gradient-to-br from-yellow-50 to-yellow-100 p-4 rounded-lg text-center">
                    <div class="text-xs text-gray-600 mb-1">Total Borrowed</div>
                    <div class="text-lg font-bold text-gray-900">KES {{ total_borrowed|floatformat:0|default:"0"|intcomma }}</div>
                </div>
                <div class="bg-gradient-to-br from-pink-50 to-pink-100 p-4 rounded-lg text-center">
                    <div class="text-xs text-gray-600 mb-1">Total Repaid</div>
                    <div class="text-lg font-bold text-gray-900">KES {{ total_repaid|floatformat:0|default:"0"|intcomma }}</div>
                </div>
            </div>
            
            <!-- Loan History Table -->
            {% if previous_loans %}
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Loan Number</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Amount</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Disbursed</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Total Repaid</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Outstanding</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Repayment</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        {% for loan in previous_loans %}
                        <tr class="hover:bg-gray-50">
                            <td class="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900">{{ loan.loan_number }}</td>
                            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-900">KES {{ loan.principal_amount|floatformat:2|intcomma }}</td>
                            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">{{ loan.disbursement_date|date:"Y-m-d" }}</td>
                            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-900">KES {{ loan.amount_paid|floatformat:2|intcomma }}</td>
                            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-900">KES {{ loan.outstanding_amount|floatformat:2|intcomma }}</td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                {% if loan.status == 'active' %}
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">Active</span>
                                {% elif loan.status == 'paid' %}
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">Paid</span>
                                {% elif loan.status == 'defaulted' %}
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">Defaulted</span>
                                {% else %}
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">{{ loan.status|title }}</span>
                                {% endif %}
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap text-sm font-semibold">
                                {% if loan.status == 'paid' %}
                                    <span class="text-green-600">100%</span>
                                {% elif loan.status == 'active' %}
                                    <span class="text-blue-600">{{ loan.repayment_percentage|default:"0" }}%</span>
                                {% elif loan.status == 'defaulted' %}
                                    <span class="text-red-600">{{ loan.repayment_percentage|default:"0" }}%</span>
                                {% else %}
                                    <span class="text-gray-500">{{ loan.repayment_percentage|default:"0" }}%</span>
                                {% endif %}
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            {% else %}
            <div class="text-center py-12 bg-gray-50 rounded-lg">
                <span>📥</span>
                <p class="text-sm font-medium text-gray-900">No previous loan history</p>
                <p class="text-xs text-gray-500 mt-1">This will be the borrower's first loan</p>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- Approval Form -->
<div class="px-4 py-5 sm:px-6 bg-gray-50 border-t border-gray-200">
    <form method="post" class="space-y-6" id="approvalForm">
        {% csrf_token %}
        
        <!-- Hidden fields for edited values -->
        <input type="hidden" name="approved_amount" id="approved_amount" value="{{ application.requested_amount }}">
        <input type="hidden" name="approved_duration" id="approved_duration" value="{{ application.requested_duration }}">
        <input type="hidden" name="approved_purpose" id="approved_purpose" value="{{ application.purpose }}">
        
        <div>
            <label for="disbursement_date" class="block text-sm font-medium text-gray-700">
                Disbursement Date
                {% if not user.is_admin %}
                <span class="text-xs text-gray-500">(Admin only can set past dates)</span>
                {% endif %}
            </label>
            <div class="mt-1">
                <input type="date" id="disbursement_date" name="disbursement_date"
                    class="shadow-sm focus:ring-primary focus:border-primary block w-full sm:text-sm border-gray-300 rounded-md"
                    value="{{ today|date:'Y-m-d' }}" {% if not user.is_admin %}min="{{ today|date:'Y-m-d' }}" {% endif
                    %} {% if application.borrower.status != 'active' %}disabled{% endif %}>
            </div>
            <p class="mt-1 text-sm text-gray-500">
                Select the actual date when the loan was/will be disbursed
            </p>
        </div>

        <div>
            <label for="notes" class="block text-sm font-medium text-gray-700">Approval Notes</label>
            <div class="mt-1">
                <textarea id="notes" name="notes" rows="4"
                    class="shadow-sm focus:ring-primary focus:border-primary block w-full sm:text-sm border-gray-300 rounded-md"
                    placeholder="Enter any notes or comments regarding the approval decision..." {% if
                    application.borrower.status != 'active' %}disabled{% endif %}></textarea>
            </div>
        </div>

        <div class="flex justify-end space-x-4">
            <a href="{% url 'loans:loans' %}"
                class="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                Cancel
            </a>
            {% if application.borrower.status == 'active' %}
            <button type="submit"
                class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-primary hover:bg-primary-dark focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                <span>✓</span> Approve Application
            </button>
            {% else %}
            <button type="button" disabled
                class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-gray-400 cursor-not-allowed">
                <i class="fas fa-ban mr-2"></i> Cannot Approve ({{ application.borrower.get_status_display }})
            </button>
            {% endif %}
        </div>
    </form>
</div>

<script>
// Store loan product details for calculations
const loanProduct = {
    interestRate: parseFloat('{{ application.loan_product.interest_rate }}'),
    processingFeeRate: parseFloat('{{ application.loan_product.processing_fee }}'),
    minAmount: parseFloat('{{ application.loan_product.min_amount }}'),
    maxAmount: parseFloat('{{ application.loan_product.max_amount }}'),
    minDuration: parseInt('{{ application.loan_product.min_duration }}'),
    maxDuration: parseInt('{{ application.loan_product.max_duration }}')
};

function calculateLoanTotals() {
    const amount = parseFloat(document.getElementById('edit_amount').value) || 0;
    const duration = parseInt(document.getElementById('edit_duration').value) || 0;
    const interestRate = parseFloat(document.getElementById('edit_interest_rate').value) || 0;
    const processingFeeRate = parseFloat(document.getElementById('edit_processing_fee_rate').value) || 0;
    
    // Validate amount
    if (amount < loanProduct.minAmount || amount > loanProduct.maxAmount) {
        alert('Loan amount must be between KES ' + loanProduct.minAmount.toLocaleString() + ' and KES ' + loanProduct.maxAmount.toLocaleString());
        return;
    }
    
    // Validate duration
    if (duration < loanProduct.minDuration || duration > loanProduct.maxDuration) {
        alert('Duration must be between ' + loanProduct.minDuration + ' and ' + loanProduct.maxDuration + ' days');
        return;
    }
    
    // Calculate interest using editable rate
    const interestAmount = (amount * interestRate / 100);
    
    // Calculate processing fee using editable rate
    const processingFee = (amount * processingFeeRate / 100);
    
    // Calculate total
    const totalAmount = amount + interestAmount + processingFee;
    
    // Update display fields
    document.getElementById('display_interest').value = interestAmount.toFixed(2);
    document.getElementById('display_processing_fee').value = processingFee.toFixed(2);
    document.getElementById('display_total').value = totalAmount.toFixed(2);
    
    // Update hidden fields
    document.getElementById('approved_amount').value = amount;
    document.getElementById('approved_duration').value = duration;
}

// Update hidden purpose field when textarea changes
document.getElementById('edit_purpose').addEventListener('change', function() {
    document.getElementById('approved_purpose').value = this.value;
});

// Sync hidden fields before form submission
document.getElementById('approvalForm').addEventListener('submit', function(e) {
    document.getElementById('approved_amount').value = document.getElementById('edit_amount').value;
    document.getElementById('approved_duration').value = document.getElementById('edit_duration').value;
    document.getElementById('approved_purpose').value = document.getElementById('edit_purpose').value;
});
</script>
</div>
</div>
{% endblock %}