<!-- Enhanced Penalty Charges Section -->
<div class="mt-8">
    <div class="rounded-lg bg-white shadow">
        <div class="px-4 py-5 sm:px-6 flex justify-between items-center">
            <div>
                <h3 class="text-lg font-medium leading-6 text-gray-900">Penalty Charges</h3>
                <p class="mt-1 text-sm text-gray-500">
                    Penalties applied for late payments
                </p>
            </div>
            {% if user.is_staff %}
            <div class="flex gap-2">
                {% if is_overdue %}
                <button type="button" 
                        onclick="showApplyPenaltyModal()"
                        class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-red-600 hover:bg-red-700">
                    <span>⚠️</span> Apply Penalty
                </button>
                {% endif %}
            </div>
            {% endif %}
        </div>
        
        <!-- Penalty Summary -->
        <div class="border-t border-gray-200 px-4 py-4 bg-gray-50">
            <dl class="grid grid-cols-1 gap-4 sm:grid-cols-3">
                <div>
                    <dt class="text-sm font-medium text-gray-500">Total Penalties</dt>
                    <dd class="mt-1 text-2xl font-semibold text-red-600">KES {{ total_penalties|floatformat:2 }}</dd>
                </div>
                <div>
                    <dt class="text-sm font-medium text-gray-500">Penalty Rate</dt>
                    <dd class="mt-1 text-lg font-medium text-gray-900">
                        {{ penalty_rate }}% (monthly)
                    </dd>
                </div>
                {% if is_overdue %}
                <div>
                    <dt class="text-sm font-medium text-gray-500">Suggested Penalty</dt>
                    <dd class="mt-1 text-lg font-medium text-orange-600">
                        KES {{ current_penalty|floatformat:2 }}
                        <span class="text-sm text-gray-500">({{ days_overdue }} days overdue)</span>
                    </dd>
                </div>
                {% endif %}
            </dl>
        </div>
        
        <!-- Penalty List -->
        {% if penalty_charges %}
        <div class="border-t border-gray-200">
            <div class="flow-root">
                <ul role="list" class="divide-y divide-gray-200">
                    {% for penalty in penalty_charges %}
                    <li class="px-4 py-4 sm:px-6 hover:bg-gray-50">
                        <div class="flex items-center justify-between">
                            <div class="flex flex-col flex-1">
                                <div class="flex items-center">
                                    <p class="text-sm font-medium text-red-600">
                                        KES {{ penalty.amount|floatformat:2 }}
                                    </p>
                                    {% if penalty.is_automatic %}
                                    <span class="ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">
                                        <span>🤖</span> Auto
                                    </span>
                                    {% else %}
                                    <span class="ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-800">
                                        <span>👤</span> Manual
                                    </span>
                                    {% endif %}
                                </div>
                                <p class="text-sm text-gray-500 mt-1">
                                    {{ penalty.penalty_rate }}% rate for {{ penalty.days_overdue }} days overdue
                                </p>
                                <p class="text-sm text-gray-500">
                                    Outstanding: KES {{ penalty.outstanding_amount|floatformat:2 }}
                                </p>
                                {% if penalty.penalty_date %}
                                <p class="text-sm text-gray-500">
                                    <span>📅</span> Penalty Date: {{ penalty.penalty_date|date:"M d, Y" }}
                                </p>
                                {% endif %}
                                {% if not penalty.is_automatic and penalty.applied_by %}
                                <p class="text-xs text-gray-400 mt-1">
                                    Applied by: {{ penalty.applied_by.get_full_name }}
                                </p>
                                {% endif %}
                            </div>
                            <div class="flex flex-col items-end">
                                <p class="text-sm text-gray-500">
                                    {{ penalty.applied_date|date:"M d, Y" }}
                                </p>
                                <p class="text-xs text-gray-400">
                                    {{ penalty.applied_date|time:"H:i" }}
                                </p>
                                {% if user.is_staff and not penalty.is_automatic %}
                                <form method="post" action="{% url 'loans:delete_penalty' penalty.id %}" 
                                      onsubmit="return confirm('Are you sure you want to delete this penalty?');"
                                      class="mt-2">
                                    {% csrf_token %}
                                    <button type="submit" 
                                            class="inline-flex items-center px-2 py-1 border border-transparent text-xs font-medium rounded text-red-700 bg-red-100 hover:bg-red-200">
                                        <span>🗑️</span> Delete
                                    </button>
                                </form>
                                {% endif %}
                            </div>
                        </div>
                    </li>
                    {% endfor %}
                </ul>
            </div>
        </div>
        {% else %}
        <div class="border-t border-gray-200 px-4 py-8 text-center">
            <p class="text-sm text-gray-500">No penalties applied yet.</p>
            {% if is_overdue and user.is_staff %}
            <button type="button" 
                    onclick="showApplyPenaltyModal()"
                    class="mt-4 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-red-600 hover:bg-red-700">
                <span>⚠️</span> Apply First Penalty
            </button>
            {% endif %}
        </div>
        {% endif %}
    </div>
</div>

