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

{% block title %}Loans Due Dashboard - Repayment Tracking{% endblock %}

{% block extra_css %}
<style>
    :root {
        --primary: #6366f1;
        --primary-dark: #4f46e5;
        --danger: #ef4444;
        --warning: #f59e0b;
        --info: #3b82f6;
        --success: #10b981;
        --dark: #0f172a;
        --gray-50: #f9fafb;
        --gray-100: #f3f4f6;
        --gray-200: #e5e7eb;
        --gray-700: #374151;
        --gray-900: #111827;
    }

    body {
        background: linear-gradient(135deg, var(--dark) 0%, #1e293b 50%, #334155 100%);
        min-height: 100vh;
        font-family: 'Inter', system-ui, -apple-system, sans-serif;
    }

    .dashboard-container {
        background: rgba(255, 255, 255, 0.98);
        backdrop-filter: blur(20px);
        border-radius: 24px;
        margin: 2rem;
        padding: 2rem;
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.4);
    }

    .page-header {
        text-align: center;
        margin-bottom: 3rem;
        padding: 2.5rem;
        background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
        color: white;
        border-radius: 20px;
        position: relative;
        overflow: hidden;
    }

    .page-header::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: repeating-linear-gradient(
            45deg,
            transparent,
            transparent 10px,
            rgba(255, 255, 255, 0.03) 10px,
            rgba(255, 255, 255, 0.03) 20px
        );
        animation: slide 20s linear infinite;
    }

    @keyframes slide {
        0% { transform: translate(0, 0); }
        100% { transform: translate(50%, 50%); }
    }

    .page-title {
        font-size: 2.5rem;
        font-weight: 900;
        margin-bottom: 0.5rem;
        position: relative;
        z-index: 1;
    }

    .page-subtitle {
        font-size: 1.1rem;
        opacity: 0.95;
        position: relative;
        z-index: 1;
    }

    /* Summary Cards */
    .summary-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .summary-card {
        background: white;
        border-radius: 16px;
        padding: 1.5rem;
        text-align: center;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        border: 2px solid var(--gray-200);
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }

    .summary-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, var(--primary), var(--info));
    }

    .summary-card.daily::before {
        background: linear-gradient(90deg, var(--danger), #dc2626);
    }

    .summary-card.weekly::before {
        background: linear-gradient(90deg, var(--warning), #d97706);
    }

    .summary-card.monthly::before {
        background: linear-gradient(90deg, var(--info), #1e40af);
    }

    .summary-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.15);
    }

    .summary-value {
        font-size: 2.5rem;
        font-weight: 800;
        margin: 0.5rem 0;
        color: var(--gray-900);
    }

    .summary-label {
        font-size: 0.875rem;
        font-weight: 600;
        color: var(--gray-700);
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin-bottom: 0.25rem;
    }

    .summary-amount {
        font-size: 1.25rem;
        font-weight: 700;
        color: var(--primary);
        margin-top: 0.5rem;
    }

    /* Filters */
    .filters-section {
        background: white;
        border-radius: 16px;
        padding: 1.5rem;
        margin-bottom: 2rem;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }

    .filters-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
        align-items: end;
    }

    .filter-group label {
        display: block;
        font-size: 0.875rem;
        font-weight: 600;
        color: var(--gray-700);
        margin-bottom: 0.5rem;
    }

    .filter-group select,
    .filter-group input {
        width: 100%;
        padding: 0.75rem;
        border: 2px solid var(--gray-200);
        border-radius: 10px;
        font-size: 0.875rem;
        transition: all 0.2s;
    }

    .filter-group select:focus,
    .filter-group input:focus {
        outline: none;
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
    }

    .btn-apply-filters {
        padding: 0.875rem 1.5rem;
        background: linear-gradient(135deg, var(--primary), var(--primary-dark));
        color: white;
        border: none;
        border-radius: 10px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 0.5rem;
    }

    .btn-apply-filters:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(99, 102, 241, 0.3);
    }

    /* Repayment Sections */
    .repayment-section {
        margin-bottom: 2rem;
        background: white;
        border-radius: 20px;
        overflow: hidden;
        box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
    }

    .section-header {
        padding: 1.5rem 2rem;
        background: linear-gradient(135deg, var(--gray-50), var(--gray-100));
        border-bottom: 2px solid var(--gray-200);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .section-title {
        display: flex;
        align-items: center;
        gap: 1rem;
    }

    .section-icon {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        color: white;
    }

    .section-icon.daily {
        background: linear-gradient(135deg, var(--danger), #dc2626);
    }

    .section-icon.weekly {
        background: linear-gradient(135deg, var(--warning), #d97706);
    }

    .section-icon.monthly {
        background: linear-gradient(135deg, var(--info), #1e40af);
    }

    .section-count {
        padding: 0.5rem 1rem;
        border-radius: 9999px;
        font-weight: 700;
        font-size: 0.875rem;
    }

    .section-count.daily {
        background: rgba(239, 68, 68, 0.1);
        color: var(--danger);
    }

    .section-count.weekly {
        background: rgba(245, 158, 11, 0.1);
        color: var(--warning);
    }

    .section-count.monthly {
        background: rgba(59, 130, 246, 0.1);
        color: var(--info);
    }
    
    .section-count {
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    
    .show-all-btn {
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        color: inherit;
        padding: 0.25rem 0.5rem;
        border-radius: 4px;
        cursor: pointer;
        font-size: 0.75rem;
        transition: all 0.2s ease;
    }
    
    .show-all-btn:hover {
        background: rgba(255, 255, 255, 0.3);
        transform: scale(1.05);
    }

    /* Loans Grid */
    .loans-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
        gap: 1.5rem;
        padding: 2rem;
    }

    .loan-card {
        background: white;
        border-radius: 16px;
        padding: 1.5rem;
        border: 2px solid var(--gray-200);
        transition: all 0.3s ease;
        position: relative;
    }

    .loan-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.15);
    }

    .loan-card.critical {
        border-color: var(--danger);
        background: linear-gradient(135deg, #fef2f2 0%, white 100%);
        animation: pulse-border 2s infinite;
    }

    .loan-card.high {
        border-color: var(--warning);
        background: linear-gradient(135deg, #fffbeb 0%, white 100%);
    }

    .loan-card.medium {
        border-color: var(--info);
        background: linear-gradient(135deg, #eff6ff 0%, white 100%);
    }

    @keyframes pulse-border {
        0%, 100% { border-color: var(--danger); }
        50% { border-color: #dc2626; }
    }

    .loan-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 1rem;
    }

    .loan-number {
        font-size: 1.125rem;
        font-weight: 700;
        color: var(--gray-900);
    }

    .urgency-badge {
        padding: 0.5rem 1rem;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    .urgency-badge.critical {
        background: var(--danger);
        color: white;
        animation: pulse 2s infinite;
    }

    .urgency-badge.high {
        background: var(--warning);
        color: white;
    }

    .urgency-badge.medium {
        background: var(--info);
        color: white;
    }

    @keyframes pulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.8; }
    }

    .borrower-info {
        display: flex;
        align-items: center;
        gap: 1rem;
        margin-bottom: 1rem;
        padding: 0.75rem;
        background: var(--gray-50);
        border-radius: 8px;
    }

    .borrower-avatar {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        background: linear-gradient(135deg, var(--primary), var(--info));
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: 700;
        font-size: 1.125rem;
    }

    .borrower-details h4 {
        font-size: 1rem;
        font-weight: 600;
        color: var(--gray-900);
        margin-bottom: 0.25rem;
    }

    .borrower-details p {
        font-size: 0.875rem;
        color: var(--gray-700);
    }

    .loan-details {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 0.75rem;
        margin-bottom: 1rem;
    }

    .detail-item {
        text-align: center;
        padding: 0.75rem;
        background: var(--gray-50);
        border-radius: 8px;
    }

    .detail-label {
        font-size: 0.75rem;
        font-weight: 600;
        color: var(--gray-700);
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin-bottom: 0.25rem;
    }

    .detail-value {
        font-size: 1rem;
        font-weight: 700;
        color: var(--gray-900);
    }

    .payment-info {
        padding: 1rem;
        border-radius: 8px;
        margin-bottom: 1rem;
        border: 1px solid var(--gray-200);
    }

    .payment-info.daily {
        background: #fef2f2;
        border-color: #fecaca;
    }

    .payment-info.weekly {
        background: #fffbeb;
        border-color: #fed7aa;
    }

    .payment-info.monthly {
        background: #eff6ff;
        border-color: #bfdbfe;
    }

    .payment-amount {
        font-size: 1.5rem;
        font-weight: 800;
        color: var(--gray-900);
        margin-bottom: 0.5rem;
    }

    .payment-schedule {
        font-size: 0.875rem;
        color: var(--gray-700);
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .due-date-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
        padding: 0.75rem;
        background: var(--gray-50);
        border-radius: 8px;
    }

    .due-date {
        font-size: 0.875rem;
        font-weight: 600;
        color: var(--gray-900);
    }

    .days-until {
        font-size: 0.875rem;
        font-weight: 600;
        padding: 0.25rem 0.75rem;
        border-radius: 9999px;
    }

    .days-until.overdue {
        background: var(--danger);
        color: white;
    }

    .days-until.today {
        background: var(--warning);
        color: white;
    }

    .days-until.soon {
        background: var(--info);
        color: white;
    }

    .days-until.later {
        background: var(--success);
        color: white;
    }

    .action-buttons {
        display: flex;
        gap: 0.5rem;
    }

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

    .action-btn.primary {
        background: var(--primary);
        color: white;
    }

    .action-btn.primary:hover {
        background: var(--primary-dark);
        transform: translateY(-2px);
    }

    .action-btn.danger {
        background: var(--danger);
        color: white;
    }

    .action-btn.danger:hover {
        background: #dc2626;
        transform: translateY(-2px);
    }

    .no-loans {
        text-align: center;
        padding: 3rem;
        color: var(--gray-700);
    }

    .no-loans-icon {
        font-size: 3rem;
        margin-bottom: 1rem;
        opacity: 0.5;
    }

    @media (max-width: 768px) {
        .dashboard-container {
            margin: 1rem;
            padding: 1rem;
        }

        .page-title {
            font-size: 2rem;
        }

        .loans-grid {
            grid-template-columns: 1fr;
            padding: 1rem;
        }

        .loan-details {
            grid-template-columns: 1fr;
        }

        .filters-grid {
            grid-template-columns: 1fr;
        }
    }
    
    /* Pagination Controls */
    .pagination-controls {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 2rem;
        padding: 1.5rem;
        background: rgba(255, 255, 255, 0.8);
        border-radius: 12px;
        border: 1px solid var(--gray-200);
    }
    
    .pagination-info {
        font-size: 0.875rem;
        color: var(--gray-600);
        font-weight: 500;
    }
    
    .pagination-buttons {
        display: flex;
        align-items: center;
        gap: 1rem;
    }
    
    .pagination-btn {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.75rem 1.5rem;
        background: var(--primary);
        color: white;
        border: none;
        border-radius: 8px;
        font-size: 0.875rem;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    
    .pagination-btn:hover {
        background: var(--primary-dark);
        transform: translateY(-1px);
    }
    
    .pagination-btn:disabled {
        background: var(--gray-300);
        color: var(--gray-500);
        cursor: not-allowed;
        transform: none;
    }
    
    .page-info {
        font-size: 0.875rem;
        color: var(--gray-600);
        font-weight: 500;
        padding: 0.5rem 1rem;
        background: var(--gray-100);
        border-radius: 6px;
    }
    
    @media (max-width: 768px) {
        .pagination-controls {
            flex-direction: column;
            gap: 1rem;
            text-align: center;
        }
        
        .pagination-buttons {
            flex-wrap: wrap;
            justify-content: center;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="dashboard-container">
    <!-- Page Header -->
    <div class="page-header">
        <div style="display: flex; justify-content: space-between; align-items: center; position: relative; z-index: 1;">
            <div>
                <h1 class="page-title">
                    <i class="fas fa-calendar-check"></i>
                    Loans Due Dashboard
                </h1>
                <p class="page-subtitle">Real-time repayment tracking with urgency-based prioritization</p>
            </div>
            <div style="display: flex; gap: 10px;">
                <a href="?export=excel{% if filters.period_filter %}&period={{ filters.period_filter }}{% endif %}{% if filters.start_date %}&start_date={{ filters.start_date }}{% endif %}{% if filters.end_date %}&end_date={{ filters.end_date }}{% endif %}{% if filters.product_id %}&product={{ filters.product_id }}{% endif %}{% if filters.delinquency_status %}&delinquency_status={{ filters.delinquency_status }}{% endif %}" class="btn-apply-filters" style="background: linear-gradient(135deg, #10b981, #059669);">
                    <span>📊</span> Export Excel
                </a>
                <a href="?export=pdf{% if filters.period_filter %}&period={{ filters.period_filter }}{% endif %}{% if filters.start_date %}&start_date={{ filters.start_date }}{% endif %}{% if filters.end_date %}&end_date={{ filters.end_date }}{% endif %}{% if filters.product_id %}&product={{ filters.product_id }}{% endif %}{% if filters.delinquency_status %}&delinquency_status={{ filters.delinquency_status }}{% endif %}" class="btn-apply-filters" style="background: linear-gradient(135deg, #ef4444, #dc2626);">
                    <span>📄</span> Export PDF
                </a>
            </div>
        </div>
    </div>

    <!-- Summary Metrics -->
    <div class="summary-grid">
        <div class="summary-card daily">
            <div class="summary-label">Daily Payments</div>
            <div class="summary-value">{{ daily_loans_count|default:0 }}</div>
            <div class="summary-amount">KSh {{ daily_amount_due|default:0|floatformat:0|intcomma }}</div>
        </div>
        <div class="summary-card weekly">
            <div class="summary-label">Weekly Payments</div>
            <div class="summary-value">{{ weekly_loans_count|default:0 }}</div>
            <div class="summary-amount">KSh {{ weekly_amount_due|default:0|floatformat:0|intcomma }}</div>
        </div>
        <div class="summary-card monthly">
            <div class="summary-label">Monthly Payments</div>
            <div class="summary-value">{{ monthly_loans_count|default:0 }}</div>
            <div class="summary-amount">KSh {{ monthly_amount_due|default:0|floatformat:0|intcomma }}</div>
        </div>
        <div class="summary-card">
            <div class="summary-label">Total Due</div>
            <div class="summary-value">{{ total_loans_count|default:0 }}</div>
            <div class="summary-amount">KSh {{ total_amount_due|default:0|floatformat:0|intcomma }}</div>
        </div>
    </div>

    <!-- Comprehensive Filters (Requirements 9.1, 9.2, 9.3, 9.4, 9.5) -->
    <div class="filters-section">
        <form method="get" id="filtersForm">
            <div class="filters-grid">
                <!-- Period Quick Filters (Requirements 9.2, 9.3) -->
                <div class="filter-group">
                    <label>Period Filter</label>
                    <select name="period">
                        <option value="all_time" {% if filters.period_filter == 'all_time' %}selected{% endif %}>All Time</option>
                        <option value="daily" {% if filters.period_filter == 'daily' %}selected{% endif %}>📅 Due Today</option>
                        <option value="weekly" {% if filters.period_filter == 'weekly' %}selected{% endif %}>📆 Due This Week (7 days)</option>
                        <option value="monthly" {% if filters.period_filter == 'monthly' %}selected{% endif %}>📊 Due This Month (30 days)</option>
                        <option value="custom" {% if filters.period_filter == 'custom' %}selected{% endif %}>🔧 Custom Date Range</option>
                    </select>
                </div>
                
                <!-- Date Range Filters (Requirement 9.4) -->
                <div class="filter-group">
                    <label>From Date</label>
                    <input type="date" name="start_date" value="{{ filters.start_date }}" placeholder="Start Date">
                </div>
                <div class="filter-group">
                    <label>To Date</label>
                    <input type="date" name="end_date" value="{{ filters.end_date }}" placeholder="End Date">
                </div>
                
                <!-- Loan Product Filter (Requirement 9.1) -->
                <div class="filter-group">
                    <label>Loan Product</label>
                    <select name="product">
                        <option value="">All Products</option>
                        {% for product in loan_products %}
                            <option value="{{ product.id }}" {% if filters.product_id == product.id|stringformat:"s" %}selected{% endif %}>
                                {{ product.name }}
                            </option>
                        {% endfor %}
                    </select>
                </div>
                
                <!-- Delinquency Status Filter (Requirement 9.1) -->
                <div class="filter-group">
                    <label>Delinquency Status</label>
                    <select name="delinquency_status">
                        <option value="">All Status</option>
                        <option value="current" {% if filters.delinquency_status == 'current' %}selected{% endif %}>✅ Current</option>
                        <option value="overdue" {% if filters.delinquency_status == 'overdue' %}selected{% endif %}>⚠️ Overdue</option>
                        <option value="critical" {% if filters.delinquency_status == 'critical' %}selected{% endif %}>🚨 Critical</option>
                    </select>
                </div>
                
                <!-- Existing Filters -->
                <div class="filter-group">
                    <label>Repayment Method</label>
                    <select name="repayment_method">
                        <option value="">All Methods</option>
                        <option value="daily" {% if request.GET.repayment_method == 'daily' %}selected{% endif %}>Daily</option>
                        <option value="weekly" {% if request.GET.repayment_method == 'weekly' %}selected{% endif %}>Weekly</option>
                        <option value="monthly" {% if request.GET.repayment_method == 'monthly' %}selected{% endif %}>Monthly</option>
                    </select>
                </div>
                
                <div class="filter-group">
                    <label>Urgency Level</label>
                    <select name="urgency">
                        <option value="">All Levels</option>
                        <option value="critical" {% if request.GET.urgency == 'critical' %}selected{% endif %}>Critical</option>
                        <option value="high" {% if request.GET.urgency == 'high' %}selected{% endif %}>High</option>
                        <option value="medium" {% if request.GET.urgency == 'medium' %}selected{% endif %}>Medium</option>
                    </select>
                </div>
                
                <div class="filter-group">
                    <label>Days Until Due</label>
                    <select name="days_until">
                        <option value="">All</option>
                        <option value="overdue" {% if request.GET.days_until == 'overdue' %}selected{% endif %}>Overdue</option>
                        <option value="today" {% if request.GET.days_until == 'today' %}selected{% endif %}>Due Today</option>
                        <option value="week" {% if request.GET.days_until == 'week' %}selected{% endif %}>Due This Week</option>
                        <option value="month" {% if request.GET.days_until == 'month' %}selected{% endif %}>Due This Month</option>
                    </select>
                </div>
                
                <!-- Action Buttons -->
                <div class="filter-group">
                    <button type="submit" class="btn-apply-filters">
                        <span>🔍</span>
                        Apply Filters
                    </button>
                </div>
                <div class="filter-group">
                    <a href="?" class="btn-apply-filters" style="background: linear-gradient(135deg, #6b7280, #4b5563); text-decoration: none; text-align: center;">
                        <span>🔄</span>
                        Clear Filters
                    </a>
                </div>
            </div>
        </form>
    </div>

    <!-- Daily Payments Section -->
    {% if daily_loans %}
    <div class="repayment-section">
        <div class="section-header">
            <div class="section-title">
                <div class="section-icon daily">
                    <i class="fas fa-calendar-day"></i>
                </div>
                <div>
                    <h3>Daily Payments</h3>
                    <p style="font-size: 0.875rem; color: #6b7280; margin: 0;">Critical attention required - payments due every day</p>
                </div>
            </div>
            <div class="section-count daily">
                {{ daily_loans|length }} of {{ daily_loans_count }} loans
                {% if daily_loans_count > 6 %}
                    <button class="show-all-btn" onclick="toggleShowAll('daily')" title="Show all loans">
                        <i class="fas fa-expand-arrows-alt"></i>
                    </button>
                {% endif %}
            </div>
        </div>
        <div class="loans-grid">
            {% for loan in daily_loans %}
            <div class="loan-card {{ loan.urgency }}">
                <div class="loan-header">
                    <div class="loan-number">{{ loan.loan_number }}</div>
                    <div class="urgency-badge {{ loan.urgency }}">{{ loan.urgency|title }}</div>
                </div>
                
                <div class="borrower-info">
                    <div class="borrower-avatar">{{ loan.borrower_name|slice:":2"|upper }}</div>
                    <div class="borrower-details">
                        <h4>{{ loan.borrower_name }}</h4>
                        <p>{{ loan.borrower_phone }}</p>
                    </div>
                </div>

                <div class="loan-details">
                    <div class="detail-item">
                        <div class="detail-label">Outstanding</div>
                        <div class="detail-value">KSh {{ loan.outstanding_balance|floatformat:0|intcomma }}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">Amount Paid</div>
                        <div class="detail-value">KSh {{ loan.amount_paid|default:0|floatformat:0|intcomma }}</div>
                    </div>
                </div>

                <div class="payment-info daily">
                    <div class="payment-amount">KSh {{ loan.expected_payment_amount|floatformat:0|intcomma }}</div>
                    <div class="payment-schedule">
                        <i class="fas fa-calendar-day"></i>
                        Daily Payment Required
                    </div>
                </div>

                <div class="due-date-info">
                    <div class="due-date">Due: {{ loan.due_date|date:"M d, Y" }}</div>
                    <div class="days-until {% if loan.days_until_due < 0 %}overdue{% elif loan.days_until_due == 0 %}today{% elif loan.days_until_due <= 1 %}soon{% else %}later{% endif %}">
                        {% if loan.days_until_due < 0 %}
                            {% widthratio loan.days_until_due 1 -1 %} days overdue
                        {% elif loan.days_until_due == 0 %}
                            Due today!
                        {% elif loan.days_until_due == 1 %}
                            Due tomorrow
                        {% else %}
                            {{ loan.days_until_due }} days
                        {% endif %}
                    </div>
                </div>

                <div class="action-buttons">
                    <button class="action-btn danger" onclick="contactBorrower('{{ loan.id }}', 'urgent')">
                        <span>📞</span>
                        Call Now
                    </button>
                    <button class="action-btn primary" onclick="viewLoanDetails('{{ loan.id }}')">
                        <i class="fas fa-eye"></i>
                        View Details
                    </button>
                </div>
            </div>
            {% endfor %}
        </div>
        
        <!-- Pagination Controls for Daily Loans -->
        {% if pagination.daily_total_pages > 1 and not pagination.daily_show_all %}
        <div class="pagination-controls">
            <div class="pagination-info">
                Showing {{ daily_loans|length }} of {{ daily_loans_count }} loans
            </div>
            <div class="pagination-buttons">
                {% if pagination.daily_has_prev %}
                    <button class="pagination-btn" onclick="changePage('daily', {{ pagination.daily_page|add:"-1" }})">
                        <span>‹</span> Previous
                    </button>
                {% endif %}
                
                <span class="page-info">
                    Page {{ pagination.daily_page }} of {{ pagination.daily_total_pages }}
                </span>
                
                {% if pagination.daily_has_next %}
                    <button class="pagination-btn" onclick="changePage('daily', {{ pagination.daily_page|add:"1" }})">
                        Next <span>›</span>
                    </button>
                {% endif %}
            </div>
        </div>
        {% endif %}
    </div>
    {% endif %}

    <!-- Weekly Payments Section -->
    {% if weekly_loans %}
    <div class="repayment-section">
        <div class="section-header">
            <div class="section-title">
                <div class="section-icon weekly">
                    <i class="fas fa-calendar-week"></i>
                </div>
                <div>
                    <h3>Weekly Payments</h3>
                    <p style="font-size: 0.875rem; color: #6b7280; margin: 0;">Weekly payment schedule - monitor closely</p>
                </div>
            </div>
            <div class="section-count weekly">
                {{ weekly_loans|length }} of {{ weekly_loans_count }} loans
                {% if weekly_loans_count > 6 %}
                    <button class="show-all-btn" onclick="toggleShowAll('weekly')" title="Show all loans">
                        <i class="fas fa-expand-arrows-alt"></i>
                    </button>
                {% endif %}
            </div>
        </div>
        <div class="loans-grid">
            {% for loan in weekly_loans %}
            <div class="loan-card {{ loan.urgency }}">
                <div class="loan-header">
                    <div class="loan-number">{{ loan.loan_number }}</div>
                    <div class="urgency-badge {{ loan.urgency }}">{{ loan.urgency|title }}</div>
                </div>
                
                <div class="borrower-info">
                    <div class="borrower-avatar">{{ loan.borrower_name|slice:":2"|upper }}</div>
                    <div class="borrower-details">
                        <h4>{{ loan.borrower_name }}</h4>
                        <p>{{ loan.borrower_phone }}</p>
                    </div>
                </div>

                <div class="loan-details">
                    <div class="detail-item">
                        <div class="detail-label">Outstanding</div>
                        <div class="detail-value">KSh {{ loan.outstanding_balance|floatformat:0|intcomma }}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">Amount Paid</div>
                        <div class="detail-value">KSh {{ loan.amount_paid|default:0|floatformat:0|intcomma }}</div>
                    </div>
                </div>

                <div class="payment-info weekly">
                    <div class="payment-amount">KSh {{ loan.expected_payment_amount|floatformat:0|intcomma }}</div>
                    <div class="payment-schedule">
                        <i class="fas fa-calendar-week"></i>
                        Weekly Payment Required
                    </div>
                </div>

                <div class="due-date-info">
                    <div class="due-date">Due: {{ loan.due_date|date:"M d, Y" }}</div>
                    <div class="days-until {% if loan.days_until_due < 0 %}overdue{% elif loan.days_until_due == 0 %}today{% elif loan.days_until_due <= 3 %}soon{% else %}later{% endif %}">
                        {% if loan.days_until_due < 0 %}
                            {% widthratio loan.days_until_due 1 -1 %} days overdue
                        {% elif loan.days_until_due == 0 %}
                            Due today!
                        {% elif loan.days_until_due <= 3 %}
                            Due in {{ loan.days_until_due }} days
                        {% else %}
                            {{ loan.days_until_due }} days
                        {% endif %}
                    </div>
                </div>

                <div class="action-buttons">
                    <button class="action-btn {% if loan.urgency == 'critical' %}danger{% else %}primary{% endif %}" onclick="contactBorrower('{{ loan.id }}', '{{ loan.urgency }}')">
                        <span>📞</span>
                        {% if loan.urgency == 'critical' %}Call Now{% else %}Contact{% endif %}
                    </button>
                    <button class="action-btn primary" onclick="viewLoanDetails('{{ loan.id }}')">
                        <i class="fas fa-eye"></i>
                        View Details
                    </button>
                </div>
            </div>
            {% endfor %}
        </div>
        
        <!-- Pagination Controls for Weekly Loans -->
        {% if pagination.weekly_total_pages > 1 and not pagination.weekly_show_all %}
        <div class="pagination-controls">
            <div class="pagination-info">
                Showing {{ weekly_loans|length }} of {{ weekly_loans_count }} loans
            </div>
            <div class="pagination-buttons">
                {% if pagination.weekly_has_prev %}
                    <button class="pagination-btn" onclick="changePage('weekly', {{ pagination.weekly_page|add:"-1" }})">
                        <span>‹</span> Previous
                    </button>
                {% endif %}
                
                <span class="page-info">
                    Page {{ pagination.weekly_page }} of {{ pagination.weekly_total_pages }}
                </span>
                
                {% if pagination.weekly_has_next %}
                    <button class="pagination-btn" onclick="changePage('weekly', {{ pagination.weekly_page|add:"1" }})">
                        Next <span>›</span>
                    </button>
                {% endif %}
            </div>
        </div>
        {% endif %}
    </div>
    {% endif %}

    <!-- Monthly Payments Section -->
    {% if monthly_loans %}
    <div class="repayment-section">
        <div class="section-header">
            <div class="section-title">
                <div class="section-icon monthly">
                    <span>📅</span>
                </div>
                <div>
                    <h3>Monthly Payments</h3>
                    <p style="font-size: 0.875rem; color: #6b7280; margin: 0;">Monthly payment schedule - standard monitoring</p>
                </div>
            </div>
            <div class="section-count monthly">
                {{ monthly_loans|length }} of {{ monthly_loans_count }} loans
                {% if monthly_loans_count > 6 %}
                    <button class="show-all-btn" onclick="toggleShowAll('monthly')" title="Show all loans">
                        <i class="fas fa-expand-arrows-alt"></i>
                    </button>
                {% endif %}
            </div>
        </div>
        <div class="loans-grid">
            {% for loan in monthly_loans %}
            <div class="loan-card {{ loan.urgency }}">
                <div class="loan-header">
                    <div class="loan-number">{{ loan.loan_number }}</div>
                    <div class="urgency-badge {{ loan.urgency }}">{{ loan.urgency|title }}</div>
                </div>
                
                <div class="borrower-info">
                    <div class="borrower-avatar">{{ loan.borrower_name|slice:":2"|upper }}</div>
                    <div class="borrower-details">
                        <h4>{{ loan.borrower_name }}</h4>
                        <p>{{ loan.borrower_phone }}</p>
                    </div>
                </div>
                
                <div class="loan-details">
                    <div class="detail-item">
                        <div class="detail-label">Outstanding</div>
                        <div class="detail-value">KSh {{ loan.outstanding_balance|floatformat:0|intcomma }}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">Amount Paid</div>
                        <div class="detail-value">KSh {{ loan.amount_paid|default:0|floatformat:0|intcomma }}</div>
                    </div>
                </div>

                <div class="payment-info monthly">
                    <div class="due-date-info">
                        <div class="due-date">Due: {{ loan.due_date|date:"M d, Y" }}</div>
                        <div class="days-until {% if loan.days_until_due < 0 %}overdue{% elif loan.days_until_due == 0 %}today{% elif loan.days_until_due <= 7 %}soon{% else %}later{% endif %}">
                            {% if loan.days_until_due < 0 %}
                                {% widthratio loan.days_until_due 1 -1 %} days overdue
                            {% elif loan.days_until_due == 0 %}
                                Due today!
                            {% elif loan.days_until_due <= 7 %}
                                Due in {{ loan.days_until_due }} days
                            {% else %}
                                {{ loan.days_until_due }} days
                            {% endif %}
                        </div>
                    </div>
                </div>

                <div class="action-buttons">
                    <button class="action-btn {% if loan.urgency == 'critical' %}danger{% else %}primary{% endif %}" onclick="contactBorrower('{{ loan.id }}', '{{ loan.urgency }}')">
                        <span>📞</span>
                        {% if loan.urgency == 'critical' %}Call Now{% else %}Contact{% endif %}
                    </button>
                    <button class="action-btn primary" onclick="viewLoanDetails('{{ loan.id }}')">
                        <i class="fas fa-eye"></i>
                        View Details
                    </button>
                </div>
            </div>
            {% endfor %}
        </div>
        
        <!-- Pagination Controls for Monthly Loans -->
        {% if pagination.monthly_total_pages > 1 and not pagination.monthly_show_all %}
        <div class="pagination-controls">
            <div class="pagination-info">
                Showing {{ monthly_loans|length }} of {{ monthly_loans_count }} loans
            </div>
            <div class="pagination-buttons">
                {% if pagination.monthly_has_prev %}
                    <button class="pagination-btn" onclick="changePage('monthly', {{ pagination.monthly_page|add:"-1" }})">
                        <span>‹</span> Previous
                    </button>
                {% endif %}
                
                <span class="page-info">
                    Page {{ pagination.monthly_page }} of {{ pagination.monthly_total_pages }}
                </span>
                
                {% if pagination.monthly_has_next %}
                    <button class="pagination-btn" onclick="changePage('monthly', {{ pagination.monthly_page|add:"1" }})">
                        Next <span>›</span>
                    </button>
                {% endif %}
            </div>
        </div>
        {% endif %}
    </div>
    {% endif %}
</div>
{% endblock %}

{% block scripts %}
<script>
    // Contact borrower functionality
    function contactBorrower(loanId, urgency) {
        // Get loan details from the page
        const loanCard = document.querySelector(`[onclick*="'${loanId}'"]`).closest('.loan-card');
        const borrowerName = loanCard.querySelector('.borrower-details h4')?.textContent || 'Borrower';
        const loanNumber = loanCard.querySelector('.loan-number')?.textContent || loanId;
        const outstandingBalance = loanCard.querySelector('.detail-value')?.textContent || 'N/A';
        
        // Create contact message based on urgency
        let message = '';
        if (urgency === 'critical' || urgency === 'urgent') {
            message = `URGENT: ${borrowerName}, your loan ${loanNumber} (${outstandingBalance}) is overdue. Please contact us immediately to avoid additional charges.`;
        } else {
            message = `Hello ${borrowerName}, this is a reminder about your loan ${loanNumber} (${outstandingBalance}). Please ensure payment is made on time.`;
        }
        
        // Show contact options
        if (confirm(`${message}\n\nWould you like to call the borrower?`)) {
            // In a real application, this would integrate with a phone system
            alert('Calling functionality would be implemented here. For now, please contact the borrower manually.');
        }
    }
    
    // View loan details functionality
    function viewLoanDetails(loanId) {
        // Redirect to loan details page
        window.location.href = `/loans/${loanId}/`;
    }
    
    // Auto-refresh functionality
    function refreshDashboard() {
        location.reload();
    }
    
    // Auto-refresh every 5 minutes
    setInterval(refreshDashboard, 300000);
    
    // Pagination functionality
    function changePage(category, page) {
        const url = new URL(window.location);
        url.searchParams.set(`${category}_page`, page);
        window.location.href = url.toString();
    }
    
    // Show all loans functionality
    function toggleShowAll(category) {
        const url = new URL(window.location);
        url.searchParams.set(`${category}_page`, 1);
        url.searchParams.set(`${category}_show_all`, 'true');
        window.location.href = url.toString();
    }
    
    // Add loading states to buttons
    document.addEventListener('DOMContentLoaded', function() {
        const actionButtons = document.querySelectorAll('.action-btn');
        actionButtons.forEach(button => {
            button.addEventListener('click', function() {
                const originalText = this.innerHTML;
                this.innerHTML = '<span>⟳</span> Processing...';
                this.disabled = true;
                
                // Re-enable after 2 seconds
                setTimeout(() => {
                    this.innerHTML = originalText;
                    this.disabled = false;
                }, 2000);
            });
        });
    });
</script>
{% endblock %}