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

{% block title %}Delinquent Loans Report{% endblock %}

{% block extra_css %}
<!-- Use reliable CDN sources without integrity checks -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/date-fns@2.29.3/index.min.js"></script>
<script src="https://unpkg.com/jspdf@2.5.1/dist/jspdf.umd.min.js"></script>
<script src="https://unpkg.com/jspdf-autotable@3.5.31/dist/jspdf.plugin.autotable.min.js"></script>
<script src="https://unpkg.com/xlsx@0.18.5/dist/xlsx.full.min.js"></script>

<!-- Simple and reliable library initialization -->
<script>
window.addEventListener('load', function() {
    // Wait a bit for all scripts to load
    setTimeout(function() {
        console.log('Checking library availability...');
        console.log('Chart available:', typeof Chart !== 'undefined');
        console.log('jsPDF available:', typeof window.jspdf !== 'undefined' || typeof jsPDF !== 'undefined');
        console.log('XLSX available:', typeof XLSX !== 'undefined');
        
        // Initialize charts if Chart.js is available
        if (typeof Chart !== 'undefined') {
            try {
                initializeCharts();
                console.log('Charts initialized successfully');
            } catch (error) {
                console.error('Error initializing charts:', error);
            }
        } else {
            console.error('Chart.js not loaded');
            const chartsSection = document.getElementById('chartsSection');
            if (chartsSection) {
                chartsSection.innerHTML = '<div class="alert alert-warning">Charts unavailable. Please refresh the page.</div>';
            }
        }
        
        // Setup other event listeners
        try {
            setupEventListeners();
        } catch (error) {
            console.error('Error setting up event listeners:', error);
        }
    }, 500); // Increased delay to ensure all scripts load
});
</script>
<style>
    .chart-container {
        position: relative;
        height: 300px;
        margin-bottom: 2rem;
    }
    .export-dropdown {
        display: none;
        position: absolute;
        right: 0;
        top: 100%;
        background: white;
        border: 1px solid #e5e7eb;
        border-radius: 0.5rem;
        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        z-index: 10;
        min-width: 200px;
    }
    .export-dropdown.show {
        display: block;
    }
    .severity-indicator {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        display: inline-block;
        margin-right: 8px;
    }
    .severity-mild { background-color: #fbbf24; }
    .severity-moderate { background-color: #f97316; }
    .severity-severe { background-color: #ef4444; }
    .trend-up { color: #ef4444; }
    .trend-down { color: #10b981; }
    .trend-stable { color: #6b7280; }
</style>
{% endblock %}

{% block content %}
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6">
    <!-- Page Header -->
    <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">Delinquent Loans Report</h1>
                <p class="text-gray-600 dark:text-gray-400 mt-1">Comprehensive analysis of overdue loans, collection status, and risk assessment</p>
            </div>
            <div class="flex gap-2">
                <a href="{% url 'reports:reports_dashboard' %}"
                    class="inline-flex items-center px-4 py-2 text-sm font-medium text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600 transition-colors">
                    <span>←</span> Back to Dashboard
                </a>
                <div class="relative">
                    <button id="exportDropdownBtn"
                        class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-purple-600 rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all transform hover:-translate-y-0.5">
                        <span>⬇️</span> Export Report
                        <span>﹀</span>
                    </button>
                    <div id="exportDropdown" class="export-dropdown dark:bg-gray-800 dark:border-gray-600">
                        <a href="?{{ request.GET.urlencode }}&format=pdf" class="block px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700">
                            <span>📄</span> Export as PDF
                        </a>
                        <a href="?{{ request.GET.urlencode }}&format=excel" class="block px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700">
                            <span>📊</span> Export as Excel
                        </a>
                        <a href="?{{ request.GET.urlencode }}&format=csv" class="block px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700">
                            <i class="fas fa-file-csv mr-2 text-blue-500"></i> Export as CSV
                        </a>
                        <a href="#" onclick="printReport()" class="block px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700">
                            <span>🖨️</span> Print Report
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Enhanced Filters -->
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 mb-8">
        <h2 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            <span>🔍</span> Advanced Filters & Date Range
        </h2>
        <form method="GET" class="space-y-4">
            <!-- Date Range Selection -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Quick Date Presets</label>
                    <select id="datePreset" onchange="applyDatePreset()"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        <option value="">Custom Range</option>
                        <option value="today">Today</option>
                        <option value="yesterday">Yesterday</option>
                        <option value="last7days">Last 7 Days</option>
                        <option value="last30days">Last 30 Days</option>
                        <option value="last90days">Last 90 Days</option>
                        <option value="thismonth">This Month</option>
                        <option value="lastmonth">Last Month</option>
                        <option value="thisyear">This Year</option>
                        <option value="lastyear">Last Year</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">From Date</label>
                    <input type="date" name="date_from" id="dateFrom" value="{{ filters.date_from }}"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">To Date</label>
                    <input type="date" name="date_to" id="dateTo" value="{{ filters.date_to }}"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                </div>
            </div>

            <!-- Additional Filters -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Delinquency Severity</label>
                    <select name="severity_filter"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        <option value="">All Severities</option>
                        <option value="mild" {% if filters.severity_filter == 'mild' %}selected{% endif %}>Mild (1-30 days)</option>
                        <option value="moderate" {% if filters.severity_filter == 'moderate' %}selected{% endif %}>Moderate (31-60 days)</option>
                        <option value="severe" {% if filters.severity_filter == 'severe' %}selected{% endif %}>Severe (60+ days)</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Amount Range</label>
                    <select name="amount_range"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        <option value="">All Amounts</option>
                        <option value="0-10000" {% if filters.amount_range == '0-10000' %}selected{% endif %}>KES 0 - 10,000</option>
                        <option value="10000-50000" {% if filters.amount_range == '10000-50000' %}selected{% endif %}>KES 10,000 - 50,000</option>
                        <option value="50000-100000" {% if filters.amount_range == '50000-100000' %}selected{% endif %}>KES 50,000 - 100,000</option>
                        <option value="100000+" {% if filters.amount_range == '100000+' %}selected{% endif %}>KES 100,000+</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Loan Type</label>
                    <select name="loan_type"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        <option value="">All Loan Types</option>
                        <option value="personal" {% if filters.loan_type == 'personal' %}selected{% endif %}>Personal Loans</option>
                        <option value="business" {% if filters.loan_type == 'business' %}selected{% endif %}>Business Loans</option>
                        <option value="emergency" {% if filters.loan_type == 'emergency' %}selected{% endif %}>Emergency Loans</option>
                        <option value="asset" {% if filters.loan_type == 'asset' %}selected{% endif %}>Asset-Based Loans</option>
                    </select>
                </div>
                <div class="flex items-end">
                    <button type="submit"
                        class="w-full px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors">
                        <span>🔍</span> Apply Filters
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- Enhanced Summary Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 border-l-4 border-yellow-500">
            <div class="flex items-center justify-between">
                <div>
                    <div class="flex items-center">
                        <span class="severity-indicator severity-mild"></span>
                        <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Mild Delinquent</p>
                    </div>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                        {{ report_data.summary.mild_delinquent_count|default:0 }}
                    </p>
                    <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                        KES {{ report_data.summary.mild_delinquent_amount|default:0|floatformat:0|intcomma }}
                    </p>
                </div>
                <div class="p-3 rounded-full bg-yellow-100 dark:bg-yellow-900">
                    <span>⚠️</span>
                </div>
            </div>
            <div class="mt-3 flex items-center text-xs">
                <span class="trend-up">
                    <span>↑</span> +{{ report_data.summary.mild_trend|default:0 }}%
                </span>
                <span class="text-gray-500 ml-2">vs last period</span>
            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 border-l-4 border-orange-500">
            <div class="flex items-center justify-between">
                <div>
                    <div class="flex items-center">
                        <span class="severity-indicator severity-moderate"></span>
                        <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Moderate Delinquent</p>
                    </div>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                        {{ report_data.summary.moderate_delinquent_count|default:0 }}
                    </p>
                    <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                        KES {{ report_data.summary.moderate_delinquent_amount|default:0|floatformat:0|intcomma }}
                    </p>
                </div>
                <div class="p-3 rounded-full bg-orange-100 dark:bg-orange-900">
                    <span>⚠️</span>
                </div>
            </div>
            <div class="mt-3 flex items-center text-xs">
                <span class="trend-up">
                    <span>↑</span> +{{ report_data.summary.moderate_trend|default:0 }}%
                </span>
                <span class="text-gray-500 ml-2">vs last period</span>
            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 border-l-4 border-red-500">
            <div class="flex items-center justify-between">
                <div>
                    <div class="flex items-center">
                        <span class="severity-indicator severity-severe"></span>
                        <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Severe Delinquent</p>
                    </div>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                        {{ report_data.summary.severe_delinquent_count|default:0 }}
                    </p>
                    <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                        KES {{ report_data.summary.severe_delinquent_amount|default:0|floatformat:0|intcomma }}
                    </p>
                </div>
                <div class="p-3 rounded-full bg-red-100 dark:bg-red-900">
                    <span>✕</span>
                </div>
            </div>
            <div class="mt-3 flex items-center text-xs">
                <span class="trend-down">
                    <span>↓</span> -{{ report_data.summary.severe_trend|default:0 }}%
                </span>
                <span class="text-gray-500 ml-2">vs last period</span>
            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 border-l-4 border-purple-500">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Total Amount Overdue</p>
                    <p class="text-2xl font-bold text-gray-900 dark:text-white mt-1">
                        KES {{ report_data.summary.total_amount_overdue|default:0|floatformat:0|intcomma }}
                    </p>
                    <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                        {{ report_data.summary.total_delinquent_count|default:0 }} total loans
                    </p>
                </div>
                <div class="p-3 rounded-full bg-purple-100 dark:bg-purple-900">
                    <span>$</span>
                </div>
            </div>
            <div class="mt-3 flex items-center text-xs">
                <span class="trend-stable">
                    <span>−</span> {{ report_data.summary.recovery_rate|default:0 }}%
                </span>
                <span class="text-gray-500 ml-2">recovery rate</span>
            </div>
        </div>
    </div>

    <!-- Additional Metrics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Collection Efficiency</h3>
                <span>📈</span>
            </div>
            <div class="space-y-3">
                <div class="flex justify-between items-center">
                    <span class="text-sm text-gray-600 dark:text-gray-400">Collections This Month</span>
                    <span class="font-semibold text-green-600">KES {{ report_data.summary.collections_this_month|default:0|floatformat:0|intcomma }}</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-sm text-gray-600 dark:text-gray-400">Average Days to Collect</span>
                    <span class="font-semibold text-gray-900 dark:text-white">{{ report_data.summary.avg_collection_days|default:0 }} days</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-sm text-gray-600 dark:text-gray-400">Success Rate</span>
                    <span class="font-semibold text-blue-600">{{ report_data.summary.collection_success_rate|default:0 }}%</span>
                </div>
            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Risk Assessment</h3>
                <i class="fas fa-shield-alt text-red-500 text-xl"></i>
            </div>
            <div class="space-y-3">
                <div class="flex justify-between items-center">
                    <span class="text-sm text-gray-600 dark:text-gray-400">High Risk Loans</span>
                    <span class="font-semibold text-red-600">{{ report_data.summary.high_risk_count|default:0 }}</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-sm text-gray-600 dark:text-gray-400">Potential Loss</span>
                    <span class="font-semibold text-red-600">KES {{ report_data.summary.potential_loss|default:0|floatformat:0|intcomma }}</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-sm text-gray-600 dark:text-gray-400">Risk Score</span>
                    <span class="font-semibold text-orange-600">{{ report_data.summary.risk_score|default:0 }}/100</span>
                </div>
            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Portfolio Health</h3>
                <i class="fas fa-heartbeat text-green-500 text-xl"></i>
            </div>
            <div class="space-y-3">
                <div class="flex justify-between items-center">
                    <span class="text-sm text-gray-600 dark:text-gray-400">Delinquency Rate</span>
                    <span class="font-semibold text-orange-600">{{ report_data.summary.delinquency_rate|default:0 }}%</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-sm text-gray-600 dark:text-gray-400">Portfolio at Risk</span>
                    <span class="font-semibold text-red-600">{{ report_data.summary.portfolio_at_risk|default:0 }}%</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-sm text-gray-600 dark:text-gray-400">Health Score</span>
                    <span class="font-semibold text-green-600">{{ report_data.summary.health_score|default:0 }}/100</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Interactive Charts Section -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <!-- Delinquency Distribution Pie Chart -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                <span>📊</span> Delinquency Distribution
            </h3>
            <div class="chart-container">
                <canvas id="delinquencyPieChart"></canvas>
            </div>
        </div>

        <!-- Amount Distribution Bar Chart -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                <span>📊</span> Amount by Severity
            </h3>
            <div class="chart-container">
                <canvas id="amountBarChart"></canvas>
            </div>
        </div>

        <!-- Delinquency Trend Line Chart -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                <span>📈</span> Delinquency Trends (Last 12 Months)
            </h3>
            <div class="chart-container">
                <canvas id="trendLineChart"></canvas>
            </div>
        </div>

        <!-- Collection Performance Chart -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                <span>📈</span> Collection Performance
            </h3>
            <div class="chart-container">
                <canvas id="collectionChart"></canvas>
            </div>
        </div>
    </div>

    <!-- Enhanced Delinquent Loans Table -->
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-semibold text-gray-900 dark:text-white">
                <i class="fas fa-table mr-2"></i> Delinquent Loans Details
            </h2>
            <div class="flex items-center space-x-4">
                <div class="flex items-center space-x-2">
                    <label class="text-sm text-gray-600 dark:text-gray-400">Show:</label>
                    <select id="entriesPerPage" onchange="updateTableEntries()"
                        class="px-2 py-1 border border-gray-300 rounded text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        <option value="10">10</option>
                        <option value="25" selected>25</option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                    </select>
                    <span class="text-sm text-gray-600 dark:text-gray-400">entries</span>
                </div>
                <div class="relative">
                    <input type="text" id="tableSearch" placeholder="Search loans..."
                        class="pl-8 pr-4 py-2 border border-gray-300 rounded-lg text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                        onkeyup="searchTable()">
                    <span>🔍</span>
                </div>
            </div>
        </div>
        
        {% if report_data.loans %}
        <div class="overflow-x-auto">
            <table id="delinquencyTable" class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                <thead class="bg-gradient-to-r from-blue-600 to-purple-600">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider cursor-pointer" onclick="sortTable(0)">
                            Loan # <i class="fas fa-sort ml-1"></i>
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider cursor-pointer" onclick="sortTable(1)">
                            Borrower <i class="fas fa-sort ml-1"></i>
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider cursor-pointer" onclick="sortTable(2)">
                            Contact <i class="fas fa-sort ml-1"></i>
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider cursor-pointer" onclick="sortTable(3)">
                            Days Overdue <i class="fas fa-sort ml-1"></i>
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider cursor-pointer" onclick="sortTable(4)">
                            Amount Overdue <i class="fas fa-sort ml-1"></i>
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider cursor-pointer" onclick="sortTable(5)">
                            Outstanding Balance <i class="fas fa-sort ml-1"></i>
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">
                            Risk Level
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">
                            Last Contact
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-white uppercase tracking-wider">
                            Actions
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                    {% for loan in report_data.loans %}
                    <tr class="hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">
                            <div class="flex items-center">
                                <span class="severity-indicator {% if loan.days_overdue <= 30 %}severity-mild{% elif loan.days_overdue <= 60 %}severity-moderate{% else %}severity-severe{% endif %}"></span>
                                {{ loan.loan_number }}
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">
                            <div>
                                <div class="font-medium">{{ loan.borrower_name }}</div>
                                <div class="text-xs text-gray-500">ID: {{ loan.borrower_id|default:"N/A" }}</div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">
                            <div>
                                <div>{{ loan.borrower_phone|default:"N/A" }}</div>
                                <div class="text-xs text-gray-500">{{ loan.borrower_email|default:"N/A" }}</div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-semibold">
                            <div class="{% if loan.days_overdue <= 30 %}text-yellow-600{% elif loan.days_overdue <= 60 %}text-orange-600{% else %}text-red-600{% endif %}">
                                {{ loan.days_overdue }} days
                                <div class="text-xs text-gray-500">Due: {{ loan.due_date|default:"N/A" }}</div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-semibold text-red-600 dark:text-red-400">
                            KES {{ loan.amount_overdue|floatformat:2|intcomma }}
                            <div class="text-xs text-gray-500">+ KES {{ loan.penalty_amount|default:0|floatformat:2|intcomma }} penalty</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">
                            KES {{ loan.outstanding_balance|floatformat:2|intcomma }}
                            <div class="text-xs text-gray-500">of KES {{ loan.original_amount|default:0|floatformat:2|intcomma }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            {% if loan.days_overdue <= 30 %}
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200">
                                    <span>⚠️</span> Low Risk
                                </span>
                            {% elif loan.days_overdue <= 60 %}
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200">
                                    <span>⚠️</span> Medium Risk
                                </span>
                            {% else %}
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200">
                                    <span>✕</span> High Risk
                                </span>
                            {% endif %}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ loan.last_contact_date|default:"Never" }}
                            <div class="text-xs">{{ loan.last_contact_method|default:"N/A" }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm">
                            <div class="flex space-x-2">
                                <a href="tel:{{ loan.borrower_phone }}" 
                                    class="inline-flex items-center px-2 py-1 text-xs font-medium text-blue-600 bg-blue-50 rounded hover:bg-blue-100 dark:bg-blue-900 dark:text-blue-200 dark:hover:bg-blue-800 transition-colors">
                                    <span>📞</span> Call
                                </a>
                                <a href="sms:{{ loan.borrower_phone }}" 
                                    class="inline-flex items-center px-2 py-1 text-xs font-medium text-green-600 bg-green-50 rounded hover:bg-green-100 dark:bg-green-900 dark:text-green-200 dark:hover:bg-green-800 transition-colors">
                                    <i class="fas fa-sms mr-1"></i> SMS
                                </a>
                                <button onclick="showLoanDetails('{{ loan.loan_number }}')"
                                    class="inline-flex items-center px-2 py-1 text-xs font-medium text-purple-600 bg-purple-50 rounded hover:bg-purple-100 dark:bg-purple-900 dark:text-purple-200 dark:hover:bg-purple-800 transition-colors">
                                    <i class="fas fa-eye mr-1"></i> View
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <div class="flex items-center justify-between mt-6">
            <div class="text-sm text-gray-700 dark:text-gray-300">
                Showing <span class="font-medium">1</span> to <span class="font-medium">{{ report_data.loans|length }}</span> of <span class="font-medium">{{ report_data.total_count|default:report_data.loans|length }}</span> results
            </div>
            <div class="flex space-x-2">
                <button class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-700">
                    Previous
                </button>
                <button class="px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700">
                    1
                </button>
                <button class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-700">
                    Next
                </button>
            </div>
        </div>
        {% else %}
        <div class="text-center py-12">
            <span>✓</span>
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-2">No delinquent loans found</h3>
            <p class="text-gray-600 dark:text-gray-400">All loans are current with their payments for the selected criteria.</p>
        </div>
        {% endif %}
    </div>
</div>

<script>
// Sample data - replace with actual data from Django context
const reportData = {
    delinquencyDistribution: {
        labels: ['Mild (1-30 days)', 'Moderate (31-60 days)', 'Severe (60+ days)'],
        data: [{{ report_data.summary.mild_delinquent_count|default:15 }}, {{ report_data.summary.moderate_delinquent_count|default:8 }}, {{ report_data.summary.severe_delinquent_count|default:3 }}],
        colors: ['#fbbf24', '#f97316', '#ef4444']
    },
    amountDistribution: {
        labels: ['Mild', 'Moderate', 'Severe'],
        data: [{{ report_data.summary.mild_delinquent_amount|default:150000 }}, {{ report_data.summary.moderate_delinquent_amount|default:320000 }}, {{ report_data.summary.severe_delinquent_amount|default:180000 }}],
        colors: ['#fbbf24', '#f97316', '#ef4444']
    },
    monthlyTrends: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        delinquent: [12, 15, 18, 14, 16, 20, 18, 22, 19, 17, 21, 26],
        recovered: [8, 12, 14, 11, 13, 16, 15, 18, 16, 14, 17, 20]
    },
    collectionPerformance: {
        labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
        collections: [45000, 52000, 38000, 61000],
        targets: [50000, 50000, 50000, 50000]
    }
};

// Initialize Charts
document.addEventListener('DOMContentLoaded', function() {
    initializeCharts();
    setupEventListeners();
});

function initializeCharts() {
    // Check if Chart is available
    if (typeof Chart === 'undefined') {
        console.error('Chart.js is not loaded');
        return;
    }
    
    try {
        // Delinquency Distribution Pie Chart
        const pieCtx = document.getElementById('delinquencyPieChart');
        if (pieCtx) {
            new Chart(pieCtx.getContext('2d'), {
                type: 'doughnut',
                data: {
                    labels: reportData.delinquencyDistribution.labels,
                    datasets: [{
                        data: reportData.delinquencyDistribution.data,
                        backgroundColor: reportData.delinquencyDistribution.colors,
                        borderWidth: 2,
                        borderColor: '#ffffff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                usePointStyle: true
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((context.parsed * 100) / total).toFixed(1);
                                    return context.label + ': ' + context.parsed + ' (' + percentage + '%)';
                                }
                            }
                        }
                    }
                }
            });
        }

        // Amount Distribution Bar Chart
        const barCtx = document.getElementById('amountBarChart');
        if (barCtx) {
            new Chart(barCtx.getContext('2d'), {
                type: 'bar',
                data: {
                    labels: reportData.amountDistribution.labels,
                    datasets: [{
                        label: 'Amount Overdue (KES)',
                        data: reportData.amountDistribution.data,
                        backgroundColor: reportData.amountDistribution.colors,
                        borderRadius: 8,
                        borderSkipped: false
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return 'KES ' + context.parsed.y.toLocaleString();
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return 'KES ' + (value / 1000) + 'K';
                                }
                            }
                        }
                    }
                }
            });
        }

        // Trend Line Chart
        const lineCtx = document.getElementById('trendLineChart');
        if (lineCtx) {
            new Chart(lineCtx.getContext('2d'), {
                type: 'line',
                data: {
                    labels: reportData.monthlyTrends.labels,
                    datasets: [{
                        label: 'New Delinquent',
                        data: reportData.monthlyTrends.delinquent,
                        borderColor: '#ef4444',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        tension: 0.4,
                        fill: true
                    }, {
                        label: 'Recovered',
                        data: reportData.monthlyTrends.recovered,
                        borderColor: '#10b981',
                        backgroundColor: 'rgba(16, 185, 129, 0.1)',
                        tension: 0.4,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top'
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    },
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    }
                }
            });
        }

        // Collection Performance Chart
        const collectionCtx = document.getElementById('collectionChart');
        if (collectionCtx) {
            new Chart(collectionCtx.getContext('2d'), {
                type: 'bar',
                data: {
                    labels: reportData.collectionPerformance.labels,
                    datasets: [{
                        label: 'Collections',
                        data: reportData.collectionPerformance.collections,
                        backgroundColor: '#3b82f6',
                        borderRadius: 8
                    }, {
                        label: 'Target',
                        data: reportData.collectionPerformance.targets,
                        backgroundColor: '#e5e7eb',
                        borderRadius: 8
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top'
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return context.dataset.label + ': KES ' + context.parsed.y.toLocaleString();
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return 'KES ' + (value / 1000) + 'K';
                                }
                            }
                        }
                    }
                }
            });
        }
    } catch (error) {
        console.error('Error initializing charts:', error);
    }
}

