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

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

{% block extra_css %}
<!-- Add Chart.js library -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/date-fns@2.29.3/index.min.js"></script>

<style>
.chart-container {
    position: relative;
    height: 300px;
    margin: 20px 0;
}
    .urgency-critical {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        animation: pulse 2s infinite;
    }
    
    .urgency-high {
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    }
    
    .urgency-medium {
        background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    }
    
    .urgency-low {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    }
    
    .contact-btn {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
    
    .contact-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    }
    
    .loan-row {
        transition: all 0.3s ease;
        border-left: 4px solid transparent;
    }
    
    .loan-row:hover {
        background: rgba(59, 130, 246, 0.05);
        border-left-color: #3b82f6;
        transform: translateX(4px);
    }
    
    .loan-row.critical {
        border-left-color: #ef4444;
        background: rgba(239, 68, 68, 0.02);
    }
    
    .loan-row.high {
        border-left-color: #f59e0b;
        background: rgba(245, 158, 11, 0.02);
    }
    
    .stats-card {
        background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.7) 100%);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
    
    .stats-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    }
    
    .filter-panel {
        background: linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(147, 51, 234, 0.1) 100%);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(59, 130, 246, 0.2);
    }
    
    @keyframes slideIn {
        from { opacity: 0; transform: translateY(20px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .slide-in {
        animation: slideIn 0.6s ease-out;
    }
    
    .notification-dot {
        animation: pulse 2s infinite;
    }
    
    @media print {
        .no-print { display: none !important; }
        .loan-row { border-left: none !important; }
        .stats-card { box-shadow: none !important; }
    }
</style>
{% endblock %}

{% block content %}
<div class="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900 transition-all duration-300">
<div class="p-6">
    <!-- Page Header -->
    <div class="mb-8 slide-in">
        <div class="bg-gradient-to-r from-blue-600 via-purple-600 to-blue-800 rounded-2xl shadow-2xl p-8 text-white">
            <div class="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6">
                <div>
                    <div class="flex items-center gap-3 mb-3">
                        <div class="p-3 bg-white/20 rounded-xl backdrop-blur-sm">
                            <i class="fas fa-calendar-day text-2xl"></i>
                        </div>
                        <div>
                            <h1 class="text-3xl font-bold">Loans Due Report</h1>
                            <div class="flex items-center gap-2 mt-1">
                                {% if report_data.summary.today_due_count > 0 %}
                                    <span class="notification-dot w-3 h-3 bg-red-400 rounded-full"></span>
                                {% endif %}
                                <p class="text-blue-100">
                                    {% if filters.today_only %}
                                        Loans due today ({{ "now"|date:"M d, Y" }})
                                    {% else %}
                                        {% if filters.start_date and filters.end_date %}
                                            From {{ filters.start_date|date:"M d, Y" }} to {{ filters.end_date|date:"M d, Y" }}
                                        {% else %}
                                            All upcoming due loans
                                        {% endif %}
                                    {% endif %}
                                </p>
                            </div>
                        </div>
                    </div>
                    <div class="flex flex-wrap gap-3">
                        <span class="px-3 py-1 bg-white/20 rounded-full text-sm font-medium backdrop-blur-sm">
                            <span>⏰</span> Last updated: {% now "H:i" %}
                        </span>
                        <span class="px-3 py-1 bg-white/20 rounded-full text-sm font-medium backdrop-blur-sm">
                            <span>📅</span> {{ "now"|date:"l, M d, Y" }}
                        </span>
                    </div>
                </div>
                <div class="flex flex-col sm:flex-row gap-3 no-print">
                    <button onclick="window.print()" 
                        class="inline-flex items-center px-6 py-3 bg-white/20 hover:bg-white/30 rounded-xl font-semibold transition-all transform hover:-translate-y-1 backdrop-blur-sm">
                        <span>🖨️</span> Print Report
                    </button>
                    <a href="?{% for key, value in request.GET.items %}{% if key != 'format' %}{{ key }}={{ value }}&{% endif %}{% endfor %}format=pdf" 
                        class="inline-flex items-center px-6 py-3 bg-white text-blue-600 hover:bg-blue-50 rounded-xl font-semibold transition-all transform hover:-translate-y-1 shadow-lg">
                        <span>⬇️</span> Export PDF
                    </a>
                    <button onclick="refreshData()" 
                        class="inline-flex items-center px-6 py-3 bg-green-500 hover:bg-green-600 rounded-xl font-semibold transition-all transform hover:-translate-y-1">
                        <span>🔄</span> Refresh
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Advanced Filters -->
    <div class="filter-panel rounded-2xl p-6 mb-8 slide-in no-print">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
                <span>🔍</span>
                Advanced Filters
            </h2>
            <button onclick="toggleFilters()" class="text-blue-600 hover:text-blue-800 font-medium">
                <span>﹀</span>
            </button>
        </div>
        
        <div id="filter-content" class="space-y-6">
            <form method="get" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 xl:grid-cols-6 gap-4">
                <div>
                    <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Start Date</label>
                    <input type="date" name="start_date" id="start_date"
                        value="{{ filters.start_date|date:'Y-m-d' }}"
                        class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white transition-all">
                </div>
                
                <div>
                    <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">End Date</label>
                    <input type="date" name="end_date" id="end_date"
                        value="{{ filters.end_date|date:'Y-m-d' }}"
                        class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white transition-all">
                </div>
                
                <div>
                    <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Quick Filter</label>
                    <select name="quick_filter" onchange="applyQuickFilter(this.value)"
                        class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white transition-all">
                        <option value="">Select Period</option>
                        <option value="today" {% if filters.today_only %}selected{% endif %}>Today Only</option>
                        <option value="tomorrow">Tomorrow</option>
                        <option value="week">This Week</option>
                        <option value="month">This Month</option>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Amount Range</label>
                    <select name="amount_range" value="{{ filters.amount_range }}"
                        class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white transition-all">
                        <option value="">All Amounts</option>
                        <option value="0-5000" {% if filters.amount_range == '0-5000' %}selected{% endif %}>KES 0 - 5,000</option>
                        <option value="5000-20000" {% if filters.amount_range == '5000-20000' %}selected{% endif %}>KES 5,000 - 20,000</option>
                        <option value="20000-50000" {% if filters.amount_range == '20000-50000' %}selected{% endif %}>KES 20,000 - 50,000</option>
                        <option value="50000+" {% if filters.amount_range == '50000+' %}selected{% endif %}>KES 50,000+</option>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Urgency Level</label>
                    <select name="urgency" value="{{ filters.urgency }}"
                        class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white transition-all">
                        <option value="">All Urgency</option>
                        <option value="critical" {% if filters.urgency == 'critical' %}selected{% endif %}>Critical (Due Today)</option>
                        <option value="high" {% if filters.urgency == 'high' %}selected{% endif %}>High (Due Tomorrow)</option>
                        <option value="medium" {% if filters.urgency == 'medium' %}selected{% endif %}>Medium (This Week)</option>
                        <option value="low" {% if filters.urgency == 'low' %}selected{% endif %}>Low (Future)</option>
                    </select>
                </div>
                
                <div class="flex items-end gap-2">
                    <button type="submit"
                        class="flex-1 px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-xl font-semibold hover:from-blue-700 hover:to-purple-700 transition-all transform hover:-translate-y-1 shadow-lg">
                        <span>🔍</span> Apply
                    </button>
                    <a href="{% url 'reports:loans_due_report' %}"
                        class="px-4 py-3 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-xl transition-all">
                        <span>✕</span>
                    </a>
                </div>
                
                <input type="hidden" name="today_only" id="today_only_hidden" value="{% if filters.today_only %}true{% endif %}">
            </form>
        </div>
    </div>

    <!-- Critical Summary Statistics -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8 slide-in">
        <!-- Total Loans Due -->
        <div class="stats-card rounded-2xl p-6 hover-lift">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wider">Total Loans Due</p>
                    <p class="text-3xl font-bold text-gray-900 dark:text-white mt-2">
                        {{ report_data.summary.total_loans_due|default:0 }}
                    </p>
                    <div class="flex items-center mt-2">
                        <span class="text-sm text-gray-500">
                            {% if report_data.summary.total_loans_due > 0 %}
                                <span>↑</span>
                                Active monitoring required
                            {% else %}
                                <span>✓</span>
                                All clear
                            {% endif %}
                        </span>
                    </div>
                </div>
                <div class="p-4 bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl">
                    <i class="fas fa-list-alt text-white text-2xl"></i>
                </div>
            </div>
        </div>

        <!-- Total Amount Due -->
        <div class="stats-card rounded-2xl p-6 hover-lift">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wider">Total Amount Due</p>
                    <p class="text-3xl font-bold text-gray-900 dark:text-white mt-2">
                        KES {{ report_data.summary.total_amount_due|default:0|floatformat:0|intcomma }}
                    </p>
                    <div class="flex items-center mt-2">
                        <span class="text-sm text-green-600">
                            <span>💵</span>
                            Expected collections
                        </span>
                    </div>
                </div>
                <div class="p-4 bg-gradient-to-br from-green-500 to-green-600 rounded-xl">
                    <span>$</span>
                </div>
            </div>
        </div>

        <!-- Due Today (Critical) -->
        <div class="stats-card rounded-2xl p-6 hover-lift {% if report_data.summary.today_due_count > 0 %}ring-2 ring-red-200 bg-red-50 dark:bg-red-900/20{% endif %}">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wider">Due Today</p>
                    <p class="text-3xl font-bold {% if report_data.summary.today_due_count > 0 %}text-red-600{% else %}text-gray-900 dark:text-white{% endif %} mt-2">
                        {{ report_data.summary.today_due_count|default:0 }}
                    </p>
                    <div class="flex items-center mt-2">
                        {% if report_data.summary.today_due_count > 0 %}
                            <span class="text-sm text-red-600 font-semibold">
                                <span>⚠️</span>
                                Immediate attention required
                            </span>
                        {% else %}
                            <span class="text-sm text-green-600">
                                <span>✓</span>
                                No urgent collections
                            </span>
                        {% endif %}
                    </div>
                </div>
                <div class="p-4 bg-gradient-to-br {% if report_data.summary.today_due_count > 0 %}from-red-500 to-red-600{% else %}from-gray-400 to-gray-500{% endif %} rounded-xl">
                    <i class="fas fa-calendar-day text-white text-2xl"></i>
                </div>
            </div>
        </div>

        <!-- Due This Week -->
        <div class="stats-card rounded-2xl p-6 hover-lift">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wider">Due This Week</p>
                    <p class="text-3xl font-bold text-gray-900 dark:text-white mt-2">
                        {{ report_data.summary.week_due_count|default:0 }}
                    </p>
                    <div class="flex items-center mt-2">
                        <span class="text-sm text-orange-600">
                            <i class="fas fa-calendar-week mr-1"></i>
                            Plan collections
                        </span>
                    </div>
                </div>
                <div class="p-4 bg-gradient-to-br from-orange-500 to-orange-600 rounded-xl">
                    <i class="fas fa-calendar-week text-white text-2xl"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Enhanced Loans Table -->
    <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl overflow-hidden slide-in">
        <div class="bg-gradient-to-r from-gray-50 to-gray-100 dark:from-gray-700 dark:to-gray-800 px-8 py-6 border-b border-gray-200 dark:border-gray-700">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                <div>
                    <h2 class="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-3">
                        <i class="fas fa-list-alt text-blue-600"></i>
                        Loans Due Details
                        <span class="text-lg font-normal text-gray-600 dark:text-gray-400">
                            ({{ report_data.loans|length }} loans)
                        </span>
                    </h2>
                    <p class="text-gray-600 dark:text-gray-400 mt-1">Click on any loan for detailed actions</p>
                </div>
                <div class="flex gap-3 no-print">
                    <button onclick="selectAllLoans()" 
                        class="px-4 py-2 bg-blue-100 hover:bg-blue-200 text-blue-700 rounded-lg font-medium transition-all">
                        <i class="fas fa-check-square mr-2"></i> Select All
                    </button>
                    <button onclick="bulkActions()" 
                        class="px-4 py-2 bg-green-100 hover:bg-green-200 text-green-700 rounded-lg font-medium transition-all">
                        <span>⚡</span> Bulk Actions
                    </button>
                </div>
            </div>
        </div>

        {% if report_data.loans %}
        <div class="overflow-x-auto">
            <table 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-4 text-left text-xs font-bold text-white uppercase tracking-wider no-print">
                            <input type="checkbox" id="select-all" class="rounded border-white/30 bg-white/20 text-blue-600 focus:ring-blue-500">
                        </th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-white uppercase tracking-wider">Loan Details</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-white uppercase tracking-wider">Borrower Info</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-white uppercase tracking-wider">Financial Info</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-white uppercase tracking-wider">Due Date & Urgency</th>
                        <th class="px-6 py-4 text-left text-xs font-bold text-white uppercase tracking-wider no-print">Quick 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="loan-row {% with days_until=loan.days_until_due.days %}{% if days_until == 0 %}critical{% elif days_until == 1 %}high{% endif %}{% endwith %}" 
                        data-loan-id="{{ loan.id }}" data-phone="{{ loan.borrower__phone_number }}">
                        
                        <!-- Selection Checkbox -->
                        <td class="px-6 py-4 whitespace-nowrap no-print">
                            <input type="checkbox" class="loan-checkbox rounded border-gray-300 text-blue-600 focus:ring-blue-500" 
                                   value="{{ loan.id }}">
                        </td>

                        <!-- Loan Details -->
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="flex-shrink-0 h-12 w-12">
                                    <div class="h-12 w-12 rounded-xl bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
                                        <i class="fas fa-file-invoice-dollar text-white text-lg"></i>
                                    </div>
                                </div>
                                <div class="ml-4">
                                    <div class="text-lg font-bold text-gray-900 dark:text-white">
                                        {{ loan.loan_number }}
                                    </div>
                                    <div class="text-sm text-gray-600 dark:text-gray-400">
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
                                            {{ loan.application__loan_product__name|default:"Standard Loan" }}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </td>

                        <!-- Borrower Info -->
                        <td class="px-6 py-4">
                            <div class="space-y-1">
                                <div class="text-lg font-semibold text-gray-900 dark:text-white">
                                    {{ loan.borrower__first_name }} {{ loan.borrower__last_name }}
                                </div>
                                <div class="flex items-center text-sm text-gray-600 dark:text-gray-400">
                                    <span>📞</span>
                                    <a href="tel:{{ loan.borrower__phone_number }}" 
                                       class="hover:text-green-600 transition-colors font-medium">
                                        {{ loan.borrower__phone_number|default:"No phone" }}
                                    </a>
                                </div>
                                {% if loan.borrower__email %}
                                <div class="flex items-center text-sm text-gray-600 dark:text-gray-400">
                                    <span>✉️</span>
                                    <a href="mailto:{{ loan.borrower__email }}" 
                                       class="hover:text-blue-600 transition-colors">
                                        {{ loan.borrower__email|truncatechars:25 }}
                                    </a>
                                </div>
                                {% endif %}
                            </div>
                        </td>

                        <!-- Financial Info -->
                        <td class="px-6 py-4">
                            <div class="space-y-2">
                                <div>
                                    <span class="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Principal</span>
                                    <div class="text-lg font-semibold text-gray-900 dark:text-white">
                                        KES {{ loan.principal_amount|floatformat:0|intcomma }}
                                    </div>
                                </div>
                                <div>
                                    <span class="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Outstanding</span>
                                    <div class="text-lg font-bold text-red-600 dark:text-red-400">
                                        KES {{ loan.outstanding_balance|floatformat:0|intcomma }}
                                    </div>
                                </div>
                                <div class="w-full bg-gray-200 rounded-full h-2 dark:bg-gray-700">
                                    {% widthratio loan.outstanding_balance loan.principal_amount 100 as progress %}
                                    <div class="bg-gradient-to-r from-red-500 to-red-600 h-2 rounded-full transition-all" 
                                         style="width: {{ progress }}%"></div>
                                </div>
                            </div>
                        </td>

                        <!-- Due Date & Urgency -->
                        <td class="px-6 py-4">
                            <div class="space-y-3">
                                <div>
                                    <div class="text-lg font-semibold text-gray-900 dark:text-white">
                                        {{ loan.due_date|date:"M d, Y" }}
                                    </div>
                                    <div class="text-sm text-gray-600 dark:text-gray-400">
                                        {{ loan.due_date|date:"l, H:i" }}
                                    </div>
                                </div>
                                
                                {% with days_until=loan.days_until_due.days %}
                                <div>
                                    {% if days_until == 0 %}
                                        <span class="urgency-critical inline-flex items-center px-3 py-1 rounded-full text-sm font-bold text-white">
                                            <span>⚠️</span>
                                            DUE TODAY
                                        </span>
                                    {% elif days_until == 1 %}
                                        <span class="urgency-high inline-flex items-center px-3 py-1 rounded-full text-sm font-bold text-white">
                                            <span>⏰</span>
                                            Due Tomorrow
                                        </span>
                                    {% elif days_until <= 7 %}
                                        <span class="urgency-medium inline-flex items-center px-3 py-1 rounded-full text-sm font-bold text-white">
                                            <span>📅</span>
                                            {{ days_until }} days
                                        </span>
                                    {% else %}
                                        <span class="urgency-low inline-flex items-center px-3 py-1 rounded-full text-sm font-bold text-white">
                                            <i class="fas fa-calendar-plus mr-2"></i>
                                            {{ days_until }} days
                                        </span>
                                    {% endif %}
                                </div>
                                {% endwith %}
                            </div>
                        </td>

                        <!-- Quick Actions -->
                        <td class="px-6 py-4 whitespace-nowrap no-print">
                            <div class="flex flex-col gap-2">
                                <button onclick="callBorrower('{{ loan.borrower__phone_number }}', '{{ loan.borrower__first_name }} {{ loan.borrower__last_name }}')" 
                                    class="contact-btn inline-flex items-center px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg font-semibold transition-all">
                                    <span>📞</span> Call
                                </button>
                                <button onclick="sendSMS('{{ loan.borrower__phone_number }}', '{{ loan.loan_number }}')" 
                                    class="contact-btn inline-flex items-center px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg font-semibold transition-all">
                                    <i class="fas fa-sms mr-2"></i> SMS
                                </button>
                                <button onclick="recordPayment('{{ loan.id }}')" 
                                    class="contact-btn inline-flex items-center px-4 py-2 bg-purple-500 hover:bg-purple-600 text-white rounded-lg font-semibold transition-all">
                                    <span>💵</span> Payment
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <div class="text-center py-16">
            <div class="mx-auto w-24 h-24 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center mb-6">
                <span>✓</span>
            </div>
            <h3 class="text-2xl font-bold text-gray-900 dark:text-white mb-2">All Clear!</h3>
            <p class="text-gray-600 dark:text-gray-400 text-lg">No loans are due in the selected period.</p>
            <p class="text-gray-500 dark:text-gray-500 mt-2">Your portfolio is up to date.</p>
        </div>
        {% endif %}
    </div>

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

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

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

        <!-- Collection Priority Doughnut Chart -->
        <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-6">
            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                <i class="fas fa-bullseye mr-2 text-red-600"></i> Collection Priority
            </h3>
            <div class="chart-container">
                <canvas id="priorityDoughnutChart"></canvas>
            </div>
        </div>
    </div>

    <!-- Quick Action Panels -->
    {% if report_data.categorized.today or report_data.categorized.tomorrow or report_data.categorized.this_week %}
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mt-8 slide-in">
        <!-- Critical: Due Today -->
        {% if report_data.categorized.today %}
        <div class="bg-gradient-to-br from-red-50 to-red-100 dark:from-red-900/20 dark:to-red-800/20 rounded-2xl overflow-hidden shadow-lg border border-red-200 dark:border-red-800">
            <div class="bg-gradient-to-r from-red-500 to-red-600 px-6 py-4">
                <h3 class="text-lg font-bold text-white flex items-center gap-2">
                    <span>⚠️</span>
                    Critical: Due Today
                    <span class="bg-white/20 px-2 py-1 rounded-full text-sm">{{ report_data.categorized.today|length }}</span>
                </h3>
            </div>
            <div class="p-4 space-y-3 max-h-80 overflow-y-auto">
                {% for loan in report_data.categorized.today|slice:":8" %}
                <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm border border-red-100 dark:border-red-800/50">
                    <div class="flex justify-between items-start">
                        <div class="flex-1">
                            <div class="font-bold text-gray-900 dark:text-white">{{ loan.loan_number }}</div>
                            <div class="text-sm text-gray-600 dark:text-gray-400">{{ loan.borrower__first_name }} {{ loan.borrower__last_name }}</div>
                            <div class="text-xs text-gray-500 dark:text-gray-500 mt-1">{{ loan.borrower__phone_number }}</div>
                        </div>
                        <div class="text-right">
                            <div class="font-bold text-red-600 dark:text-red-400">KES {{ loan.outstanding_balance|floatformat:0|intcomma }}</div>
                            <button onclick="callBorrower('{{ loan.borrower__phone_number }}', '{{ loan.borrower__first_name }} {{ loan.borrower__last_name }}')" 
                                class="mt-2 px-3 py-1 bg-red-500 hover:bg-red-600 text-white text-xs rounded-lg transition-all">
                                <span>📞</span> Call Now
                            </button>
                        </div>
                    </div>
                </div>
                {% endfor %}
                {% if report_data.categorized.today|length > 8 %}
                <div class="text-center py-2">
                    <button onclick="showAllToday()" class="text-red-600 hover:text-red-800 font-medium text-sm">
                        View {{ report_data.categorized.today|length|add:"-8" }} more...
                    </button>
                </div>
                {% endif %}
            </div>
        </div>
        {% endif %}

        <!-- High Priority: Due Tomorrow -->
        {% if report_data.categorized.tomorrow %}
        <div class="bg-gradient-to-br from-orange-50 to-orange-100 dark:from-orange-900/20 dark:to-orange-800/20 rounded-2xl overflow-hidden shadow-lg border border-orange-200 dark:border-orange-800">
            <div class="bg-gradient-to-r from-orange-500 to-orange-600 px-6 py-4">
                <h3 class="text-lg font-bold text-white flex items-center gap-2">
                    <span>⏰</span>
                    High: Due Tomorrow
                    <span class="bg-white/20 px-2 py-1 rounded-full text-sm">{{ report_data.categorized.tomorrow|length }}</span>
                </h3>
            </div>
            <div class="p-4 space-y-3 max-h-80 overflow-y-auto">
                {% for loan in report_data.categorized.tomorrow|slice:":8" %}
                <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm border border-orange-100 dark:border-orange-800/50">
                    <div class="flex justify-between items-start">
                        <div class="flex-1">
                            <div class="font-bold text-gray-900 dark:text-white">{{ loan.loan_number }}</div>
                            <div class="text-sm text-gray-600 dark:text-gray-400">{{ loan.borrower__first_name }} {{ loan.borrower__last_name }}</div>
                            <div class="text-xs text-gray-500 dark:text-gray-500 mt-1">{{ loan.borrower__phone_number }}</div>
                        </div>
                        <div class="text-right">
                            <div class="font-bold text-orange-600 dark:text-orange-400">KES {{ loan.outstanding_balance|floatformat:0|intcomma }}</div>
                            <button onclick="sendSMS('{{ loan.borrower__phone_number }}', '{{ loan.loan_number }}')" 
                                class="mt-2 px-3 py-1 bg-orange-500 hover:bg-orange-600 text-white text-xs rounded-lg transition-all">
                                <i class="fas fa-sms mr-1"></i> Remind
                            </button>
                        </div>
                    </div>
                </div>
                {% endfor %}
                {% if report_data.categorized.tomorrow|length > 8 %}
                <div class="text-center py-2">
                    <button onclick="showAllTomorrow()" class="text-orange-600 hover:text-orange-800 font-medium text-sm">
                        View {{ report_data.categorized.tomorrow|length|add:"-8" }} more...
                    </button>
                </div>
                {% endif %}
            </div>
        </div>
        {% endif %}

        <!-- Medium Priority: Due This Week -->
        {% if report_data.categorized.this_week %}
        <div class="bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-900/20 dark:to-blue-800/20 rounded-2xl overflow-hidden shadow-lg border border-blue-200 dark:border-blue-800">
            <div class="bg-gradient-to-r from-blue-500 to-blue-600 px-6 py-4">
                <h3 class="text-lg font-bold text-white flex items-center gap-2">
                    <i class="fas fa-calendar-week"></i>
                    Medium: This Week
                    <span class="bg-white/20 px-2 py-1 rounded-full text-sm">{{ report_data.categorized.this_week|length }}</span>
                </h3>
            </div>
            <div class="p-4 space-y-3 max-h-80 overflow-y-auto">
                {% for loan in report_data.categorized.this_week|slice:":8" %}
                <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm border border-blue-100 dark:border-blue-800/50">
                    <div class="flex justify-between items-start">
                        <div class="flex-1">
                            <div class="font-bold text-gray-900 dark:text-white">{{ loan.loan_number }}</div>
                            <div class="text-sm text-gray-600 dark:text-gray-400">{{ loan.borrower__first_name }} {{ loan.borrower__last_name }}</div>
                            <div class="text-xs text-gray-500 dark:text-gray-500 mt-1">Due: {{ loan.due_date|date:"M d" }}</div>
                        </div>
                        <div class="text-right">
                            <div class="font-bold text-blue-600 dark:text-blue-400">KES {{ loan.outstanding_balance|floatformat:0|intcomma }}</div>
                            <button onclick="scheduleFollowUp('{{ loan.id }}')" 
                                class="mt-2 px-3 py-1 bg-blue-500 hover:bg-blue-600 text-white text-xs rounded-lg transition-all">
                                <i class="fas fa-calendar-plus mr-1"></i> Schedule
                            </button>
                        </div>
                    </div>
                </div>
                {% endfor %}
                {% if report_data.categorized.this_week|length > 8 %}
                <div class="text-center py-2">
                    <button onclick="showAllWeek()" class="text-blue-600 hover:text-blue-800 font-medium text-sm">
                        View {{ report_data.categorized.this_week|length|add:"-8" }} more...
                    </button>
                </div>
                {% endif %}
            </div>
        </div>
        {% endif %}
    </div>
    {% endif %}

    <!-- Floating Action Button for Mobile -->
    <div class="fixed bottom-6 right-6 lg:hidden no-print">
        <button onclick="toggleMobileActions()" 
            class="w-16 h-16 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-full shadow-2xl hover:shadow-3xl transition-all transform hover:scale-110">
            <span>⚡</span>
        </button>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// Global variables
let selectedLoans = [];
let filtersVisible = true;

// Chart Data (this should come from Django context)
const chartData = {
    dueDateDistribution: {
        labels: ['Due Today', 'Due Tomorrow', 'Due This Week', 'Due Later'],
        data: [{{ chart_data.today_due|default:0 }}, 
               {{ chart_data.tomorrow_due|default:0 }}, 
               {{ chart_data.week_due|default:0 }}, 
               {{ chart_data.later_due_count|default:0 }}],
        colors: ['#ef4444', '#f97316', '#eab308', '#22c55e']
    },
    amountDistribution: {
        labels: ['Critical', 'High', 'Medium', 'Low'],
        amounts: [{{ chart_data.today_due_amount|default:0 }}, 
                 {{ chart_data.tomorrow_due_amount|default:0 }}, 
                 {{ chart_data.week_due_amount|default:0 }}, 
                 {{ chart_data.later_due_amount|default:0 }}]
    },
    trendData: {{ chart_data.trend_data|safe|default:'[]' }},
    priorityData: {
        labels: {{ chart_data.priority_data.labels|safe|default:'[]' }},
        data: {{ chart_data.priority_data.data|safe|default:'[]' }}
    }
};

// Initialize Charts
function initializeCharts() {
    if (typeof Chart === 'undefined') {
        console.error('Chart.js is not loaded');
        document.querySelectorAll('.chart-container').forEach(container => {
            container.innerHTML = '<div class="bg-yellow-100 border border-yellow-400 text-yellow-700 px-4 py-3 rounded">Charts unavailable. Please refresh the page.</div>';
        });
        return;
    }
    
    try {
        // Due Date Distribution Pie Chart
        const pieCtx = document.getElementById('dueDatePieChart');
        if (pieCtx) {
            new Chart(pieCtx.getContext('2d'), {
                type: 'doughnut',
                data: {
                    labels: chartData.dueDateDistribution.labels,
                    datasets: [{
                        data: chartData.dueDateDistribution.data,
                        backgroundColor: chartData.dueDateDistribution.colors,
                        borderWidth: 2,
                        borderColor: '#ffffff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                usePointStyle: true
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return context.label + ': ' + context.raw + ' loans';
                                }
                            }
                        }
                    }
                }
            });
        }

        // Amount Distribution Bar Chart
        const barCtx = document.getElementById('amountBarChart');
        if (barCtx) {
            new Chart(barCtx.getContext('2d'), {
                type: 'bar',
                data: {
                    labels: chartData.amountDistribution.labels,
                    datasets: [{
                        label: 'Amount Due (KES)',
                        data: chartData.amountDistribution.amounts,
                        backgroundColor: ['#ef4444', '#f97316', '#eab308', '#22c55e'],
                        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.toLocaleString();
                                }
                            }
                        }
                    }
                }
            });
        }

        // Loans Due Trend Line Chart
        const trendCtx = document.getElementById('trendLineChart');
        if (trendCtx && chartData.trendData) {
            new Chart(trendCtx.getContext('2d'), {
                type: 'line',
                data: {
                    labels: chartData.trendData.map(item => {
                        const date = new Date(item.date);
                        return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
                    }),
                    datasets: [{
                        label: 'Loans Due',
                        data: chartData.trendData.map(item => item.count),
                        borderColor: '#8b5cf6',
                        backgroundColor: 'rgba(139, 92, 246, 0.1)',
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4,
                        pointBackgroundColor: '#8b5cf6',
                        pointBorderColor: '#ffffff',
                        pointBorderWidth: 2,
                        pointRadius: 5
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false
                        }
                    },
                    scales: {
                        x: {
                            display: true,
                            title: {
                                display: true,
                                text: 'Date'
                            }
                        },
                        y: {
                            display: true,
                            title: {
                                display: true,
                                text: 'Number of Loans'
                            },
                            beginAtZero: true
                        }
                    },
                    interaction: {
                        mode: 'nearest',
                        axis: 'x',
                        intersect: false
                    }
                }
            });
        }

        // Collection Priority Doughnut Chart
        const priorityCtx = document.getElementById('priorityDoughnutChart');
        if (priorityCtx && chartData.priorityData.labels.length > 0) {
            new Chart(priorityCtx.getContext('2d'), {
                type: 'doughnut',
                data: {
                    labels: chartData.priorityData.labels,
                    datasets: [{
                        data: chartData.priorityData.data,
                        backgroundColor: ['#dc2626', '#ea580c', '#ca8a04', '#16a34a'],
                        borderWidth: 2,
                        borderColor: '#ffffff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                usePointStyle: true
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return context.label + ': ' + context.parsed + ' loans';
                                }
                            }
                        }
                    }
                }
            });
        }

        console.log('Charts initialized successfully');
    } catch (error) {
        console.error('Error initializing charts:', error);
        showNotification('Charts could not be loaded. Please refresh the page.', 'warning');
    }
}

