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

{% block title %}Registration Fees Analytics - Enhanced Report{% endblock %}

{% block extra_css %}
<style>
.metric-card {
    background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    color: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.metric-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 25px rgba(59, 130, 246, 0.3);
}

.metric-card.success { background: linear-gradient(135deg, #10b981 0%, #059669 100%); }
.metric-card.warning { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); }
.metric-card.danger { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); }
.metric-card.info { background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%); }
.metric-card.purple { background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); }

.filter-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    border: 1px solid #e5e7eb;
}

.chart-container {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    border: 1px solid #e5e7eb;
    height: 400px;
}

.data-table {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    border: 1px solid #e5e7eb;
}

.data-table th {
    background: #f9fafb;
    padding: 1rem;
    text-align: left;
    font-weight: 600;
    color: #374151;
    border-bottom: 1px solid #e5e7eb;
}

.data-table td {
    padding: 1rem;
    border-bottom: 1px solid #f3f4f6;
}

.data-table tr:hover {
    background: #f9fafb;
}

.clickable {
    cursor: pointer;
    transition: all 0.2s;
}

.clickable:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.action-btn {
    padding: 0.5rem 1rem;
    border-radius: 6px;
    font-size: 0.875rem;
    font-weight: 500;
    transition: all 0.2s;
    border: none;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.action-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.action-btn.primary { background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%); color: white; }
.action-btn.success { background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; }
.action-btn.warning { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white; }
.action-btn.danger { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); color: white; }