function setupEventListeners() {
    // Export dropdown toggle
    document.getElementById('exportDropdownBtn').addEventListener('click', function(e) {
        e.preventDefault();
        const dropdown = document.getElementById('exportDropdown');
        dropdown.classList.toggle('show');
    });

    // Close dropdown when clicking outside
    document.addEventListener('click', function(e) {
        if (!e.target.closest('#exportDropdownBtn') && !e.target.closest('#exportDropdown')) {
            document.getElementById('exportDropdown').classList.remove('show');
        }
    });
}

// Date preset functionality
function applyDatePreset() {
    const preset = document.getElementById('datePreset').value;
    const fromDate = document.getElementById('dateFrom');
    const toDate = document.getElementById('dateTo');
    const today = new Date();
    
    switch(preset) {
        case 'today':
            fromDate.value = toDate.value = today.toISOString().split('T')[0];
            break;
        case 'yesterday':
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            fromDate.value = toDate.value = yesterday.toISOString().split('T')[0];
            break;
        case 'last7days':
            const week = new Date(today);
            week.setDate(week.getDate() - 7);
            fromDate.value = week.toISOString().split('T')[0];
            toDate.value = today.toISOString().split('T')[0];
            break;
        case 'last30days':
            const month = new Date(today);
            month.setDate(month.getDate() - 30);
            fromDate.value = month.toISOString().split('T')[0];
            toDate.value = today.toISOString().split('T')[0];
            break;
        case 'last90days':
            const quarter = new Date(today);
            quarter.setDate(quarter.getDate() - 90);
            fromDate.value = quarter.toISOString().split('T')[0];
            toDate.value = today.toISOString().split('T')[0];
            break;
        case 'thismonth':
            fromDate.value = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0];
            toDate.value = today.toISOString().split('T')[0];
            break;
        case 'lastmonth':
            const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
            const lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 0);
            fromDate.value = lastMonth.toISOString().split('T')[0];
            toDate.value = lastMonthEnd.toISOString().split('T')[0];
            break;
        case 'thisyear':
            fromDate.value = new Date(today.getFullYear(), 0, 1).toISOString().split('T')[0];
            toDate.value = today.toISOString().split('T')[0];
            break;
        case 'lastyear':
            fromDate.value = new Date(today.getFullYear() - 1, 0, 1).toISOString().split('T')[0];
            toDate.value = new Date(today.getFullYear() - 1, 11, 31).toISOString().split('T')[0];
            break;
    }
}

