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

{% block title %}Enhanced Rollover Requests{% endblock %}

{% block extra_head %}
<link href="https://cdn.tailwindcss.com/3.4.17" rel="stylesheet">
<style>
  .bg-primary { background-color: #1a56db; }
  .bg-primary-dark { background-color: #1e429f; }
  .text-primary { color: #1a56db; }
  .hover\:bg-primary-dark:hover { background-color: #1e429f; }
  body { font-family: 'Inter', sans-serif; }
</style>
{% endblock %}

{% block content %}
<div class="mb-8">
    <div class="flex justify-between items-center">
        <div>
            <h2 class="text-2xl font-bold leading-7 text-gray-900 sm:truncate sm:text-3xl sm:tracking-tight">
                <span>🔄</span>
                Enhanced Rollover Requests
            </h2>
            <p class="text-gray-600 mt-1">Manage loan rollover requests with full loan parameters</p>
        </div>
        <div class="flex space-x-3">
            <a href="{% url 'loans:loans' %}" class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                <span>←</span>
                Back to Loans
            </a>
            <a href="{% url 'loans:rolled_over_loans' %}" class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                <i class="fas fa-history mr-2"></i>
                Rolled Over Loans
            </a>
        </div>
    </div>
</div>

<!-- Rollover Requests Table -->
<div class="bg-white shadow overflow-hidden sm:rounded-md">
    <div class="px-4 py-5 sm:px-6">
        <h3 class="text-lg leading-6 font-medium text-gray-900">Pending Rollover Requests</h3>
        <p class="mt-1 max-w-2xl text-sm text-gray-500">Review and approve enhanced rollover requests</p>
    </div>
    
    {% if rollovers %}
    <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Original Loan
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Borrower
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        New Loan Details
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Custom Terms
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Status
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Requested Date
                    </th>
                    <th scope="col" class="relative px-6 py-3">
                        <span class="sr-only">Actions</span>
                    </th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
                {% for rollover in rollovers %}
                <tr class="hover:bg-gray-50" data-rollover-id="{{ rollover.pk }}" data-rollover-date="{{ rollover.rollover_date|date:'Y-m-d'|default:'' }}">
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm font-medium text-gray-900">
                            <a href="{% url 'loans:loan_detail' pk=rollover.loan.pk %}" class="text-primary hover:text-primary-dark">
                                {{ rollover.loan.loan_number }}
                            </a>
                        </div>
                        <div class="text-sm text-gray-500">
                            Due: {{ rollover.loan.due_date|date:"M d, Y" }}
                        </div>
                        <div class="text-sm text-gray-500">
                            Outstanding: KES {{ rollover.loan.outstanding_amount|floatformat:2|intcomma }}
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 h-10 w-10">
                                <div class="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center">
                                    <span>👤</span>
                                </div>
                            </div>
                            <div class="ml-4">
                                <div class="text-sm font-medium text-gray-900">
                                    {{ rollover.loan.borrower.get_full_name }}
                                </div>
                                <div class="text-sm text-gray-500">
                                    {{ rollover.loan.borrower.phone_number }}
                                </div>
                            </div>
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-gray-900">
                            <strong>Amount:</strong> KES {{ rollover.requested_amount|floatformat:2|intcomma }}
                        </div>
                        <div class="text-sm text-gray-500">
                            <strong>Duration:</strong> {{ rollover.requested_duration }} days
                        </div>
                        {% if rollover.rollover_date %}
                        <div class="text-sm text-blue-600">
                            <strong>Requested Date:</strong> {{ rollover.rollover_date|date:"M d, Y" }}
                        </div>
                        {% endif %}
                        {% if rollover.rollover_fee %}
                        <div class="text-sm text-gray-500">
                            <strong>Rollover Fee:</strong> KES {{ rollover.rollover_fee|floatformat:2|intcomma }}
                        </div>
                        {% endif %}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        {% if rollover.requested_interest_rate %}
                        <div class="text-sm text-gray-900">
                            <strong>Interest:</strong> {{ rollover.requested_interest_rate }}%
                        </div>
                        {% else %}
                        <div class="text-sm text-gray-500">Default interest rate</div>
                        {% endif %}
                        
                        {% if rollover.requested_processing_fee %}
                        <div class="text-sm text-gray-900">
                            <strong>Processing Fee:</strong> KES {{ rollover.requested_processing_fee|floatformat:2|intcomma }}
                        </div>
                        {% else %}
                        <div class="text-sm text-gray-500">Default processing fee</div>
                        {% endif %}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full
                            {% 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>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {{ rollover.requested_at|date:"M d, Y H:i" }}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        {% if rollover.status == 'pending' and user.is_admin %}
                        <div class="flex space-x-2">
                            <button onclick="approveRollover('{{ rollover.pk }}')" 
                                    class="inline-flex items-center px-3 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-3 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 %}
                    </td>
                </tr>
                
                <!-- Expandable Reason Row -->
                <tr class="bg-gray-50">
                    <td colspan="7" class="px-6 py-3">
                        <div class="text-sm text-gray-700">
                            <strong>Reason:</strong> {{ rollover.reason }}
                        </div>
                        {% if rollover.review_notes %}
                        <div class="text-sm text-gray-600 mt-2">
                            <strong>Review Notes:</strong> {{ rollover.review_notes }}
                        </div>
                        {% endif %}
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
    
    {% else %}
    <div class="text-center py-12">
        <span>🔄</span>
        <h3 class="text-lg font-medium text-gray-900 mb-2">No rollover requests found</h3>
        <p class="text-gray-500">There are currently no pending rollover requests.</p>
        <div class="mt-6">
            <a href="{% url 'loans:loans' %}" class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary-dark">
                View All Loans
            </a>
        </div>
    </div>
    {% endif %}
</div>

<!-- Approval Modal -->
<div class="modal fade" id="approvalModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="approvalModalTitle">Approve Rollover</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form id="approvalForm" method="post">
                {% csrf_token %}
                <div class="modal-body">
                    <div class="form-group">
                        <label for="disbursement_date">Disbursement Date</label>
                        <input type="date" class="form-control" name="disbursement_date" id="disbursement_date" 
                               value="" 
                               {% if not user.is_admin %}min="{{ today|date:'Y-m-d' }}" {% endif %}>
                        <small class="form-text text-muted">
                            Select the actual date when the loan was/will be disbursed. 
                            Leave blank to use the rollover date from the request.
                            {% if not user.is_admin %}(Admin only can set past dates){% endif %}
                        </small>
                    </div>
                    <div class="form-group">
                        <label for="notes">Notes (Optional)</label>
                        <textarea class="form-control" name="notes" id="notes" rows="3" 
                                placeholder="Add any notes about this decision..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="approvalSubmitBtn">Approve</button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
function approveRollover(rolloverPk) {
    document.getElementById('approvalModalTitle').textContent = 'Approve Rollover';
    document.getElementById('approvalSubmitBtn').textContent = 'Approve';
    document.getElementById('approvalSubmitBtn').className = 'btn btn-success';
    document.getElementById('approvalForm').action = `/loans/rollovers/${rolloverPk}/approve/`;
    
    // Find the rollover row and get the rollover_date
    const rolloverRow = document.querySelector(`tr[data-rollover-id="${rolloverPk}"]`);
    const rolloverDateInput = document.getElementById('disbursement_date');
    
    if (rolloverRow) {
        const rolloverDate = rolloverRow.getAttribute('data-rollover-date');
        if (rolloverDate) {
            rolloverDateInput.value = rolloverDate;
        } else {
            rolloverDateInput.value = '';
        }
    } else {
        rolloverDateInput.value = '';
    }
    
    $('#approvalModal').modal('show');
}

function rejectRollover(rolloverPk) {
    document.getElementById('approvalModalTitle').textContent = 'Reject Rollover';
    document.getElementById('approvalSubmitBtn').textContent = 'Reject';
    document.getElementById('approvalSubmitBtn').className = 'btn btn-danger';
    document.getElementById('approvalForm').action = `/loans/rollovers/${rolloverPk}/reject/`;
    $('#approvalModal').modal('show');
}
</script>
{% endblock %}