.payment-status-badge {
    padding: 0.25rem 0.75rem;
    border-radius: 9999px;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.status-paid { background-color: #dcfce7; color: #166534; }
.status-pending { background-color: #fef3c7; color: #92400e; }
.status-overdue { background-color: #fee2e2; color: #991b1b; }
.status-waived { background-color: #e0e7ff; color: #3730a3; }
</style>
{% endblock %}

{% block content %}
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6">
    <!-- Header Section -->
    <div class="mb-8">
        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <div>
                <h1 class="text-3xl font-bold text-gray-900 dark:text-white">
                    <i class="fas fa-file-invoice-dollar text-cyan-500 mr-3"></i>
                    Registration Fees Analytics
                </h1>
                <p class="text-gray-600 dark:text-gray-400 mt-2">
                    Comprehensive analysis of client registration fees and onboarding revenue
                </p>
            </div>
            <div class="flex gap-3">
                <a href="{% url 'reports:registration_fees_settings' %}" class="action-btn warning">
                    <span>⚙️</span>
                    Settings
                </a>
                <button onclick="exportToExcel()" class="action-btn success">
                    <span>📊</span>
                    Export Excel
                </button>
                <button onclick="exportToPDF()" class="action-btn danger">
                    <span>📄</span>
                    Export PDF
                </button>
                <a href="{% url 'reports:reports_dashboard' %}" class="action-btn primary">
                    <span>←</span>
                    Back to Dashboard
                </a>
            </div>
        </div>
    </div>

    <!-- Filters Section -->
    <div class="filter-card mb-8">
        <h3 class="text-lg font-semibold text-gray-900 mb-4">
            <span>🔍</span>
            Report Filters
        </h3>
        <form method="GET" class="grid grid-cols-1 md:grid-cols-5 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Period</label>
                <select name="period" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" onchange="this.form.submit()">
                    <option value="current_month" {% if selected_period == 'current_month' %}selected{% endif %}>Current Month</option>
                    <option value="last_month" {% if selected_period == 'last_month' %}selected{% endif %}>Last Month</option>
                    <option value="current_quarter" {% if selected_period == 'current_quarter' %}selected{% endif %}>Current Quarter</option>
                    <option value="last_quarter" {% if selected_period == 'last_quarter' %}selected{% endif %}>Last Quarter</option>
                    <option value="current_year" {% if selected_period == 'current_year' %}selected{% endif %}>Current Year</option>
                    <option value="all_time" {% if selected_period == 'all_time' %}selected{% endif %}>All Time</option>
                    <option value="custom" {% if selected_period == 'custom' %}selected{% endif %}>Custom Range</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Start Date</label>
                <input type="date" name="start_date" value="{{ start_date|date:'Y-m-d' }}" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">End Date</label>
                <input type="date" name="end_date" value="{{ end_date|date:'Y-m-d' }}" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Payment Status</label>
                <select name="payment_status" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    <option value="">All Status</option>
                    <option value="paid">Paid</option>
                    <option value="pending">Pending</option>
                    <option value="overdue">Overdue</option>
                    <option value="waived">Waived</option>
                </select>
            </div>
            <div class="flex items-end">
                <button type="submit" class="action-btn primary w-full">
                    <span>🔍</span>
                    Apply Filters
                </button>
            </div>
        </form>
    </div>

    <!-- Key Metrics Row -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6 mb-8">
        <div class="metric-card success clickable" onclick="showTotalIncome()">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-xl font-bold mb-2">
                        KSh {{ report_data.summary.total_registration_income|default:0|floatformat:0|intcomma }}
                    </h3>
                    <p class="text-sm opacity-90">Total Registration Income</p>
                </div>
                <span>💵</span>
            </div>
        </div>

        <div class="metric-card info clickable" onclick="showTotalRegistrations()">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-xl font-bold mb-2">
                        {{ report_data.summary.total_registrations|default:0 }}
                    </h3>
                    <p class="text-sm opacity-90">Total Registrations</p>
                </div>
                <span>👤+</span>
            </div>
        </div>

        <div class="metric-card warning clickable" onclick="showAverageFee()">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-xl font-bold mb-2">
                        KSh {{ report_data.summary.average_registration_fee|default:0|floatformat:0|intcomma }}
                    </h3>
                    <p class="text-sm opacity-90">Average Fee</p>
                </div>
                <span>📈</span>
            </div>
        </div>

        <div class="metric-card purple clickable" onclick="showCollectionRate()">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-xl font-bold mb-2">
                        {{ report_data.summary.collection_rate|default:0|floatformat:1 }}%
                    </h3>
                    <p class="text-sm opacity-90">Collection Rate</p>
                </div>
                <i class="fas fa-percentage text-2xl opacity-75"></i>
            </div>
        </div>

        <div class="metric-card clickable" onclick="showMonthlyGrowth()">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-xl font-bold mb-2">
                        {{ report_data.summary.monthly_growth_rate|default:0|floatformat:1 }}%
                    </h3>
                    <p class="text-sm opacity-90">Monthly Growth</p>
                </div>
                <i class="fas fa-trending-up text-2xl opacity-75"></i>
            </div>
        </div>
    </div>

    <!-- Payment Status Breakdown -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="metric-card success clickable" onclick="filterByStatus('paid')">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-lg font-semibold mb-2">
                        {{ report_data.payment_status.paid_count|default:0 }}
                    </h3>
                    <p class="text-sm opacity-90">Paid Registrations</p>
                    <p class="text-xs opacity-75">KSh {{ report_data.payment_status.paid_amount|default:0|floatformat:0|intcomma }}</p>
                </div>
                <span>✓</span>
            </div>
        </div>

        <div class="metric-card warning clickable" onclick="filterByStatus('pending')">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-lg font-semibold mb-2">
                        {{ report_data.payment_status.pending_count|default:0 }}
                    </h3>
                    <p class="text-sm opacity-90">Pending Payments</p>
                    <p class="text-xs opacity-75">KSh {{ report_data.payment_status.pending_amount|default:0|floatformat:0|intcomma }}</p>
                </div>
                <span>⏰</span>
            </div>
        </div>

        <div class="metric-card danger clickable" onclick="filterByStatus('overdue')">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-lg font-semibold mb-2">
                        {{ report_data.payment_status.overdue_count|default:0 }}
                    </h3>
                    <p class="text-sm opacity-90">Overdue Payments</p>
                    <p class="text-xs opacity-75">KSh {{ report_data.payment_status.overdue_amount|default:0|floatformat:0|intcomma }}</p>
                </div>
                <span>⚠️</span>
            </div>
        </div>

        <div class="metric-card info clickable" onclick="filterByStatus('waived')">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-lg font-semibold mb-2">
                        {{ report_data.payment_status.waived_count|default:0 }}
                    </h3>
                    <p class="text-sm opacity-90">Waived Fees</p>
                    <p class="text-xs opacity-75">KSh {{ report_data.payment_status.waived_amount|default:0|floatformat:0|intcomma }}</p>
                </div>
                <span>🎁</span>
            </div>
        </div>
    </div>


    <!-- Detailed Registration Fees Table -->
    <div class="data-table mb-8">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-900">
                <i class="fas fa-table text-blue-500 mr-2"></i>
                Detailed Registration Fees Breakdown
            </h3>
        </div>
        
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr>
                        <th class="text-left">Client Details</th>
                        <th class="text-left">Registration Date</th>
                        <th class="text-right">Fee Amount</th>
                        <th class="text-center">Payment Status</th>
                        <th class="text-left">Payment Date</th>
                        <th class="text-left">Payment Method</th>
                        <th class="text-left">Notes</th>
                        <th class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {% if report_data.registrations %}
                        {% for registration in report_data.registrations %}
                        <tr class="clickable" onclick="viewClientDetails('{{ registration.client_id }}')">
                            <td>
                                <div class="font-medium text-blue-600">{{ registration.client_name }}</div>
                                <div class="text-sm text-gray-500">{{ registration.client_phone }}</div>
                                <div class="text-sm text-gray-500">ID: {{ registration.client_id_number|default:"N/A" }}</div>
                            </td>
                            <td>
                                <div class="font-medium text-gray-900">{{ registration.registration_date|date:"M d, Y" }}</div>
                                <div class="text-sm text-gray-500">{{ registration.registration_date|date:"H:i" }}</div>
                            </td>
                            <td class="text-right">
                                <div class="font-medium text-green-600">
                                    KSh {{ registration.fee_amount|floatformat:0|intcomma }}
                                </div>
                                {% if registration.discount_amount > 0 %}
                                <div class="text-sm text-gray-500">
                                    Discount: KSh {{ registration.discount_amount|floatformat:0|intcomma }}
                                </div>
                                {% endif %}
                            </td>
                            <td class="text-center">
                                <span class="payment-status-badge status-{{ registration.payment_status|default:'pending' }}">
                                    {{ registration.payment_status|default:'Pending'|title }}
                                </span>
                            </td>
                            <td>
                                {% if registration.payment_date %}
                                    <div class="text-sm text-gray-900">{{ registration.payment_date|date:"M d, Y" }}</div>
                                    <div class="text-sm text-gray-500">{{ registration.payment_date|date:"H:i" }}</div>
                                {% else %}
                                    <span class="text-sm text-gray-400">Not paid</span>
                                {% endif %}
                            </td>
                            <td>
                                {% if registration.payment_method %}
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                        {{ registration.payment_method|title }}
                                    </span>
                                {% else %}
                                    <span class="text-sm text-gray-400">N/A</span>
                                {% endif %}
                            </td>
                            <td>
                                <div class="text-sm text-gray-600">
                                    {{ registration.notes|default:"No notes"|truncatechars:50 }}
                                </div>
                            </td>
                            <td class="text-center">
                                <div class="flex justify-center gap-2">
                                    {% if registration.payment_status == 'pending' or registration.payment_status == 'overdue' %}
                                    <button onclick="recordPayment('{{ registration.id }}')" class="action-btn success" title="Record Payment">
                                        <span>💳</span>
                                    </button>
                                    {% endif %}
                                    <button onclick="viewClientDetails('{{ registration.client_id }}')" class="action-btn primary" title="View Client">
                                        <span>👤</span>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    {% else %}
                        <tr>
                            <td colspan="8" class="text-center py-8 text-gray-500">
                                <span>ℹ️</span>
                                <h3 class="text-lg font-medium mb-2">No Registration Fees Found</h3>
                                <p>No registration fees found for the selected period and filters.</p>
                            </td>
                        </tr>
                    {% endif %}
                </tbody>
            </table>
        </div>
    </div>

    <!-- Summary Statistics -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div class="filter-card">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">
                <span>📊</span>
                Collection Summary
            </h3>
            <div class="space-y-3">
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Fees Collected:</span>
                    <span class="font-semibold text-green-600">KSh {{ report_data.summary.fees_collected|default:0|floatformat:0|intcomma }}</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Fees Outstanding:</span>
                    <span class="font-semibold text-yellow-600">KSh {{ report_data.summary.fees_outstanding|default:0|floatformat:0|intcomma }}</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Collection Efficiency:</span>
                    <span class="font-semibold text-blue-600">{{ report_data.summary.collection_efficiency|default:0|floatformat:1 }}%</span>
                </div>
            </div>
        </div>

        <div class="filter-card">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">
                <i class="fas fa-trending-up text-green-500 mr-2"></i>
                Performance Metrics
            </h3>
            <div class="space-y-3">
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Growth vs Last Period:</span>
                    <span class="font-semibold {% if report_data.summary.growth_rate >= 0 %}text-green-600{% else %}text-red-600{% endif %}">
                        {{ report_data.summary.growth_rate|default:0|floatformat:1 }}%
                    </span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Highest Single Fee:</span>
                    <span class="font-semibold text-blue-600">KSh {{ report_data.summary.highest_fee|default:0|floatformat:0|intcomma }}</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Average Days to Pay:</span>
                    <span class="font-semibold text-purple-600">{{ report_data.summary.avg_days_to_pay|default:0|floatformat:1 }}</span>
                </div>
            </div>
        </div>

        <div class="filter-card">
            <h3 class="text-lg font-semibold text-gray-900 mb-4">
                <span>📅</span>
                Period Comparison
            </h3>
            <div class="space-y-3">
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">This Period:</span>
                    <span class="font-semibold text-blue-600">KSh {{ report_data.summary.current_period_income|default:0|floatformat:0|intcomma }}</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Previous Period:</span>
                    <span class="font-semibold text-gray-600">KSh {{ report_data.summary.previous_period_income|default:0|floatformat:0|intcomma }}</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-gray-600">Difference:</span>
                    <span class="font-semibold {% if report_data.summary.period_difference >= 0 %}text-green-600{% else %}text-red-600{% endif %}">
                        {% if report_data.summary.period_difference >= 0 %}+{% endif %}KSh {{ report_data.summary.period_difference|default:0|floatformat:0|intcomma }}
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Scripts -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    initializeCharts();
});

function initializeCharts() {
    // All charts removed
}

// Interactive Functions
function showTotalIncome() {
    alert('Total Registration Income: KSh {{ report_data.summary.total_registration_income|default:0|floatformat:0|intcomma }}');
}

function showTotalRegistrations() {
    alert('Total Registrations: {{ report_data.summary.total_registrations|default:0 }}');
}

function showAverageFee() {
    alert('Average Registration Fee: KSh {{ report_data.summary.average_registration_fee|default:0|floatformat:0|intcomma }}');
}

function showCollectionRate() {
    alert('Collection Rate: {{ report_data.summary.collection_rate|default:0|floatformat:1 }}%');
}

function showMonthlyGrowth() {
    alert('Monthly Growth Rate: {{ report_data.summary.monthly_growth_rate|default:0|floatformat:1 }}%');
}

function filterByStatus(status) {
    const params = new URLSearchParams(window.location.search);
    params.set('payment_status', status);
    window.location.href = `${window.location.pathname}?${params.toString()}`;
}

function recordPayment(registrationId) {
    alert(`Recording payment for registration ${registrationId}`);
}

function viewClientDetails(clientId) {
    window.open(`/clients/${clientId}/`, '_blank');
}

function exportToExcel() {
    window.location.href = '{% url "reports:registration_fees_report" %}?export=excel&{{ request.GET.urlencode }}';
}

function exportToPDF() {
    window.location.href = '{% url "reports:registration_fees_report" %}?export=pdf&{{ request.GET.urlencode }}';
}
</script>
{% endblock %}