// Export functions
// ... existing code ...
function exportToPDF() {
    try {
        console.log('Attempting PDF export...');
        
        // Check for jsPDF availability (version 2.5.1 structure)
        let jsPDFClass;
        if (typeof window.jspdf !== 'undefined' && window.jspdf.jsPDF) {
            jsPDFClass = window.jspdf.jsPDF;
        } else if (typeof jsPDF !== 'undefined') {
            jsPDFClass = jsPDF;
        } else {
            console.error('jsPDF not found in expected locations');
            throw new Error('jsPDF library not found. Please refresh the page and try again.');
        }
        
        console.log('jsPDF found, creating document...');
        const doc = new jsPDFClass('p', 'mm', 'a4');
        
        // Check if autoTable is available
        if (typeof doc.autoTable !== 'function') {
            console.warn('autoTable not available, using simple export');
            return exportToPDFSimple();
        }
        
        let yPos = 20;
        
        // Add header
        doc.setFontSize(24);
        doc.setFont(undefined, 'bold');
        doc.text('DELINQUENT LOANS REPORT', 105, yPos, { align: 'center' });
        yPos += 15;
        
        doc.setFontSize(12);
        doc.setFont(undefined, 'normal');
        doc.text('Generated on: ' + new Date().toLocaleDateString(), 105, yPos, { align: 'center' });
        yPos += 20;
        
        // Executive Summary
        doc.setFontSize(16);
        doc.setFont(undefined, 'bold');
        doc.text('EXECUTIVE SUMMARY', 20, yPos);
        yPos += 15;
        
        // Create summary table
        const summaryData = [
            ['Category', 'Count', 'Amount (KES)'],
            ['Mild Delinquent (1-30 days)', reportData.delinquencyDistribution.data[0].toString(), 'KES ' + reportData.amountDistribution.data[0].toLocaleString()],
            ['Moderate Delinquent (31-60 days)', reportData.delinquencyDistribution.data[1].toString(), 'KES ' + reportData.amountDistribution.data[1].toLocaleString()],
            ['Severe Delinquent (60+ days)', reportData.delinquencyDistribution.data[2].toString(), 'KES ' + reportData.amountDistribution.data[2].toLocaleString()]
        ];
        
        doc.autoTable({
            head: [summaryData[0]],
            body: summaryData.slice(1),
            startY: yPos,
            theme: 'grid',
            headStyles: { fillColor: [52, 152, 219] },
            styles: { fontSize: 10 }
        });
        
        yPos = doc.lastAutoTable.finalY + 20;
        
        // Add totals
        const totalAmount = reportData.amountDistribution.data.reduce((a, b) => a + b, 0);
        const totalCount = reportData.delinquencyDistribution.data.reduce((a, b) => a + b, 0);
        
        doc.setFontSize(12);
        doc.setFont(undefined, 'bold');
        doc.text('SUMMARY TOTALS', 20, yPos);
        yPos += 10;
        
        doc.setFontSize(10);
        doc.setFont(undefined, 'normal');
        doc.text(`Total Delinquent Loans: ${totalCount}`, 20, yPos);
        yPos += 8;
        doc.text(`Total Amount at Risk: KES ${totalAmount.toLocaleString()}`, 20, yPos);
        yPos += 8;
        doc.text(`Average per Loan: KES ${Math.round(totalAmount / totalCount).toLocaleString()}`, 20, yPos);
        
        // Save the PDF
        doc.save('delinquent-loans-report.pdf');
        
        // Hide dropdown
        const dropdown = document.getElementById('exportDropdown');
        if (dropdown) dropdown.classList.remove('show');
        
        alert('PDF report generated successfully!');
        console.log('PDF export completed successfully');
        
    } catch (error) {
        console.error('PDF Export Error:', error);
        alert('Error generating PDF: ' + error.message);
    }
}
// ... existing code ...