// Initialize page
document.addEventListener('DOMContentLoaded', function() {
    initializeFilters();
    initializeCheckboxes();
    initializeTooltips();
    startAutoRefresh();
    
    // Initialize charts after a short delay
    setTimeout(function() {
        if (typeof Chart !== 'undefined') {
            initializeCharts();
        } else {
            console.error('Chart.js not loaded');
            const chartsSection = document.getElementById('chartsSection');
            if (chartsSection) {
                chartsSection.innerHTML = '<div class="bg-yellow-100 border border-yellow-400 text-yellow-700 px-4 py-3 rounded">Charts unavailable. Please refresh the page.</div>';
            }
        }
    }, 500);
    
    // Add keyboard shortcuts
    document.addEventListener('keydown', handleKeyboardShortcuts);
});

// Filter Management
function initializeFilters() {
    const todayOnlyHidden = document.getElementById('today_only_hidden');
    const startDate = document.getElementById('start_date');
    const endDate = document.getElementById('end_date');
    
    if (todayOnlyHidden.value === 'true') {
        startDate.disabled = true;
        endDate.disabled = true;
    }
}

function toggleFilters() {
    const content = document.getElementById('filter-content');
    const chevron = document.getElementById('filter-chevron');
    
    filtersVisible = !filtersVisible;
    
    if (filtersVisible) {
        content.style.display = 'block';
        chevron.style.transform = 'rotate(0deg)';
    } else {
        content.style.display = 'none';
        chevron.style.transform = 'rotate(-90deg)';
    }
}

