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

{% block content %}
<div class="container mx-auto px-4 py-8">
    <div class="bg-white shadow overflow-hidden sm:rounded-lg">
        <!-- Client Info Header -->
        <div class="px-4 py-5 sm:px-6">
            <div class="flex justify-between items-center">
                <div>
            <h3 class="text-lg leading-6 font-medium text-gray-900">Client Information</h3>
                    <p class="mt-1 max-w-2xl text-sm text-gray-500">Personal and account details for {{ client.get_full_name }}</p>
                </div>
                <div class="flex space-x-2">
                    <a href="{% url 'users:client_complete_history' client.id %}" 
                       class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700">
                        <i class="fas fa-history mr-2"></i>
                        Complete History
                    </a>
                    <a href="{% url 'loans:new_application' %}?client_id={{ client.id }}" 
                       class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700">
                        <span>+</span>
                        New Loan
                    </a>
                    <a href="{% url 'users:client_update' client.id %}" 
                       class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50">
                        <span>✏️</span>
                        Edit Client
                    </a>
                </div>
            </div>
        </div>

        <!-- Tabs -->
        <div class="border-b border-gray-200">
            <nav class="-mb-px flex" aria-label="Tabs">
                <button class="tab-button w-1/5 py-4 px-1 text-center border-b-2 font-medium text-sm border-indigo-500 text-indigo-600" 
                        data-tab="details">Details</button>
                <button class="tab-button w-1/5 py-4 px-1 text-center border-b-2 font-medium text-sm border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                        data-tab="loans">Loans</button>
                <button class="tab-button w-1/5 py-4 px-1 text-center border-b-2 font-medium text-sm border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                        data-tab="payments">Payments</button>
                <button class="tab-button w-1/5 py-4 px-1 text-center border-b-2 font-medium text-sm border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                        data-tab="documents">Documents</button>
                <button class="tab-button w-1/5 py-4 px-1 text-center border-b-2 font-medium text-sm border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                        data-tab="reports">Reports</button>
            </nav>
        </div>

        <!-- Details Tab -->
        <div id="details" class="tab-content p-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Personal Information -->
                <div class="bg-gray-50 p-4 rounded-lg">
                    <h4 class="text-lg font-medium text-gray-900 mb-4">Personal Information</h4>
                    <dl class="space-y-3">
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Full Name</dt>
                            <dd class="text-sm text-gray-900">{{ client.get_full_name }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Email</dt>
                            <dd class="text-sm text-gray-900">{{ client.email }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Phone Number</dt>
                            <dd class="text-sm text-gray-900">{{ client.phone_number }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Date of Birth</dt>
                            <dd class="text-sm text-gray-900">{{ client.date_of_birth|date:"F j, Y"|default:"Not provided" }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Gender</dt>
                            <dd class="text-sm text-gray-900">{{ client.get_gender_display|default:"Not provided" }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">ID Number</dt>
                            <dd class="text-sm text-gray-900">{{ client.id_number|default:"Not provided" }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Nationality</dt>
                            <dd class="text-sm text-gray-900">{{ client.nationality|default:"Not provided" }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Marital Status</dt>
                            <dd class="text-sm text-gray-900">{{ client.get_marital_status_display|default:"Not provided" }}</dd>
                        </div>
                    </dl>
                </div>

                <!-- Business Information -->
                <div class="bg-gray-50 p-4 rounded-lg">
                    <h4 class="text-lg font-medium text-gray-900 mb-4">Business Information</h4>
                    <dl class="space-y-3">
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Business Name</dt>
                            <dd class="text-sm text-gray-900">{{ client.business_name|default:"Not provided" }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Business Type</dt>
                            <dd class="text-sm text-gray-900">{{ client.get_business_type_display|default:"Not provided" }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Monthly Income</dt>
                            <dd class="text-sm text-gray-900">KES {{ client.monthly_income|floatformat:2|default:"Not provided" }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Employer</dt>
                            <dd class="text-sm text-gray-900">{{ client.employer|default:"Not provided" }}</dd>
                        </div>
                    </dl>
                </div>

                <!-- Address Information -->
                <div class="bg-gray-50 p-4 rounded-lg md:col-span-2">
                    <h4 class="text-lg font-medium text-gray-900 mb-4">Address Information</h4>
                    <dl class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Address</dt>
                            <dd class="text-sm text-gray-900">{{ client.physical_address|default:"Not provided" }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">City</dt>
                            <dd class="text-sm text-gray-900">{{ client.city|default:"Not provided" }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">County</dt>
                            <dd class="text-sm text-gray-900">{{ client.county|default:"Not provided" }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Postal Code</dt>
                            <dd class="text-sm text-gray-900">{{ client.postal_code|default:"Not provided" }}</dd>
                        </div>
                    </dl>
                </div>

                <!-- Account Status -->
                <div class="bg-gray-50 p-4 rounded-lg md:col-span-2">
                    <h4 class="text-lg font-medium text-gray-900 mb-4">Account Status</h4>
                    <dl class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Status</dt>
                            <dd class="text-sm">
                                <span class="px-2 py-1 text-xs font-medium rounded-full 
                                    {% if client.status == 'active' %}bg-green-100 text-green-800
                                    {% elif client.status == 'suspended' %}bg-yellow-100 text-yellow-800
                                    {% elif client.status == 'blacklisted' %}bg-red-100 text-red-800
                                    {% else %}bg-gray-100 text-gray-800{% endif %}">
                                    {{ client.get_status_display }}
                                </span>
                            </dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Credit Score</dt>
                            <dd class="text-sm text-gray-900">
                                {% if credit_score %}
                                    <span class="px-2 py-1 text-xs font-medium rounded-full 
                                        {% if credit_score.score >= 80 %}bg-green-100 text-green-800
                                        {% elif credit_score.score >= 60 %}bg-yellow-100 text-yellow-800
                                        {% else %}bg-red-100 text-red-800{% endif %}">
                                        {{ credit_score.score }}/100
                                    </span>
                                {% else %}
                                    <span class="text-gray-500">Not available</span>
                                {% endif %}
                            </dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">Member Since</dt>
                            <dd class="text-sm text-gray-900">{{ client.date_joined|date:"F j, Y" }}</dd>
                        </div>
                    </dl>
                </div>
            </div>
        </div>

        <!-- Loans Tab -->
        <div id="loans" class="tab-content hidden p-4">
            <div class="mb-4 flex justify-between items-center">
                <h3 class="text-lg font-medium text-gray-900">Loan History</h3>
                <div class="flex space-x-2">
                    <a href="{% url 'loans:new_application' %}?client_id={{ client.id }}" 
                       class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700">
                        <span>+</span>
                        New Loan Application
                    </a>
                </div>
            </div>

            <!-- Enhanced Loan Statistics -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                <div class="bg-white rounded-lg shadow p-4">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <span>💵</span>
                        </div>
                        <div class="ml-3">
                            <h4 class="text-sm font-medium text-gray-500">Total Borrowed</h4>
                            <p class="text-xl font-bold text-gray-900">KES {{ total_borrowed|floatformat:2 }}</p>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow p-4">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <span>💰</span>
                        </div>
                        <div class="ml-3">
                            <h4 class="text-sm font-medium text-gray-500">Total Repaid</h4>
                            <p class="text-xl font-bold text-gray-900">KES {{ total_repaid|floatformat:2 }}</p>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow p-4">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <span>⚠️</span>
                        </div>
                        <div class="ml-3">
                            <h4 class="text-sm font-medium text-gray-500">Outstanding</h4>
                            <p class="text-xl font-bold {% if total_outstanding > 0 %}text-orange-600{% else %}text-gray-900{% endif %}">KES {{ total_outstanding|floatformat:2 }}</p>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow p-4">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <span>📈</span>
                        </div>
                        <div class="ml-3">
                            <h4 class="text-sm font-medium text-gray-500">Payment Performance</h4>
                            <p class="text-xl font-bold {% if payment_performance >= 80 %}text-green-600{% elif payment_performance >= 60 %}text-yellow-600{% else %}text-red-600{% endif %}">{{ payment_performance|floatformat:1 }}%</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Loan Status Summary -->
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                <div class="bg-green-50 rounded-lg p-4 text-center">
                    <div class="text-2xl font-bold text-green-600">{{ active_loans }}</div>
                    <div class="text-sm text-green-700">Active Loans</div>
                </div>
                <div class="bg-blue-50 rounded-lg p-4 text-center">
                    <div class="text-2xl font-bold text-blue-600">{{ paid_loans }}</div>
                    <div class="text-sm text-blue-700">Paid Loans</div>
                </div>
                <div class="bg-red-50 rounded-lg p-4 text-center">
                    <div class="text-2xl font-bold text-red-600">{{ overdue_count }}</div>
                    <div class="text-sm text-red-700">Overdue Loans</div>
                </div>
                <div class="bg-yellow-50 rounded-lg p-4 text-center">
                    <div class="text-2xl font-bold text-yellow-600">{{ rolled_over_loans }}</div>
                    <div class="text-sm text-yellow-700">Rolled Over</div>
                </div>
            </div>

            <!-- Loan Applications -->
            <div class="bg-white shadow rounded-lg">
                <div class="px-4 py-5 sm:p-6">
                    <h4 class="text-lg font-medium text-gray-900 mb-4">Recent Applications</h4>
                    {% if applications %}
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Application</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Product</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Amount</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Duration</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    {% for application in applications %}
                                    <tr class="hover:bg-gray-50">
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                            {{ application.application_number }}
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <div>
                                                <div class="font-medium">{{ application.loan_product.name }}</div>
                                                <div class="text-xs text-gray-500">{{ application.loan_product.get_product_type_display }}</div>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <div>
                                                <div class="font-medium">KES {{ application.requested_amount|floatformat:2 }}</div>
                                                {% if application.total_amount %}
                                                <div class="text-xs text-gray-500">Total: KES {{ application.total_amount|floatformat:2 }}</div>
                                                {% endif %}
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            {{ application.requested_duration }} days
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="px-2 py-1 text-xs font-medium rounded-full 
                                                {% if application.status == 'approved' %}bg-green-100 text-green-800
                                                {% elif application.status == 'disbursed' %}bg-blue-100 text-blue-800
                                                {% elif application.status == 'pending' %}bg-yellow-100 text-yellow-800
                                                {% elif application.status == 'under_review' %}bg-purple-100 text-purple-800
                                                {% elif application.status == 'rejected' %}bg-red-100 text-red-800
                                                {% else %}bg-gray-100 text-gray-800{% endif %}">
                                                {{ application.get_status_display }}
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            {{ application.submitted_at|date:"M j, Y" }}
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            {% if request.user.is_staff %}
                                            <a href="{% url 'loans:application_detail' application.id %}" 
                                               class="text-indigo-600 hover:text-indigo-900">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <p class="text-gray-500 text-center py-8">No loan applications found.</p>
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- Payments Tab -->
        <div id="payments" class="tab-content hidden p-4">
            <div class="mb-4 flex justify-between items-center">
                <h3 class="text-lg font-medium text-gray-900">Payment History</h3>
                <div class="flex space-x-2">
                    {% if request.user.is_staff %}
                    <a href="{% url 'loans:new_repayment' %}" 
                       class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700">
                        <span>+</span>
                        Add Payment
                    </a>
                    {% endif %}
                </div>
            </div>

            <!-- Payment Summary -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div class="bg-white rounded-lg shadow p-4">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <i class="fas fa-calendar-check text-2xl text-green-500"></i>
                        </div>
                        <div class="ml-3">
                            <h4 class="text-sm font-medium text-gray-500">Last Payment</h4>
                            <p class="text-sm font-bold text-gray-900">
                                {% if last_payment %}
                                    {{ last_payment.payment_date|date:"M j, Y" }}
                                    <br><span class="text-green-600">KES {{ last_payment.amount|floatformat:2 }}</span>
                                {% else %}
                                    <span class="text-gray-500">No payments yet</span>
                                {% endif %}
                            </p>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow p-4">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <span>⏰</span>
                        </div>
                        <div class="ml-3">
                            <h4 class="text-sm font-medium text-gray-500">Overdue Amount</h4>
                            <p class="text-sm font-bold {% if overdue_count > 0 %}text-red-600{% else %}text-gray-900{% endif %}">
                                KES {{ total_overdue_amount|floatformat:2 }}
                                {% if overdue_count > 0 %}
                                    <br><span class="text-xs text-red-500">{{ overdue_count }} loan{{ overdue_count|pluralize }}</span>
                                {% endif %}
                            </p>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow p-4">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <i class="fas fa-percentage text-2xl {% if payment_performance >= 80 %}text-green-500{% elif payment_performance >= 60 %}text-yellow-500{% else %}text-red-500{% endif %}"></i>
                        </div>
                        <div class="ml-3">
                            <h4 class="text-sm font-medium text-gray-500">Payment Rate</h4>
                            <p class="text-sm font-bold {% if payment_performance >= 80 %}text-green-600{% elif payment_performance >= 60 %}text-yellow-600{% else %}text-red-600{% endif %}">
                                {{ payment_performance|floatformat:1 }}%
                                <br><span class="text-xs text-gray-500">On-time payments</span>
                            </p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent Payments Table -->
            <div class="bg-white shadow rounded-lg">
                <div class="px-4 py-5 sm:p-6">
                    <h4 class="text-lg font-medium text-gray-900 mb-4">Recent Payments</h4>
                    {% if recent_repayments %}
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Receipt</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Loan</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Amount</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Method</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    {% for payment in recent_repayments %}
                                    <tr class="hover:bg-gray-50">
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                            {{ payment.receipt_number }}
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            {{ payment.loan.loan_number }}
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <span class="font-medium text-green-600">KES {{ payment.amount|floatformat:2 }}</span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <span class="px-2 py-1 text-xs font-medium rounded-full 
                                                {% if payment.payment_method == 'mpesa' %}bg-green-100 text-green-800
                                                {% elif payment.payment_method == 'bank' %}bg-blue-100 text-blue-800
                                                {% elif payment.payment_method == 'cash' %}bg-yellow-100 text-yellow-800
                                                {% else %}bg-gray-100 text-gray-800{% endif %}">
                                                {{ payment.get_payment_method_display }}
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            {{ payment.payment_date|date:"M j, Y g:i A" }}
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            {% if request.user.is_staff %}
                                            <a href="{% url 'loans:edit_repayment' payment.id %}" 
                                               class="text-indigo-600 hover:text-indigo-900 mr-3" title="Edit Payment">
                                                <span>✏️</span>
                                            </a>
                                            <button onclick="deletePayment('{{ payment.id }}', '{{ payment.receipt_number }}')" 
                                                    class="text-red-600 hover:text-red-900 mr-3" title="Delete Payment">
                                                <span>🗑️</span>
                                            </button>
                                            {% endif %}
                                            <button onclick="viewReceipt('{{ payment.receipt_number }}')" 
                                                    class="text-green-600 hover:text-green-900" title="View Receipt">
                                                <span>🧾</span>
                                            </button>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                        {% if recent_repayments.count >= 10 %}
                        <div class="mt-4 text-center">
                            <a href="{% url 'utils:receipts_list' %}?client={{ client.id }}" 
                               class="text-indigo-600 hover:text-indigo-900 text-sm font-medium">
                                View All Payments <span>→</span>
                            </a>
                        </div>
                        {% endif %}
                    {% else %}
                        <div class="text-center py-8">
                            <span>🧾</span>
                            <p class="text-gray-500">No payments found for this client.</p>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- Documents Tab -->
        <div id="documents" class="tab-content hidden p-4">
            <div class="mb-4 flex justify-between items-center">
                <h3 class="text-lg font-medium text-gray-900">Client Documents</h3>
                <div class="flex space-x-2">
                    <a href="{% url 'users:client_documents' client.id %}" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-primary hover:bg-opacity-90">
                        <span>📂</span>
                        View All Documents
                    </a>
                    <button onclick="uploadDocument()" class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50">
                        <span>⬆️</span>
                        Upload New
                    </button>
                </div>
            </div>

            <!-- Document Summary -->
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <!-- ID Document -->
                <div class="bg-white rounded-lg shadow overflow-hidden">
                    <div class="p-4">
                        <div class="flex items-center justify-between mb-4">
                            <h4 class="text-lg font-medium text-gray-900">
                                <span>🪪</span>
                                National ID
                            </h4>
                            <span class="text-sm text-gray-500">{{ id_documents.count }} files</span>
                        </div>
                        <p class="text-sm text-gray-500">Front and back scanned copies</p>
                        <div class="mt-4">
                            <a href="{% url 'users:client_documents' client.id %}#id-documents" class="text-primary hover:text-opacity-80 text-sm font-medium">
                                View Documents <span>→</span>
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Selfie -->
                <div class="bg-white rounded-lg shadow overflow-hidden">
                    <div class="p-4">
                        <div class="flex items-center justify-between mb-4">
                            <h4 class="text-lg font-medium text-gray-900">
                                <span>📷</span>
                                Selfie Photo
                            </h4>
                            <span class="text-sm text-gray-500">{{ selfie_documents.count }} files</span>
                        </div>
                        <p class="text-sm text-gray-500">Recent photo for verification</p>
                        <div class="mt-4">
                            <a href="{% url 'users:client_documents' client.id %}#selfie" class="text-primary hover:text-opacity-80 text-sm font-medium">
                                View Documents <span>→</span>
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Utility Bill -->
                <div class="bg-white rounded-lg shadow overflow-hidden">
                    <div class="p-4">
                        <div class="flex items-center justify-between mb-4">
                            <h4 class="text-lg font-medium text-gray-900">
                                <span>🧾</span>
                                Utility Bill
                            </h4>
                            <span class="text-sm text-gray-500">{{ utility_documents.count }} files</span>
                        </div>
                        <p class="text-sm text-gray-500">Recent utility bill for address verification</p>
                        <div class="mt-4">
                            <a href="{% url 'users:client_documents' client.id %}#utility-bill" class="text-primary hover:text-opacity-80 text-sm font-medium">
                                View Documents <span>→</span>
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Bank Statement -->
                <div class="bg-white rounded-lg shadow overflow-hidden">
                    <div class="p-4">
                        <div class="flex items-center justify-between mb-4">
                            <h4 class="text-lg font-medium text-gray-900">
                                <i class="fas fa-university text-primary mr-2"></i>
                                Bank Statement
                            </h4>
                            <span class="text-sm text-gray-500">{{ bank_documents.count }} files</span>
                        </div>
                        <p class="text-sm text-gray-500">Last 6 months bank statement</p>
                        <div class="mt-4">
                            <a href="{% url 'users:client_documents' client.id %}#bank-statement" class="text-primary hover:text-opacity-80 text-sm font-medium">
                                View Documents <span>→</span>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Reports Tab -->
        <div id="reports" class="tab-content hidden p-4">
            <div class="mb-4 flex justify-between items-center">
                <h3 class="text-lg font-medium text-gray-900">Client Reports</h3>
                <div class="flex space-x-2">
                    <button onclick="downloadClientReport('pdf')" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700">
                        <span>📄</span>
                        Download PDF
                    </button>
                    <button onclick="downloadClientReport('csv')" class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50">
                        <i class="fas fa-file-csv mr-2"></i>
                        Download CSV
                    </button>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <!-- Loan History -->
                <div class="bg-white rounded-lg shadow p-4">
                    <h4 class="text-lg font-medium text-gray-900 mb-4">Loan History</h4>
                    <div id="loanHistoryChart" class="h-64 flex items-center justify-center text-gray-500">
                        Chart will be loaded here
                    </div>
                </div>

                <!-- Credit Score -->
                <div class="bg-white rounded-lg shadow p-4">
                    <h4 class="text-lg font-medium text-gray-900 mb-4">Credit Score History</h4>
                    <div id="creditScoreChart" class="h-64 flex items-center justify-center text-gray-500">
                        Chart will be loaded here
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // Add client ID for API calls
    const clientId = '{{ client.id }}';

    // Tab switching logic
    document.querySelectorAll('.tab-button').forEach(button => {
        button.addEventListener('click', () => {
            // Remove active class from all buttons and content
            document.querySelectorAll('.tab-button').forEach(b => {
                b.classList.remove('border-indigo-500', 'text-indigo-600');
                b.classList.add('border-transparent', 'text-gray-500', 'hover:text-gray-700', 'hover:border-gray-300');
            });
            document.querySelectorAll('.tab-content').forEach(c => c.classList.add('hidden'));

            // Add active class to clicked button and show content
            button.classList.remove('border-transparent', 'text-gray-500', 'hover:text-gray-700', 'hover:border-gray-300');
            button.classList.add('border-indigo-500', 'text-indigo-600');
            document.getElementById(button.dataset.tab).classList.remove('hidden');

            // Load charts if reports tab is selected
            if (button.dataset.tab === 'reports') {
                loadCharts();
            }
        });
    });

    function downloadClientReport(format) {
        // Create a simple report download
        const reportData = {
            clientName: '{{ client.get_full_name }}',
            email: '{{ client.email }}',
            phone: '{{ client.phone_number }}',
            totalBorrowed: '{{ total_borrowed|floatformat:2 }}',
            totalRepaid: '{{ total_repaid|floatformat:2 }}',
            activeLoans: '{{ active_loans }}',
            creditScore: '{% if credit_score %}{{ credit_score.score }}{% else %}N/A{% endif %}'
        };

        if (format === 'pdf') {
            // For now, just show an alert. In production, this would generate a PDF
            alert('PDF report generation would be implemented here');
        } else {
            // Generate CSV
            const csvContent = `Client Name,Email,Phone,Total Borrowed,Total Repaid,Active Loans,Credit Score\n${reportData.clientName},${reportData.email},${reportData.phone},${reportData.totalBorrowed},${reportData.totalRepaid},${reportData.activeLoans},${reportData.creditScore}`;
            const blob = new Blob([csvContent], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `client_report_${clientId}.csv`;
            a.click();
            window.URL.revokeObjectURL(url);
        }
    }

    function uploadDocument() {
        // Implement document upload functionality
        alert('Document upload functionality would be implemented here');
    }

    function loadCharts() {
        // Simple chart implementation - in production, you'd load real data
        const loanHistoryChart = document.getElementById('loanHistoryChart');
        const creditScoreChart = document.getElementById('creditScoreChart');
        
        loanHistoryChart.innerHTML = '<div class="text-center"><span>📈</span><p class="text-sm text-gray-500">Loan history chart would be displayed here</p></div>';
        creditScoreChart.innerHTML = '<div class="text-center"><span>📊</span><p class="text-sm text-gray-500">Credit score chart would be displayed here</p></div>';
    }

    function viewReceipt(receiptNumber) {
        // Open receipt in new window/tab
        const receiptUrl = `/utils/receipts/?search=${receiptNumber}`;
        window.open(receiptUrl, '_blank');
    }

    let paymentToDelete = null;

    function deletePayment(paymentId, receiptNumber) {
        paymentToDelete = paymentId;
        document.getElementById('deleteReceiptNumber').textContent = receiptNumber;
        document.getElementById('deletePaymentModal').classList.remove('hidden');
    }

    function hideDeletePaymentModal() {
        document.getElementById('deletePaymentModal').classList.add('hidden');
        paymentToDelete = null;
    }

    function confirmDeletePayment() {
        if (paymentToDelete) {
            // Redirect to custom delete page
            window.location.href = `/loans/repayments/${paymentToDelete}/delete/`;
        }
    }
</script>

<!-- Delete Payment Modal -->
<div id="deletePaymentModal" 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">
                <div class="sm:flex sm:items-start">
                    <div class="mx-auto flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                        <span>⚠️</span>
                    </div>
                    <div class="mt-3 text-center sm:ml-4 sm:mt-0 sm:text-left">
                        <h3 class="text-base font-semibold leading-6 text-gray-900">Delete Payment</h3>
                        <div class="mt-2">
                            <p class="text-sm text-gray-500">
                                Are you sure you want to delete payment <span id="deleteReceiptNumber" class="font-medium"></span>? 
                                This action cannot be undone and will update the loan balance.
                            </p>
                        </div>
                    </div>
                </div>
                <div class="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse">
                    <button type="button" onclick="confirmDeletePayment()" 
                            class="inline-flex w-full justify-center rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-red-500 sm:ml-3 sm:w-auto">
                        Delete Payment
                    </button>
                    <button type="button" onclick="hideDeletePaymentModal()" 
                            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:mt-0 sm:w-auto">
                        Cancel
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %} 