function exportToPDFSimple() {
    try {
        console.log('Attempting simple PDF export...');
        
        // Check for jsPDF availability
        let jsPDFClass;
        if (typeof window.jspdf !== 'undefined' && window.jspdf.jsPDF) {
            jsPDFClass = window.jspdf.jsPDF;
        } else if (typeof jsPDF !== 'undefined') {
            jsPDFClass = jsPDF;
        } else {
            throw new Error('jsPDF library not found. Please refresh the page and try again.');
        }
        
        const doc = new jsPDFClass();
        
        // Add title
        doc.setFontSize(20);
        doc.text('Delinquent Loans Report', 20, 20);
        
        // Add date
        doc.setFontSize(12);
        doc.text('Generated: ' + new Date().toLocaleDateString(), 20, 35);
        
        // Add summary
        let yPos = 50;
        doc.setFontSize(14);
        doc.text('Summary:', 20, yPos);
        yPos += 15;
        
        doc.setFontSize(10);
        doc.text(`Mild Delinquent: ${reportData.delinquencyDistribution.data[0]} loans - KES ${reportData.amountDistribution.data[0].toLocaleString()}`, 25, yPos);
        yPos += 8;
        doc.text(`Moderate Delinquent: ${reportData.delinquencyDistribution.data[1]} loans - KES ${reportData.amountDistribution.data[1].toLocaleString()}`, 25, yPos);
        yPos += 8;
        doc.text(`Severe Delinquent: ${reportData.delinquencyDistribution.data[2]} loans - KES ${reportData.amountDistribution.data[2].toLocaleString()}`, 25, yPos);
        yPos += 15;
        
        const totalAmount = reportData.amountDistribution.data.reduce((a, b) => a + b, 0);
        const totalCount = reportData.delinquencyDistribution.data.reduce((a, b) => a + b, 0);
        
        doc.setFontSize(12);
        doc.text('Totals:', 20, yPos);
        yPos += 10;
        doc.setFontSize(10);
        doc.text(`Total Loans: ${totalCount}`, 25, yPos);
        yPos += 8;
        doc.text(`Total Amount: KES ${totalAmount.toLocaleString()}`, 25, yPos);
        
        doc.save('delinquent-loans-simple-report.pdf');
        
        const dropdown = document.getElementById('exportDropdown');
        if (dropdown) dropdown.classList.remove('show');
        
        alert('Simple PDF report generated successfully!');
        console.log('Simple PDF export completed successfully');
        
    } catch (error) {
        console.error('Simple PDF Export Error:', error);
        alert('Error generating PDF: ' + error.message + '. Please refresh the page.');
    }
}