function applyQuickFilter(value) {
    const startDate = document.getElementById('start_date');
    const endDate = document.getElementById('end_date');
    const todayOnlyHidden = document.getElementById('today_only_hidden');
    const form = startDate.closest('form');
    
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    const weekEnd = new Date(today);
    weekEnd.setDate(weekEnd.getDate() + 7);
    
    const monthEnd = new Date(today);
    monthEnd.setDate(monthEnd.getDate() + 30);
    
    switch(value) {
        case 'today':
            todayOnlyHidden.value = 'true';
            startDate.value = today.toISOString().split('T')[0];
            endDate.value = today.toISOString().split('T')[0];
            break;
        case 'tomorrow':
            todayOnlyHidden.value = '';
            startDate.value = tomorrow.toISOString().split('T')[0];
            endDate.value = tomorrow.toISOString().split('T')[0];
            break;
        case 'week':
            todayOnlyHidden.value = '';
            startDate.value = today.toISOString().split('T')[0];
            endDate.value = weekEnd.toISOString().split('T')[0];
            break;
        case 'month':
            todayOnlyHidden.value = '';
            startDate.value = today.toISOString().split('T')[0];
            endDate.value = monthEnd.toISOString().split('T')[0];
            break;
        default:
            todayOnlyHidden.value = '';
    }
    
    // Auto-submit form when quick filter is applied
    if (value) {
        form.submit();
    }
}

