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

{% block title %}Payment Receipts{% endblock %}

{% block content %}
<div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <!-- Header -->
        <div class="mb-8">
            <div class="flex justify-between items-center">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900">Payment Receipts</h1>
                    <p class="mt-2 text-gray-600">Manage and view all payment receipts</p>
                </div>
                <div class="text-right">
                    <div class="text-sm text-gray-500">Total Receipts</div>
                    <div class="text-2xl font-bold text-blue-600">{{ receipts.count }}</div>
                </div>
            </div>
        </div>
<div class="card-header">
    <h3 class="card-title">Payment Receipts</h3>
    <div class="card-tools">
        <form method="post" action="{% url 'utils:bulk_generate_receipts' %}" style="display: inline;">
            {% csrf_token %}
            <button type="submit" class="btn btn-warning btn-sm" onclick="return confirm('Generate receipts for all repayments that don\'t have receipts? This may take a few moments.')">
                <i class="fas fa-magic"></i> Generate All Missing Receipts
            </button>
        </form>
    </div>
</div>
        <!-- Filters -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-8">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label for="searchInput" class="block text-sm font-medium text-gray-700 mb-2">Search</label>
                    <input type="text" id="searchInput" placeholder="Search by client, loan number, or receipt..."
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                </div>
                <div>
                    <label for="statusFilter" class="block text-sm font-medium text-gray-700 mb-2">Status</label>
                    <select id="statusFilter"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <option value="">All Statuses</option>
                        <option value="paid">Paid</option>
                        <option value="pending">Pending</option>
                    </select>
                </div>
                <div>
                    <label for="methodFilter" class="block text-sm font-medium text-gray-700 mb-2">Payment Method</label>
                    <select id="methodFilter"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <option value="">All Methods</option>
                        <option value="mpesa">M-Pesa</option>
                        <option value="cash">Cash</option>
                        <option value="bank">Bank Transfer</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Receipts Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {% for receipt in receipts %}
            <div
                class="bg-white rounded-xl shadow-sm border border-gray-200 hover:shadow-lg transition-all duration-300 overflow-hidden">
                <!-- Receipt Header -->
                <div
                    class="{% if receipt.payment_method == 'mpesa' %}bg-gradient-to-r from-green-500 to-green-600{% elif receipt.payment_method == 'bank' %}bg-gradient-to-r from-blue-500 to-blue-600{% elif receipt.payment_method == 'cash' %}bg-gradient-to-r from-yellow-500 to-orange-500{% else %}bg-gradient-to-r from-purple-500 to-purple-600{% endif %} text-white p-6 relative">
                    <div class="flex justify-between items-start">
                        <div>
                            <div class="text-2xl font-bold">KES {{ receipt.amount_paid|floatformat:2 }}</div>
                            <div class="text-sm opacity-90 font-mono">{{ receipt.receipt_number }}</div>
                        </div>
                        <div class="bg-green-100 bg-opacity-20 px-3 py-1 rounded-full text-xs font-semibold text-gray-900">
                            {{ receipt.get_payment_method_display }}
                        </div>
                    </div>
                    <div class="mt-4">
                        <div class="text-sm opacity-90">{{ receipt.payment_date|date:"M d, Y" }}</div>
                        <div class="text-xs opacity-75">{{ receipt.payment_date|time:"g:i A" }}</div>
                    </div>
                </div>

                <!-- Receipt Details -->
                <div class="p-6">
                    <div class="space-y-4">
                        <div>
                            <div class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Client</div>
                            <div class="text-sm text-gray-900">{{ receipt.loan.borrower.get_full_name }}</div>
                        </div>

                        <div>
                            <div class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Loan</div>
                            <div class="text-sm text-gray-900">{{ receipt.loan.loan_number }}</div>
                        </div>

                        {% if receipt.repayment.mpesa_transaction_id %}
                        <div>
                            <div class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">M-Pesa
                                Transaction</div>
                            <div class="text-sm text-gray-900 font-mono">{{ receipt.repayment.mpesa_transaction_id }}</div>
                        </div>
                        {% endif %}

                        {% if receipt.repayment.mpesa_phone_number %}
                        <div>
                            <div class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Phone Number
                            </div>
                            <div class="text-sm text-gray-900">{{ receipt.repayment.mpesa_phone_number }}</div>
                        </div>
                        {% endif %}

                        <!-- Balance Information -->
                        <div class="bg-gray-50 rounded-lg p-4 mt-4">
                            <div class="space-y-2 text-sm">
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Total Loan:</span>
                                    <span class="font-semibold">KES {{ receipt.loan.total_amount|floatformat:2 }}</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Amount Paid:</span>
                                    <span class="font-semibold">KES {{ receipt.amount_paid|floatformat:2 }}</span>
                                </div>
                                <div class="flex justify-between border-t border-gray-200 pt-2">
                                    <span class="text-gray-600">Outstanding:</span>
                                    <span
                                        class="font-bold text-{% if receipt.new_balance > 0 %}red{% else %}green{% endif %}-600">
                                        KES {{ receipt.new_balance|floatformat:2 }}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="px-6 pb-6">
                    <div class="flex flex-wrap gap-2 justify-start">
                        <a href="{% url 'utils:view_receipt' receipt.id %}" target="_blank"
                           class="inline-flex items-center px-2 py-1 bg-blue-600 text-white text-xs rounded-md hover:bg-blue-700 transition-colors">
                            <i class="fas fa-eye mr-1"></i>View
                        </a>
                        
                        <a href="{% url 'utils:view_receipt' receipt.id %}?thermal=true" target="_blank"
                           class="inline-flex items-center px-2 py-1 bg-green-600 text-white text-xs rounded-md hover:bg-green-700 transition-colors">
                            <span>🖨️</span>Thermal
                        </a>
                        
                        <a href="{% url 'utils:download_receipt' receipt.id %}"
                           class="inline-flex items-center px-2 py-1 bg-purple-600 text-white text-xs rounded-md hover:bg-purple-700 transition-colors">
                            <span>⬇️</span>Download
                        </a>
                        
                        {% if user.is_staff %}
                            <a href="{% url 'utils:edit_receipt' receipt.id %}"
                               class="inline-flex items-center px-2 py-1 bg-yellow-600 text-white text-xs rounded-md hover:bg-yellow-700 transition-colors">
                                <span>✏️</span>Edit
                            </a>
                            
                            <button onclick="deleteReceipt('{{ receipt.id }}', '{{ receipt.receipt_number }}')"
                                    class="inline-flex items-center px-2 py-1 bg-red-600 text-white text-xs rounded-md hover:bg-red-700 transition-colors">
                                <span>🗑️</span>Delete
                            </button>
                        {% endif %}
                    </div>
                </div>
            </div>
            {% empty %}
            <div class="col-span-full">
                <div class="text-center py-12">
                    <div class="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <span>🧾</span>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-900 mb-2">No receipts found</h3>
                    <p class="text-gray-600">There are no payment receipts to display.</p>
                </div>
            </div>
            {% endfor %}
        </div>

        <!-- Pagination -->
        {% if is_paginated %}
        <div class="mt-8 flex justify-center">
            <nav class="flex items-center space-x-2">
                {% if page_obj.has_previous %}
                <a href="?page=1"
                    class="px-3 py-2 text-sm font-medium text-gray-500 hover:text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50">
                    First
                </a>
                <a href="?page={{ page_obj.previous_page_number }}"
                    class="px-3 py-2 text-sm font-medium text-gray-500 hover:text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50">
                    Previous
                </a>
                {% endif %}

                <span class="px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md">
                    Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
                </span>

                {% if page_obj.has_next %}
                <a href="?page={{ page_obj.next_page_number }}"
                    class="px-3 py-2 text-sm font-medium text-gray-500 hover:text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50">
                    Next
                </a>
                <a href="?page={{ page_obj.paginator.num_pages }}"
                    class="px-3 py-2 text-sm font-medium text-gray-500 hover:text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50">
                    Last
                </a>
                {% endif %}
            </nav>
        </div>
        {% endif %}
    </div>
