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

{% block title %}Reports & Statements Dashboard{% endblock %}

{% block content %}
<div class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-6">
    <div class="max-w-7xl mx-auto">
        <!-- Header -->
        <div class="mb-8">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">
                        <span>📊</span>
                        Report Generator Dashboard
                    </h1>
                    <p class="text-gray-600">Generate comprehensive reports and statements with detailed logging</p>
                </div>
                <div class="flex space-x-4">
                    <button onclick="refreshDashboard()"
                        class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors">
                        <span>🔄</span>Refresh
                    </button>
                    <a href="{% url 'utils:notifications' %}"
                        class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg transition-colors">
                        <span>🔔</span>View Logs
                    </a>
                </div>
            </div>
        </div>

        <!-- Quick Stats -->
        {% if executive_summary and 'error' not in executive_summary %}
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-blue-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Total Loans</p>
                        <p class="text-2xl font-bold text-gray-900">{{ executive_summary.total_loans|default:0 }}</p>
                    </div>
                    <div class="bg-blue-100 p-3 rounded-full">
                        <span>💵</span>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-green-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Active Loans</p>
                        <p class="text-2xl font-bold text-gray-900">{{ executive_summary.active_loans|default:0 }}</p>
                    </div>
                    <div class="bg-green-100 p-3 rounded-full">
                        <span>📈</span>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-yellow-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Collection Rate</p>
                        <p class="text-2xl font-bold text-gray-900">{{
                            executive_summary.collection_rate|default:0|floatformat:1 }}%</p>
                    </div>
                    <div class="bg-yellow-100 p-3 rounded-full">
                        <i class="fas fa-percentage text-yellow-600"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-red-500">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Overdue Loans</p>
                        <p class="text-2xl font-bold text-gray-900">{{ executive_summary.overdue_loans|default:0 }}</p>
                    </div>
                    <div class="bg-red-100 p-3 rounded-full">
                        <span>⚠️</span>
                    </div>
                </div>
            </div>
        </div>
        {% endif %}

        <!-- Reports Section -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
            <!-- System Reports -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex items-center justify-between mb-6">
                    <h2 class="text-xl font-bold text-gray-900">
                        <span>📊</span>
                        System Reports
                    </h2>
                    <span class="bg-blue-100 text-blue-800 text-sm font-medium px-3 py-1 rounded-full">
                        {{ report_types|length }} Available
                    </span>
                </div>

                <div class="space-y-4">
                    {% for report in report_types %}
                    <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                        <div class="flex items-start justify-between">
                            <div class="flex-1">
                                <div class="flex items-center mb-2">
                                    <i class="{{ report.icon }} text-blue-600 mr-3"></i>
                                    <h3 class="font-semibold text-gray-900">{{ report.name }}</h3>
                                </div>
                                <p class="text-sm text-gray-600 mb-3">{{ report.description }}</p>

                                <!-- Format Buttons -->
                                <div class="flex flex-wrap gap-2">
                                    {% for format in report.formats %}
                                    <button onclick="generateReport('{{ report.id }}', '{{ format }}')"
                                        class="bg-{{ format|default:'blue' }}-600 hover:bg-{{ format|default:'blue' }}-700 text-white px-3 py-1 rounded text-sm transition-colors">
                                        <span>⬇️</span>
                                        {{ format|upper }}
                                    </button>
                                    {% endfor %}
                                    <button onclick="previewReport('{{ report.id }}')"
                                        class="bg-gray-600 hover:bg-gray-700 text-white px-3 py-1 rounded text-sm transition-colors">
                                        <i class="fas fa-eye mr-1"></i>
                                        Preview
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>

            <!-- Individual Statements -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex items-center justify-between mb-6">
                    <h2 class="text-xl font-bold text-gray-900">
                        <span>🧾</span>
                        Individual Statements
                    </h2>
                    <span class="bg-green-100 text-green-800 text-sm font-medium px-3 py-1 rounded-full">
                        {{ statement_types|length }} Types
                    </span>
                </div>

                <div class="space-y-4">
                    {% for statement in statement_types %}
                    <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                        <div class="flex items-start justify-between">
                            <div class="flex-1">
                                <div class="flex items-center mb-2">
                                    <i class="{{ statement.icon }} text-green-600 mr-3"></i>
                                    <h3 class="font-semibold text-gray-900">{{ statement.name }}</h3>
                                </div>
                                <p class="text-sm text-gray-600 mb-3">{{ statement.description }}</p>

                                <!-- Statement Generation -->
                                {% if statement.id == 'loan_statement' %}
                                <div class="mb-3">
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Loan ID:</label>
                                    <input type="number" id="loan_id_input" placeholder="Enter loan ID"
                                        class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm">
                                </div>
                                <div class="flex flex-wrap gap-2">
                                    {% for format in statement.formats %}
                                    <button onclick="generateLoanStatement('{{ format }}')"
                                        class="bg-green-600 hover:bg-green-700 text-white px-3 py-1 rounded text-sm transition-colors">
                                        <span>⬇️</span>
                                        {{ format|upper }}
                                    </button>
                                    {% endfor %}
                                </div>
                                {% elif statement.id == 'client_statement' %}
                                <div class="mb-3">
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Client ID:</label>
                                    <input type="number" id="client_id_input" placeholder="Enter client ID"
                                        class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm">
                                </div>
                                <div class="flex flex-wrap gap-2">
                                    {% for format in statement.formats %}
                                    <button onclick="generateClientStatement('{{ format }}')"
                                        class="bg-green-600 hover:bg-green-700 text-white px-3 py-1 rounded text-sm transition-colors">
                                        <span>⬇️</span>
                                        {{ format|upper }}
                                    </button>
                                    {% endfor %}
                                </div>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>

        <!-- Recent Activity Log -->
        <div class="bg-white rounded-xl shadow-lg p-6">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-xl font-bold text-gray-900">
                    <i class="fas fa-history text-purple-600 mr-2"></i>
                    Recent Report Activity
                </h2>
                <a href="{% url 'utils:notifications' %}" class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                    View All Logs <span>→</span>
                </a>
            </div>

            <div id="recent-activity" class="space-y-3">
                <div class="text-center text-gray-500 py-8">
                    <span>⏰</span>
                    <p>Recent report generation activity will appear here</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // Report generation functions
    function generateReport(reportType, format) {
        showLoading();

        const data = {
            report_type: reportType,
            format: format,
            parameters: {}
        };

        // Add date range for collection statements
        if (reportType === 'collection_statement') {
            const dateFrom = prompt('Enter start date (YYYY-MM-DD):');
            const dateTo = prompt('Enter end date (YYYY-MM-DD):');
            if (dateFrom) data.parameters.date_from = dateFrom;
            if (dateTo) data.parameters.date_to = dateTo;
        }

        fetch('{% url "utils:generate_report_api" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token }}'
            },
            body: JSON.stringify(data)
        })
            .then(response => response.json())
            .then(data => {
                hideLoading();
                if (data.success) {
                    if (format === 'json') {
                        showPreview(data.data, reportType);
                    } else {
                        downloadFile(data.file_content, data.filename, data.content_type);
                    }
                } else {
                    alert('Error generating report: ' + data.error);
                }
            })
            .catch(error => {
                hideLoading();
                alert('Error: ' + error.message);
            });
    }

    function generateLoanStatement(format) {
        const loanId = document.getElementById('loan_id_input').value;
        if (!loanId) {
            alert('Please enter a loan ID');
            return;
        }

        showLoading();

        const data = {
            report_type: 'loan_statement',
            format: format,
            parameters: { loan_id: loanId }
        };

        fetch('{% url "utils:generate_report_api" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token }}'
            },
            body: JSON.stringify(data)
        })
            .then(response => response.json())
            .then(data => {
                hideLoading();
                if (data.success) {
                    downloadFile(data.file_content, data.filename, data.content_type);
                } else {
                    alert('Error generating statement: ' + data.error);
                }
            })
            .catch(error => {
                hideLoading();
                alert('Error: ' + error.message);
            });
    }

    function generateClientStatement(format) {
        const clientId = document.getElementById('client_id_input').value;
        if (!clientId) {
            alert('Please enter a client ID');
            return;
        }

        showLoading();

        const data = {
            report_type: 'client_statement',
            format: format,
            parameters: { client_id: clientId }
        };

        fetch('{% url "utils:generate_report_api" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token }}'
            },
            body: JSON.stringify(data)
        })
            .then(response => response.json())
            .then(data => {
                hideLoading();
                if (data.success) {
                    downloadFile(data.file_content, data.filename, data.content_type);
                } else {
                    alert('Error generating statement: ' + data.error);
                }
            })
            .catch(error => {
                hideLoading();
                alert('Error: ' + error.message);
            });
    }

    function previewReport(reportType) {
        generateReport(reportType, 'json');
    }

    function showPreview(data, reportType) {
        const modal = document.getElementById('previewModal');
        const content = document.getElementById('previewContent');

        let html = '<div class="space-y-4">';

        if (reportType === 'executive_summary') {
            html += `
            <h4 class="text-lg font-semibold">Executive Summary</h4>
            <div class="grid grid-cols-2 gap-4">
                <div class="bg-gray-50 p-3 rounded">
                    <div class="text-sm text-gray-600">Total Loans</div>
                    <div class="text-xl font-bold">${data.total_loans || 0}</div>
                </div>
                <div class="bg-gray-50 p-3 rounded">
                    <div class="text-sm text-gray-600">Active Loans</div>
                    <div class="text-xl font-bold">${data.active_loans || 0}</div>
                </div>
                <div class="bg-gray-50 p-3 rounded">
                    <div class="text-sm text-gray-600">Total Disbursed</div>
                    <div class="text-xl font-bold">KES ${(data.total_disbursed || 0).toLocaleString()}</div>
                </div>
                <div class="bg-gray-50 p-3 rounded">
                    <div class="text-sm text-gray-600">Collection Rate</div>
                    <div class="text-xl font-bold">${(data.collection_rate || 0).toFixed(1)}%</div>
                </div>
            </div>
        `;
        } else {
            html += '<pre class="bg-gray-100 p-4 rounded text-sm overflow-x-auto">' + JSON.stringify(data, null, 2) + '</pre>';
        }

        html += '</div>';
        content.innerHTML = html;
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }

    function closePreview() {
        const modal = document.getElementById('previewModal');
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }

    function downloadFile(base64Content, filename, contentType) {
        const byteCharacters = atob(base64Content);
        const byteNumbers = new Array(byteCharacters.length);
        for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob([byteArray], { type: contentType });

        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    function showLoading() {
        document.getElementById('loadingModal').classList.remove('hidden');
        document.getElementById('loadingModal').classList.add('flex');
    }

    function hideLoading() {
        document.getElementById('loadingModal').classList.add('hidden');
        document.getElementById('loadingModal').classList.remove('flex');
    }

    function refreshDashboard() {
        location.reload();
    }

    // Load recent activity on page load
    document.addEventListener('DOMContentLoaded', function () {
        // This would typically load recent activity from an API
        console.log('Reports dashboard loaded');
    });
</script>
{% endblock %}
<div class="bg-green-100 p-3 rounded-full">
    <span>📈</span>
</div>
</div>
</div>

<div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-yellow-500">
    <div class="flex items-center justify-between">
        <div>
            <p class="text-sm font-medium text-gray-600">Collection Rate</p>
            <p class="text-2xl font-bold text-gray-900">{{ executive_summary.collection_rate|default:0|floatformat:1 }}%
            </p>
        </div>
        <div class="bg-yellow-100 p-3 rounded-full">
            <i class="fas fa-percentage text-yellow-600"></i>
        </div>
    </div>
</div>

<div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-red-500">
    <div class="flex items-center justify-between">
        <div>
            <p class="text-sm font-medium text-gray-600">Overdue Loans</p>
            <p class="text-2xl font-bold text-gray-900">{{ executive_summary.overdue_loans|default:0 }}</p>
        </div>
        <div class="bg-red-100 p-3 rounded-full">
            <span>⚠️</span>
        </div>
    </div>
</div>
</div>
{% endif %}

<!-- Reports Section -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
    <!-- System Reports -->
    <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-xl font-bold text-gray-900">
                <span>📊</span>
                System Reports
            </h2>
            <span class="bg-blue-100 text-blue-800 text-sm font-medium px-3 py-1 rounded-full">
                {{ report_types|length }} Available
            </span>
        </div>

        <div class="space-y-4">
            {% for report in report_types %}
            <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <div class="flex items-center mb-2">
                            <i class="{{ report.icon }} text-blue-600 mr-3"></i>
                            <h3 class="font-semibold text-gray-900">{{ report.name }}</h3>
                        </div>
                        <p class="text-sm text-gray-600 mb-3">{{ report.description }}</p>

                        <!-- Format Buttons -->
                        <div class="flex flex-wrap gap-2">
                            {% for format in report.formats %}
                            <button onclick="generateReport('{{ report.id }}', '{{ format }}')"
                                class="bg-{{ format|default:'blue' }}-600 hover:bg-{{ format|default:'blue' }}-700 text-white px-3 py-1 rounded text-sm transition-colors">
                                <span>⬇️</span>
                                {{ format|upper }}
                            </button>
                            {% endfor %}
                            <button onclick="previewReport('{{ report.id }}')"
                                class="bg-gray-600 hover:bg-gray-700 text-white px-3 py-1 rounded text-sm transition-colors">
                                <i class="fas fa-eye mr-1"></i>
                                Preview
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>

    <!-- Individual Statements -->
    <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-xl font-bold text-gray-900">
                <span>🧾</span>
                Individual Statements
            </h2>
            <span class="bg-green-100 text-green-800 text-sm font-medium px-3 py-1 rounded-full">
                {{ statement_types|length }} Types
            </span>
        </div>

        <div class="space-y-4">
            {% for statement in statement_types %}
            <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <div class="flex items-center mb-2">
                            <i class="{{ statement.icon }} text-green-600 mr-3"></i>
                            <h3 class="font-semibold text-gray-900">{{ statement.name }}</h3>
                        </div>
                        <p class="text-sm text-gray-600 mb-3">{{ statement.description }}</p>

                        <!-- Statement Generation -->
                        {% if statement.id == 'loan_statement' %}
                        <div class="mb-3">
                            <label class="block text-sm font-medium text-gray-700 mb-1">Loan ID:</label>
                            <input type="number" id="loan_id_input" placeholder="Enter loan ID"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm">
                        </div>
                        <div class="flex flex-wrap gap-2">
                            {% for format in statement.formats %}
                            <button onclick="generateLoanStatement('{{ format }}')"
                                class="bg-green-600 hover:bg-green-700 text-white px-3 py-1 rounded text-sm transition-colors">
                                <span>⬇️</span>
                                {{ format|upper }}
                            </button>
                            {% endfor %}
                        </div>
                        {% elif statement.id == 'client_statement' %}
                        <div class="mb-3">
                            <label class="block text-sm font-medium text-gray-700 mb-1">Client ID:</label>
                            <input type="number" id="client_id_input" placeholder="Enter client ID"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm">
                        </div>
                        <div class="flex flex-wrap gap-2">
                            {% for format in statement.formats %}
                            <button onclick="generateClientStatement('{{ format }}')"
                                class="bg-green-600 hover:bg-green-700 text-white px-3 py-1 rounded text-sm transition-colors">
                                <span>⬇️</span>
                                {{ format|upper }}
                            </button>
                            {% endfor %}
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>
</div>

<!-- Recent Activity Log -->
<div class="bg-white rounded-xl shadow-lg p-6">
    <div class="flex items-center justify-between mb-6">
        <h2 class="text-xl font-bold text-gray-900">
            <i class="fas fa-history text-purple-600 mr-2"></i>
            Recent Report Activity
        </h2>
        <a href="{% url 'utils:notifications' %}" class="text-blue-600 hover:text-blue-800 text-sm font-medium">
            View All Logs <span>→</span>
        </a>
    </div>

    <div id="recent-activity" class="space-y-3">
        <div class="text-center text-gray-500 py-8">
            <span>⏰</span>
            <p>Recent report generation activity will appear here</p>
        </div>
    </div>
</div>
</div>
</div>

<!-- Loading Modal -->
<div id="loadingModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-lg p-6 max-w-sm mx-4">
        <div class="text-center">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
            <h3 class="text-lg font-semibold text-gray-900 mb-2">Generating Report</h3>
            <p class="text-gray-600">Please wait while we prepare your report...</p>
        </div>
    </div>
</div>

<!-- Preview Modal -->
<div id="previewModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-lg max-w-4xl max-h-[90vh] mx-4 overflow-hidden">
        <div class="flex items-center justify-between p-4 border-b">
            <h3 class="text-lg font-semibold text-gray-900">Report Preview</h3>
            <button onclick="closePreview()" class="text-gray-400 hover:text-gray-600">
                <span>✕</span>
            </button>
        </div>
        <div id="previewContent" class="p-6 overflow-y-auto max-h-[70vh]">
            <!-- Preview content will be loaded here -->
        </div>
    </div>
</div>

<script>
    // Report generation functions
    function generateReport(reportType, format) {
        showLoading();

        const data = {
            report_type: reportType,
            format: format,
            parameters: {}
        };

        // Add date range for collection statements
        if (reportType === 'collection_statement') {
            const dateFrom = prompt('Enter start date (YYYY-MM-DD):');
            const dateTo = prompt('Enter end date (YYYY-MM-DD):');
            if (dateFrom) data.parameters.date_from = dateFrom;
            if (dateTo) data.parameters.date_to = dateTo;
        }

        fetch('{% url "utils:generate_report_api" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token }}'
            },
            body: JSON.stringify(data)
        })
            .then(response => response.json())
            .then(data => {
                hideLoading();
                if (data.success) {
                    if (format === 'json') {
                        showPreview(data.data, reportType);
                    } else {
                        downloadFile(data.file_content, data.filename, data.content_type);
                    }
                } else {
                    alert('Error generating report: ' + data.error);
                }
            })
            .catch(error => {
                hideLoading();
                alert('Error: ' + error.message);
            });
    }

    function generateLoanStatement(format) {
        const loanId = document.getElementById('loan_id_input').value;
        if (!loanId) {
            alert('Please enter a loan ID');
            return;
        }

        showLoading();

        const data = {
            report_type: 'loan_statement',
            format: format,
            parameters: { loan_id: loanId }
        };

        fetch('{% url "utils:generate_report_api" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token }}'
            },
            body: JSON.stringify(data)
        })
            .then(response => response.json())
            .then(data => {
                hideLoading();
                if (data.success) {
                    downloadFile(data.file_content, data.filename, data.content_type);
                } else {
                    alert('Error generating statement: ' + data.error);
                }
            })
            .catch(error => {
                hideLoading();
                alert('Error: ' + error.message);
            });
    }

    function generateClientStatement(format) {
        const clientId = document.getElementById('client_id_input').value;
        if (!clientId) {
            alert('Please enter a client ID');
            return;
        }

        showLoading();

        const data = {
            report_type: 'client_statement',
            format: format,
            parameters: { client_id: clientId }
        };

        fetch('{% url "utils:generate_report_api" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token }}'
            },
            body: JSON.stringify(data)
        })
            .then(response => response.json())
            .then(data => {
                hideLoading();
                if (data.success) {
                    downloadFile(data.file_content, data.filename, data.content_type);
                } else {
                    alert('Error generating statement: ' + data.error);
                }
            })
            .catch(error => {
                hideLoading();
                alert('Error: ' + error.message);
            });
    }

    function previewReport(reportType) {
        generateReport(reportType, 'json');
    }

    function showPreview(data, reportType) {
        const modal = document.getElementById('previewModal');
        const content = document.getElementById('previewContent');

        let html = '<div class="space-y-4">';

        if (reportType === 'executive_summary') {
            html += `
            <h4 class="text-lg font-semibold">Executive Summary</h4>
            <div class="grid grid-cols-2 gap-4">
                <div class="bg-gray-50 p-3 rounded">
                    <div class="text-sm text-gray-600">Total Loans</div>
                    <div class="text-xl font-bold">${data.total_loans || 0}</div>
                </div>
                <div class="bg-gray-50 p-3 rounded">
                    <div class="text-sm text-gray-600">Active Loans</div>
                    <div class="text-xl font-bold">${data.active_loans || 0}</div>
                </div>
                <div class="bg-gray-50 p-3 rounded">
                    <div class="text-sm text-gray-600">Total Disbursed</div>
                    <div class="text-xl font-bold">KES ${(data.total_disbursed || 0).toLocaleString()}</div>
                </div>
                <div class="bg-gray-50 p-3 rounded">
                    <div class="text-sm text-gray-600">Collection Rate</div>
                    <div class="text-xl font-bold">${(data.collection_rate || 0).toFixed(1)}%</div>
                </div>
            </div>
        `;
        } else {
            html += '<pre class="bg-gray-100 p-4 rounded text-sm overflow-x-auto">' + JSON.stringify(data, null, 2) + '</pre>';
        }

        html += '</div>';
        content.innerHTML = html;
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }

    function closePreview() {
        const modal = document.getElementById('previewModal');
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }

    function downloadFile(base64Content, filename, contentType) {
        const byteCharacters = atob(base64Content);
        const byteNumbers = new Array(byteCharacters.length);
        for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob([byteArray], { type: contentType });

        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    function showLoading() {
        document.getElementById('loadingModal').classList.remove('hidden');
        document.getElementById('loadingModal').classList.add('flex');
    }

    function hideLoading() {
        document.getElementById('loadingModal').classList.add('hidden');
        document.getElementById('loadingModal').classList.remove('flex');
    }

    function refreshDashboard() {
        location.reload();
    }

    // Load recent activity on page load
    document.addEventListener('DOMContentLoaded', function () {
        // This would typically load recent activity from an API
        console.log('Reports dashboard loaded');
    });
</script>
{% endblock %}