<!-- Apply Penalty Modal -->
<div id="applyPenaltyModal" class="hidden fixed z-10 inset-0 overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true" onclick="hideApplyPenaltyModal()"></div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <form method="post" action="{% url 'loans:apply_manual_penalty' loan.id %}">
                {% csrf_token %}
                <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <div class="sm:flex sm:items-start">
                        <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                            <span class="text-2xl">⚠️</span>
                        </div>
                        <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left flex-1">
                            <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">
                                Apply Manual Penalty
                            </h3>
                            <div class="mt-4">
                                <!-- Success/Error Messages -->
                                <div id="penaltyFormMessages" class="mb-4 hidden"></div>
                                
                                <div class="mb-4 p-3 bg-yellow-50 border border-yellow-200 rounded">
                                    <p class="text-sm text-yellow-800">
                                        <strong>Loan:</strong> {{ loan.loan_number }}<br>
                                        <strong>Days Overdue:</strong> {{ days_overdue }}<br>
                                        <strong>Outstanding:</strong> KES {{ loan.outstanding_amount|floatformat:2 }}<br>
                                        <strong>Suggested Penalty:</strong> KES {{ current_penalty|floatformat:2 }}
                                    </p>
                                </div>
                                
                                <div class="mb-4">
                                    <label for="penalty_amount" class="block text-sm font-medium text-gray-700">
                                        Penalty Amount (KES) <span class="text-red-500">*</span>
                                    </label>
                                    <input type="number" 
                                           name="penalty_amount" 
                                           id="penalty_amount" 
                                           step="0.01" 
                                           min="0.01"
                                           value="{{ current_penalty }}"
                                           required
                                           class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-red-500 focus:border-red-500 sm:text-sm">
                                </div>
                                
                                <div class="mb-4">
                                    <label for="penalty_date" class="block text-sm font-medium text-gray-700">
                                        Penalty Date <span class="text-red-500">*</span>
                                    </label>
                                    <input type="date" 
                                           name="penalty_date" 
                                           id="penalty_date" 
                                           value="{% now 'Y-m-d' %}"
                                           max="{% now 'Y-m-d' %}"
                                           required
                                           class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-red-500 focus:border-red-500 sm:text-sm">
                                    <p class="mt-1 text-xs text-gray-500">Date the penalty applies to (cannot be in the future)</p>
                                </div>
                                
                                <div class="mb-4">
                                    <label for="reason" class="block text-sm font-medium text-gray-700">
                                        Reason <span class="text-red-500">*</span>
                                    </label>
                                    <textarea name="reason" 
                                              id="reason" 
                                              rows="3" 
                                              required
                                              placeholder="e.g., Late payment penalty for {{ days_overdue }} days overdue"
                                              class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-red-500 focus:border-red-500 sm:text-sm"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="submit" 
                            class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">
                        Apply Penalty
                    </button>
                    <button type="button" 
                            onclick="hideApplyPenaltyModal()"
                            class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                        Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function showApplyPenaltyModal() {
    document.getElementById('applyPenaltyModal').classList.remove('hidden');
    // Clear any previous messages
    const messagesDiv = document.getElementById('penaltyFormMessages');
    if (messagesDiv) {
        messagesDiv.classList.add('hidden');
        messagesDiv.innerHTML = '';
    }
}

function hideApplyPenaltyModal() {
    document.getElementById('applyPenaltyModal').classList.add('hidden');
}

// Handle form submission with AJAX
document.addEventListener('DOMContentLoaded', function() {
    const penaltyForm = document.querySelector('#applyPenaltyModal form');
    if (penaltyForm) {
        penaltyForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitButton = this.querySelector('button[type="submit"]');
            const messagesDiv = document.getElementById('penaltyFormMessages');
            
            // Disable submit button
            submitButton.disabled = true;
            submitButton.textContent = 'Applying...';
            
            // Clear previous messages
            messagesDiv.classList.add('hidden');
            messagesDiv.innerHTML = '';
            
            fetch(this.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': formData.get('csrfmiddlewaretoken')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success message
                    messagesDiv.innerHTML = `
                        <div class="p-3 bg-green-50 border border-green-200 rounded">
                            <p class="text-sm text-green-800">✓ ${data.message}</p>
                        </div>
                    `;
                    messagesDiv.classList.remove('hidden');
                    
                    // Reload page after 1.5 seconds to show updated penalties
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    // Show error message
                    messagesDiv.innerHTML = `
                        <div class="p-3 bg-red-50 border border-red-200 rounded">
                            <p class="text-sm text-red-800">✗ ${data.error}</p>
                        </div>
                    `;
                    messagesDiv.classList.remove('hidden');
                    
                    // Re-enable submit button
                    submitButton.disabled = false;
                    submitButton.textContent = 'Apply Penalty';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                messagesDiv.innerHTML = `
                    <div class="p-3 bg-red-50 border border-red-200 rounded">
                        <p class="text-sm text-red-800">✗ An error occurred. Please try again.</p>
                    </div>
                `;
                messagesDiv.classList.remove('hidden');
                
                // Re-enable submit button
                submitButton.disabled = false;
                submitButton.textContent = 'Apply Penalty';
            });
        });
    }
});
</script>