// Checkbox Management
function initializeCheckboxes() {
    const selectAllCheckbox = document.getElementById('select-all');
    const loanCheckboxes = document.querySelectorAll('.loan-checkbox');
    
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            loanCheckboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
                updateSelectedLoans();
            });
        });
    }
    
    loanCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateSelectedLoans);
    });
}

function selectAllLoans() {
    const selectAllCheckbox = document.getElementById('select-all');
    const loanCheckboxes = document.querySelectorAll('.loan-checkbox');
    
    const allSelected = Array.from(loanCheckboxes).every(cb => cb.checked);
    
    loanCheckboxes.forEach(checkbox => {
        checkbox.checked = !allSelected;
    });
    
    if (selectAllCheckbox) {
        selectAllCheckbox.checked = !allSelected;
    }
    
    updateSelectedLoans();
}

function updateSelectedLoans() {
    const checkedBoxes = document.querySelectorAll('.loan-checkbox:checked');
    selectedLoans = Array.from(checkedBoxes).map(cb => cb.value);
    
    // Update UI to show selection count
    const bulkButton = document.querySelector('[onclick="bulkActions()"]');
    if (bulkButton) {
        if (selectedLoans.length > 0) {
            bulkButton.innerHTML = `<span>⚡</span> Bulk Actions (${selectedLoans.length})`;
            bulkButton.classList.add('bg-green-200', 'text-green-800');
            bulkButton.classList.remove('bg-green-100', 'text-green-700');
        } else {
            bulkButton.innerHTML = '<span>⚡</span> Bulk Actions';
            bulkButton.classList.remove('bg-green-200', 'text-green-800');
            bulkButton.classList.add('bg-green-100', 'text-green-700');
        }
    }
}