</div>

<!-- Hidden form for CSRF token -->
<form id="csrf-form" style="display: none;">
    {% csrf_token %}
</form>

<script>
    // Search functionality
    document.getElementById('searchInput').addEventListener('input', function () {
        const searchTerm = this.value.toLowerCase();
        const cards = document.querySelectorAll('.grid > div');

        cards.forEach(card => {
            const text = card.textContent.toLowerCase();
            if (text.includes(searchTerm)) {
                card.style.display = 'block';
            } else {
                card.style.display = 'none';
            }
        });
    });

    // Filter functionality
    document.getElementById('statusFilter').addEventListener('change', function () {
        // Add status filtering logic here
    });

    document.getElementById('methodFilter').addEventListener('change', function () {
        const selectedMethod = this.value.toLowerCase();
        const cards = document.querySelectorAll('.grid > div');

        cards.forEach(card => {
            if (!selectedMethod) {
                card.style.display = 'block';
            } else {
                const methodText = card.textContent.toLowerCase();
                if (methodText.includes(selectedMethod)) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            }
        });
    });

    // Delete receipt functionality
    function deleteReceipt(receiptId, receiptNumber) {
        if (confirm(`Are you sure you want to delete receipt ${receiptNumber}? This action cannot be undone and will also delete the associated repayment.`)) {
            // Create a form and submit it
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = `/utils/receipt/${receiptId}/delete/`;
            
            // Get CSRF token from the hidden form
            const csrfToken = document.querySelector('#csrf-form input[name="csrfmiddlewaretoken"]').value;
            
            // Add CSRF token
            const csrfInput = document.createElement('input');
            csrfInput.type = 'hidden';
            csrfInput.name = 'csrfmiddlewaretoken';
            csrfInput.value = csrfToken;
            form.appendChild(csrfInput);
            
            document.body.appendChild(form);
            form.submit();
        }
    }
</script>
{% endblock %}