function exportToExcel() {
    const wb = XLSX.utils.book_new();
    
    // Create summary sheet
    const summaryData = [
        ['Delinquent Loans Report'],
        [''],
        ['Category', 'Count', 'Amount'],
        ['Mild Delinquent', reportData.delinquencyDistribution.data[0], reportData.amountDistribution.data[0]],
        ['Moderate Delinquent', reportData.delinquencyDistribution.data[1], reportData.amountDistribution.data[1]],
        ['Severe Delinquent', reportData.delinquencyDistribution.data[2], reportData.amountDistribution.data[2]]
    ];
    
    const ws = XLSX.utils.aoa_to_sheet(summaryData);
    XLSX.utils.book_append_sheet(wb, ws, 'Summary');
    
    // Create monthly trends sheet
    const trendsData = [
        ['Month', 'New Delinquent', 'Recovered', 'Net Change'],
        ...reportData.monthlyTrends.labels.map((month, index) => [
            month,
            reportData.monthlyTrends.delinquent[index],
            reportData.monthlyTrends.recovered[index],
            reportData.monthlyTrends.delinquent[index] - reportData.monthlyTrends.recovered[index]
        ])
    ];
    
    const trendsWs = XLSX.utils.aoa_to_sheet(trendsData);
    trendsWs['A1'].s = { font: { bold: true, sz: 14 } };
    XLSX.utils.book_append_sheet(wb, trendsWs, 'Monthly Trends');
    
    // Collection Performance Sheet
    const collectionData = [
        ['COLLECTION PERFORMANCE'],
        ['Period', 'Collections (KES)', 'Target (KES)', 'Achievement %', 'Variance (KES)'],
        ...reportData.collectionPerformance.labels.map((period, index) => [
            period,
            reportData.collectionPerformance.collections[index],
            reportData.collectionPerformance.targets[index],
            ((reportData.collectionPerformance.collections[index] / reportData.collectionPerformance.targets[index]) * 100).toFixed(1),
            reportData.collectionPerformance.collections[index] - reportData.collectionPerformance.targets[index]
        ])
    ];
    
    const collectionWs = XLSX.utils.aoa_to_sheet(collectionData);
    collectionWs['A1'].s = { font: { bold: true, sz: 14 } };
    XLSX.utils.book_append_sheet(wb, collectionWs, 'Collection Performance');
    
    // Detailed Loans Sheet
    const tableRows = document.querySelectorAll('#delinquencyTable tbody tr');
    const loansData = [['DETAILED LOAN LIST'], ['Loan Number', 'Borrower Name', 'Contact', 'Days Overdue', 'Amount Overdue (KES)', 'Outstanding Balance (KES)', 'Risk Level', 'Last Contact']];
    
    Array.from(tableRows).forEach(row => {
        const cells = row.querySelectorAll('td');
        if (cells.length >= 8) {
            loansData.push([
                cells[0].textContent.trim(),
                cells[1].textContent.trim().split('\n')[0],
                cells[2].textContent.trim().split('\n')[0],
                cells[3].textContent.trim().split(' ')[0],
                cells[4].textContent.trim().replace('KES ', '').replace(',', ''),
                cells[5].textContent.trim().replace('KES ', '').replace(',', ''),
                cells[6].textContent.trim(),
                cells[7].textContent.trim()
            ]);
        }
    });
    
    const loansWs = XLSX.utils.aoa_to_sheet(loansData);
    loansWs['A1'].s = { font: { bold: true, sz: 14 } };
    XLSX.utils.book_append_sheet(wb, loansWs, 'Detailed Loans');
    
    XLSX.writeFile(wb, 'delinquent-loans-comprehensive-report.xlsx');
    document.getElementById('exportDropdown').classList.remove('show');
}