// Communication Functions
function callBorrower(phoneNumber, borrowerName) {
    if (!phoneNumber || phoneNumber === 'N/A' || phoneNumber === 'No phone') {
        showNotification('No phone number available for this borrower', 'error');
        return;
    }
    
    // Show confirmation dialog
    if (confirm(`Call ${borrowerName} at ${phoneNumber}?`)) {
        // Log the call attempt
        logActivity('call_attempted', { phone: phoneNumber, borrower: borrowerName });
        
        // Open phone dialer
        window.open(`tel:${phoneNumber}`);
        
        // Show success notification
        showNotification(`Calling ${borrowerName}...`, 'success');
        
        // Optionally, mark as contacted in the system
        setTimeout(() => {
            if (confirm('Did you successfully contact the borrower?')) {
                markAsContacted(phoneNumber);
            }
        }, 30000); // Ask after 30 seconds
    }
}

function sendSMS(phoneNumber, loanNumber) {
    if (!phoneNumber || phoneNumber === 'N/A' || phoneNumber === 'No phone') {
        showNotification('No phone number available for this borrower', 'error');
        return;
    }
    
    const message = `Dear customer, your loan ${loanNumber} payment is due. Please make your payment to avoid late fees. Thank you.`;
    
    if (confirm(`Send SMS reminder to ${phoneNumber}?`)) {
        // Log the SMS attempt
        logActivity('sms_sent', { phone: phoneNumber, loan: loanNumber });
        
        // Open SMS app (mobile) or show message for desktop
        if (/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
            window.open(`sms:${phoneNumber}?body=${encodeURIComponent(message)}`);
        } else {
            // For desktop, copy message to clipboard
            navigator.clipboard.writeText(message).then(() => {
                showNotification('SMS message copied to clipboard', 'success');
            });
        }
        
        showNotification('SMS reminder sent successfully', 'success');
    }
}

function recordPayment(loanId) {
    // This would typically open a payment recording modal or redirect to payment page
    showNotification('Opening payment recording form...', 'info');
    
    // For now, just show a placeholder
    const amount = prompt('Enter payment amount (KES):');
    if (amount && !isNaN(amount) && parseFloat(amount) > 0) {
        logActivity('payment_recorded', { loan: loanId, amount: amount });
        showNotification(`Payment of KES ${parseFloat(amount).toLocaleString()} recorded`, 'success');
        
        // Refresh the page after a short delay
        setTimeout(() => {
            location.reload();
        }, 2000);
    }
}

// Bulk Actions
function bulkActions() {
    if (selectedLoans.length === 0) {
        showNotification('Please select loans first', 'warning');
        return;
    }
    
    const actions = [
        { id: 'bulk_call', label: 'Call All Selected Borrowers', icon: 'fas fa-phone' },
        { id: 'bulk_sms', label: 'Send SMS to All Selected', icon: 'fas fa-sms' },
        { id: 'bulk_email', label: 'Send Email Reminders', icon: 'fas fa-envelope' },
        { id: 'bulk_export', label: 'Export Selected to CSV', icon: 'fas fa-download' },
        { id: 'bulk_mark_contacted', label: 'Mark as Contacted', icon: 'fas fa-check' }
    ];
    
    let actionHtml = '<div class="space-y-2">';
    actions.forEach(action => {
        actionHtml += `
            <button onclick="executeBulkAction('${action.id}')" 
                class="w-full flex items-center px-4 py-3 text-left hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors">
                <i class="${action.icon} mr-3 text-blue-600"></i>
                ${action.label}
            </button>
        `;
    });
    actionHtml += '</div>';
    
    showModal('Bulk Actions', actionHtml);
}