function exportToCSV() {
    // Create comprehensive CSV with multiple sections
    let csvContent = 'DELINQUENT LOANS REPORT\n';
    csvContent += 'Generated: ' + new Date().toLocaleString() + '\n\n';
    
    // Summary section
    csvContent += 'SUMMARY STATISTICS\n';
    csvContent += 'Category,Count,Amount (KES),Percentage\n';
    
    const totalCount = reportData.delinquencyDistribution.data.reduce((a, b) => a + b, 0);
    const totalAmount = reportData.amountDistribution.data.reduce((a, b) => a + b, 0);
    
    reportData.delinquencyDistribution.labels.forEach((label, index) => {
        const count = reportData.delinquencyDistribution.data[index];
        const amount = reportData.amountDistribution.data[index];
        const percentage = ((count / totalCount) * 100).toFixed(1);
        csvContent += `"${label}",${count},${amount},${percentage}%\n`;
    });
    
    csvContent += `TOTAL,${totalCount},${totalAmount},100%\n\n`;
    
    // Monthly trends section
    csvContent += 'MONTHLY TRENDS\n';
    csvContent += 'Month,New Delinquent,Recovered,Net Change\n';
    
    reportData.monthlyTrends.labels.forEach((month, index) => {
        const newDel = reportData.monthlyTrends.delinquent[index];
        const recovered = reportData.monthlyTrends.recovered[index];
        const netChange = newDel - recovered;
        csvContent += `${month},${newDel},${recovered},${netChange}\n`;
    });
    
    csvContent += '\n';
    
    // Collection performance section
    csvContent += 'COLLECTION PERFORMANCE\n';
    csvContent += 'Period,Collections (KES),Target (KES),Achievement %\n';
    
    reportData.collectionPerformance.labels.forEach((period, index) => {
        const collections = reportData.collectionPerformance.collections[index];
        const target = reportData.collectionPerformance.targets[index];
        const achievement = ((collections / target) * 100).toFixed(1);
        csvContent += `${period},${collections},${target},${achievement}%\n`;
    });
    
    csvContent += '\n';
    
    // Detailed loans section
    csvContent += 'DETAILED LOAN LIST\n';
    csvContent += 'Loan Number,Borrower Name,Contact,Days Overdue,Amount Overdue (KES),Outstanding Balance (KES),Risk Level,Last Contact\n';
    
    const tableRows = document.querySelectorAll('#delinquencyTable tbody tr');
    Array.from(tableRows).forEach(row => {
        const cells = row.querySelectorAll('td');
        if (cells.length >= 8) {
            const rowData = [
                cells[0].textContent.trim(),
                cells[1].textContent.trim().split('\n')[0],
                cells[2].textContent.trim().split('\n')[0],
                cells[3].textContent.trim().split(' ')[0],
                cells[4].textContent.trim().replace('KES ', '').replace(',', ''),
                cells[5].textContent.trim().replace('KES ', '').replace(',', ''),
                cells[6].textContent.trim(),
                cells[7].textContent.trim()
            ].map(cell => `"${cell}"`).join(',');
            csvContent += rowData + '\n';
        }
    });
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'delinquent-loans-comprehensive-report.csv';
    a.click();
    window.URL.revokeObjectURL(url);
    document.getElementById('exportDropdown').classList.remove('show');
}