function executeBulkAction(actionId) {
    closeModal();
    
    switch(actionId) {
        case 'bulk_call':
            bulkCall();
            break;
        case 'bulk_sms':
            bulkSMS();
            break;
        case 'bulk_email':
            bulkEmail();
            break;
        case 'bulk_export':
            bulkExport();
            break;
        case 'bulk_mark_contacted':
            bulkMarkContacted();
            break;
    }
}

function bulkCall() {
    const phones = getSelectedPhones();
    if (phones.length === 0) {
        showNotification('No phone numbers available for selected loans', 'error');
        return;
    }
    
    if (confirm(`Call ${phones.length} borrowers? This will open multiple phone dialers.`)) {
        phones.forEach((phone, index) => {
            setTimeout(() => {
                window.open(`tel:${phone}`);
            }, index * 1000); // Stagger calls by 1 second
        });
        
        logActivity('bulk_call', { count: phones.length });
        showNotification(`Initiated calls to ${phones.length} borrowers`, 'success');
    }
}

function bulkSMS() {
    const phones = getSelectedPhones();
    if (phones.length === 0) {
        showNotification('No phone numbers available for selected loans', 'error');
        return;
    }
    
    const message = 'Dear customer, your loan payment is due. Please make your payment to avoid late fees. Thank you.';
    
    if (confirm(`Send SMS to ${phones.length} borrowers?`)) {
        // In a real implementation, this would call an API to send bulk SMS
        logActivity('bulk_sms', { count: phones.length });
        showNotification(`SMS reminders sent to ${phones.length} borrowers`, 'success');
    }
}

function bulkExport() {
    const selectedRows = getSelectedLoanData();
    if (selectedRows.length === 0) {
        showNotification('No loans selected for export', 'error');
        return;
    }
    
    // Create CSV content
    const headers = ['Loan Number', 'Borrower Name', 'Phone', 'Outstanding Amount', 'Due Date'];
    const csvContent = [
        headers.join(','),
        ...selectedRows.map(row => [
            row.loanNumber,
            `"${row.borrowerName}"`,
            row.phone,
            row.outstandingAmount,
            row.dueDate
        ].join(','))
    ].join('\n');
    
    // Download CSV
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `loans_due_${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    window.URL.revokeObjectURL(url);
    
    logActivity('bulk_export', { count: selectedRows.length });
    showNotification(`Exported ${selectedRows.length} loans to CSV`, 'success');
}

// Utility Functions
function getSelectedPhones() {
    return selectedLoans.map(loanId => {
        const row = document.querySelector(`tr[data-loan-id="${loanId}"]`);
        return row ? row.dataset.phone : null;
    }).filter(phone => phone && phone !== 'N/A' && phone !== 'No phone');
}

function getSelectedLoanData() {
    return selectedLoans.map(loanId => {
        const row = document.querySelector(`tr[data-loan-id="${loanId}"]`);
        if (!row) return null;
        
        const cells = row.querySelectorAll('td');
        return {
            loanNumber: cells[1]?.querySelector('.text-lg')?.textContent?.trim(),
            borrowerName: cells[2]?.querySelector('.text-lg')?.textContent?.trim(),
            phone: row.dataset.phone,
            outstandingAmount: cells[3]?.querySelector('.text-red-600')?.textContent?.replace('KES ', '').trim(),
            dueDate: cells[4]?.querySelector('.text-lg')?.textContent?.trim()
        };
    }).filter(data => data !== null);
}

function refreshData() {
    showNotification('Refreshing data...', 'info');
    location.reload();
}

function markAsContacted(phone) {
    // Mark loan as contacted in the system
    logActivity('marked_contacted', { phone: phone });
    showNotification('Borrower marked as contacted', 'success');
}

function scheduleFollowUp(loanId) {
    const date = prompt('Schedule follow-up date (YYYY-MM-DD):');
    if (date && /^\d{4}-\d{2}-\d{2}$/.test(date)) {
        logActivity('follow_up_scheduled', { loan: loanId, date: date });
        showNotification(`Follow-up scheduled for ${date}`, 'success');
    }
}

// Notification System
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 z-50 px-6 py-4 rounded-lg shadow-lg text-white font-semibold transform transition-all duration-300 translate-x-full`;
    
    switch(type) {
        case 'success':
            notification.classList.add('bg-green-500');
            break;
        case 'error':
            notification.classList.add('bg-red-500');
            break;
        case 'warning':
            notification.classList.add('bg-yellow-500');
            break;
        default:
            notification.classList.add('bg-blue-500');
    }
    
    notification.innerHTML = `
        <div class="flex items-center gap-2">
            <i class="fas fa-${type === 'success' ? 'check' : type === 'error' ? 'times' : type === 'warning' ? 'exclamation' : 'info'}-circle"></i>
            ${message}
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // Animate in
    setTimeout(() => {
        notification.classList.remove('translate-x-full');
    }, 100);
    
    // Auto remove
    setTimeout(() => {
        notification.classList.add('translate-x-full');
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 4000);
}

// Modal System
function showModal(title, content) {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50';
    modal.innerHTML = `
        <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl max-w-md w-full mx-4 transform transition-all">
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white">${title}</h3>
            </div>
            <div class="p-6">
                ${content}
            </div>
            <div class="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-end">
                <button onclick="closeModal()" class="px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-lg transition-colors">
                    Close
                </button>
            </div>
        </div>
    `;
    
    modal.id = 'current-modal';
    document.body.appendChild(modal);
    
    // Close on backdrop click
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            closeModal();
        }
    });
}

function closeModal() {
    const modal = document.getElementById('current-modal');
    if (modal) {
        document.body.removeChild(modal);
    }
}

// Activity Logging
function logActivity(action, data = {}) {
    const activity = {
        timestamp: new Date().toISOString(),
        action: action,
        data: data,
        user: 'current_user' // This would come from the backend
    };
    
    // Store in localStorage for now (in production, send to backend)
    const activities = JSON.parse(localStorage.getItem('loan_activities') || '[]');
    activities.push(activity);
    localStorage.setItem('loan_activities', JSON.stringify(activities.slice(-100))); // Keep last 100
    
    console.log('Activity logged:', activity);
}

// Keyboard Shortcuts
function handleKeyboardShortcuts(e) {
    if (e.ctrlKey || e.metaKey) {
        switch(e.key) {
            case 'a':
                e.preventDefault();
                selectAllLoans();
                break;
            case 'r':
                e.preventDefault();
                refreshData();
                break;
            case 'f':
                e.preventDefault();
                document.getElementById('start_date')?.focus();
                break;
        }
    }
}

// Auto-refresh
function startAutoRefresh() {
    // Auto-refresh every 5 minutes
    setInterval(() => {
        if (document.visibilityState === 'visible') {
            refreshData();
        }
    }, 300000);
}

// Initialize tooltips
function initializeTooltips() {
    // Add tooltips to action buttons
    const buttons = document.querySelectorAll('[onclick*="call"], [onclick*="SMS"], [onclick*="Payment"]');
    buttons.forEach(button => {
        button.title = button.textContent.trim();
    });
}

// Mobile-specific functions
function toggleMobileActions() {
    // Show mobile action sheet
    const actions = `
        <button onclick="selectAllLoans(); closeModal();" class="w-full flex items-center px-4 py-3 text-left hover:bg-gray-100 rounded-lg">
            <i class="fas fa-check-square mr-3"></i> Select All Loans
        </button>
        <button onclick="bulkActions();" class="w-full flex items-center px-4 py-3 text-left hover:bg-gray-100 rounded-lg">
            <span>⚡</span> Bulk Actions
        </button>
        <button onclick="refreshData(); closeModal();" class="w-full flex items-center px-4 py-3 text-left hover:bg-gray-100 rounded-lg">
            <span>🔄</span> Refresh Data
        </button>
    `;
    
    showModal('Quick Actions', actions);
}

// Print functionality
window.addEventListener('beforeprint', function() {
    document.title = `Loans Due Report - ${new Date().toLocaleDateString()}`;
});
</script>
{% endblock %}