function printReport() {
    // Create a print-friendly version with enhanced styling
    const printWindow = window.open('', '_blank');
    const printContent = `
        <!DOCTYPE html>
        <html>
        <head>
            <title>Delinquent Loans Report</title>
            <style>
                @media print {
                    body { font-family: Arial, sans-serif; margin: 0; padding: 20px; }
                    .header { text-align: center; margin-bottom: 30px; border-bottom: 2px solid #333; padding-bottom: 20px; }
                    .header h1 { font-size: 24px; margin: 0; color: #333; }
                    .header p { margin: 5px 0; color: #666; }
                    .section { margin-bottom: 30px; page-break-inside: avoid; }
                    .section h2 { font-size: 18px; color: #333; border-bottom: 1px solid #ccc; padding-bottom: 5px; }
                    .metrics-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; margin: 20px 0; }
                    .metric-card { border: 1px solid #ddd; padding: 15px; border-radius: 5px; }
                    .metric-card h3 { margin: 0 0 10px 0; font-size: 14px; color: #666; }
                    .metric-card .value { font-size: 20px; font-weight: bold; color: #333; }
                    .metric-card .subvalue { font-size: 12px; color: #888; }
                    table { width: 100%; border-collapse: collapse; margin: 15px 0; }
                    th, td { border: 1px solid #ddd; padding: 8px; text-align: left; font-size: 11px; }
                    th { background-color: #f5f5f5; font-weight: bold; }
                    .severity-mild { color: #f59e0b; }
                    .severity-moderate { color: #f97316; }
                    .severity-severe { color: #ef4444; }
                    .chart-placeholder { border: 1px dashed #ccc; padding: 20px; text-align: center; color: #666; margin: 15px 0; }
                    @page { margin: 1in; }
                }
            </style>
        </head>
        <body>
            <div class="header">
                <h1>DELINQUENT LOANS REPORT</h1>
                <p>Comprehensive Analysis of Overdue Loans</p>
                <p>Generated on: ${new Date().toLocaleString()}</p>
            </div>
            
            <div class="section">
                <h2>Executive Summary</h2>
                <div class="metrics-grid">
                    <div class="metric-card">
                        <h3>Mild Delinquent (1-30 days)</h3>
                        <div class="value severity-mild">${reportData.delinquencyDistribution.data[0]}</div>
                        <div class="subvalue">KES ${reportData.amountDistribution.data[0].toLocaleString()}</div>
                    </div>
                    <div class="metric-card">
                        <h3>Moderate Delinquent (31-60 days)</h3>
                        <div class="value severity-moderate">${reportData.delinquencyDistribution.data[1]}</div>
                        <div class="subvalue">KES ${reportData.amountDistribution.data[1].toLocaleString()}</div>
                    </div>
                    <div class="metric-card">
                        <h3>Severe Delinquent (60+ days)</h3>
                        <div class="value severity-severe">${reportData.delinquencyDistribution.data[2]}</div>
                        <div class="subvalue">KES ${reportData.amountDistribution.data[2].toLocaleString()}</div>
                    </div>
                    <div class="metric-card">
                        <h3>Total Amount at Risk</h3>
                        <div class="value">KES ${reportData.amountDistribution.data.reduce((a, b) => a + b, 0).toLocaleString()}</div>
                        <div class="subvalue">${reportData.delinquencyDistribution.data.reduce((a, b) => a + b, 0)} total loans</div>
                    </div>
                </div>
            </div>
            
            <div class="section">
                <h2>Monthly Trends Analysis</h2>
                <table>
                    <thead>
                        <tr>
                            <th>Month</th>
                            <th>New Delinquent</th>
                            <th>Recovered</th>
                            <th>Net Change</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${reportData.monthlyTrends.labels.map((month, index) => `
                            <tr>
                                <td>${month}</td>
                                <td>${reportData.monthlyTrends.delinquent[index]}</td>
                                <td>${reportData.monthlyTrends.recovered[index]}</td>
                                <td>${reportData.monthlyTrends.delinquent[index] - reportData.monthlyTrends.recovered[index]}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
            
            <div class="section">
                <h2>Collection Performance</h2>
                <table>
                    <thead>
                        <tr>
                            <th>Period</th>
                            <th>Collections (KES)</th>
                            <th>Target (KES)</th>
                            <th>Achievement %</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${reportData.collectionPerformance.labels.map((period, index) => `
                            <tr>
                                <td>${period}</td>
                                <td>${reportData.collectionPerformance.collections[index].toLocaleString()}</td>
                                <td>${reportData.collectionPerformance.targets[index].toLocaleString()}</td>
                                <td>${((reportData.collectionPerformance.collections[index] / reportData.collectionPerformance.targets[index]) * 100).toFixed(1)}%</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
            
            <div class="section">
                <h2>Detailed Loan List</h2>
                ${document.getElementById('delinquencyTable').outerHTML}
            </div>
            
            <div style="margin-top: 50px; text-align: center; font-size: 10px; color: #666;">
                <p>Confidential - Branch Management System | Generated: ${new Date().toLocaleString()}</p>
            </div>
        </body>
        </html>
    `;
    
    printWindow.document.write(printContent);
    printWindow.document.close();
    
    setTimeout(() => {
        printWindow.print();
        printWindow.close();
    }, 500);
    
    document.getElementById('exportDropdown').classList.remove('show');
}

// Table functionality
function searchTable() {
    const input = document.getElementById('tableSearch');
    const filter = input.value.toUpperCase();
    const table = document.getElementById('delinquencyTable');
    const rows = table.getElementsByTagName('tr');
    
    for (let i = 1; i < rows.length; i++) {
        const cells = rows[i].getElementsByTagName('td');
        let found = false;
        
        for (let j = 0; j < cells.length; j++) {
            if (cells[j].textContent.toUpperCase().indexOf(filter) > -1) {
                found = true;
                break;
            }
        }
        
        rows[i].style.display = found ? '' : 'none';
    }
}

function sortTable(columnIndex) {
    const table = document.getElementById('delinquencyTable');
    const tbody = table.getElementsByTagName('tbody')[0];
    const rows = Array.from(tbody.getElementsByTagName('tr'));
    
    rows.sort((a, b) => {
        const aText = a.getElementsByTagName('td')[columnIndex].textContent.trim();
        const bText = b.getElementsByTagName('td')[columnIndex].textContent.trim();
        
        if (!isNaN(aText) && !isNaN(bText)) {
            return parseFloat(aText) - parseFloat(bText);
        }
        
        return aText.localeCompare(bText);
    });
    
    rows.forEach(row => tbody.appendChild(row));
}

function updateTableEntries() {
    // Implementation for changing table entries per page
    console.log('Update table entries:', document.getElementById('entriesPerPage').value);
}

function showLoanDetails(loanNumber) {
    alert('Show details for loan: ' + loanNumber);
    // Implementation for showing loan details modal
}
</script>
{% endblock %}
