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

{% block title %}Loan Amortization Schedule - {{ loan.loan_number }}{% endblock %}

{% block extra_css %}
<style>
    .amortization-container {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        min-height: 100vh;
        padding: 2rem 0;
    }
    
    .amortization-card {
        background: white;
        border-radius: 20px;
        box-shadow: 0 20px 40px rgba(0,0,0,0.1);
        overflow: hidden;
        margin-bottom: 2rem;
    }
    
    .amortization-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 2rem;
        text-align: center;
    }
    
    .amortization-header h1 {
        font-size: 2.5rem;
        font-weight: 700;
        margin-bottom: 0.5rem;
        text-shadow: 0 2px 4px rgba(0,0,0,0.3);
    }
    
    .amortization-header .subtitle {
        font-size: 1.1rem;
        opacity: 0.9;
    }
    
    .loan-summary {
        background: #f8f9fa;
        padding: 2rem;
        border-bottom: 1px solid #e9ecef;
    }
    
    .summary-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }
    
    .summary-card {
        background: white;
        padding: 1.5rem;
        border-radius: 15px;
        box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        border-left: 4px solid #667eea;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }
    
    .summary-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 25px rgba(0,0,0,0.15);
    }
    
    .summary-card h3 {
        color: #667eea;
        font-size: 0.9rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 1px;
        margin-bottom: 0.5rem;
    }
    
    .summary-card .value {
        font-size: 1.8rem;
        font-weight: 700;
        color: #2c3e50;
        margin-bottom: 0.25rem;
    }
    
    .summary-card .label {
        font-size: 0.85rem;
        color: #6c757d;
    }
    
    .schedule-container {
        padding: 2rem;
    }
    
    .schedule-header {
        display: flex;
        justify-content: between;
        align-items: center;
        margin-bottom: 2rem;
        padding-bottom: 1rem;
        border-bottom: 2px solid #e9ecef;
    }
    
    .schedule-title {
        font-size: 1.8rem;
        font-weight: 700;
        color: #2c3e50;
    }
    
    .export-buttons {
        display: flex;
        gap: 1rem;
    }
    
    .btn-export {
        padding: 0.75rem 1.5rem;
        border-radius: 10px;
        font-weight: 600;
        text-decoration: none;
        transition: all 0.3s ease;
        border: none;
        cursor: pointer;
    }
    
    .btn-export-pdf {
        background: linear-gradient(135deg, #e74c3c, #c0392b);
        color: white;
    }
    
    .btn-export-pdf:hover {
        background: linear-gradient(135deg, #c0392b, #a93226);
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(231, 76, 60, 0.4);
    }
    
    .btn-export-excel {
        background: linear-gradient(135deg, #27ae60, #229954);
        color: white;
    }
    
    .btn-export-excel:hover {
        background: linear-gradient(135deg, #229954, #1e8449);
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(39, 174, 96, 0.4);
    }
    
    .schedule-table {
        width: 100%;
        border-collapse: collapse;
        background: white;
        border-radius: 15px;
        overflow: hidden;
        box-shadow: 0 10px 30px rgba(0,0,0,0.1);
    }
    
    .schedule-table thead {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }
    
    .schedule-table th {
        padding: 1.25rem 1rem;
        text-align: left;
        font-weight: 600;
        font-size: 0.9rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    
    .schedule-table td {
        padding: 1rem;
        border-bottom: 1px solid #f1f3f4;
        font-size: 0.9rem;
    }
    
    .schedule-table tbody tr {
        transition: background-color 0.3s ease;
    }
    
    .schedule-table tbody tr:hover {
        background-color: #f8f9fa;
    }
    
    .schedule-table tbody tr:nth-child(even) {
        background-color: #fafbfc;
    }
    
    .schedule-table tbody tr:nth-child(even):hover {
        background-color: #f1f3f4;
    }
    
    .payment-number {
        font-weight: 700;
        color: #667eea;
        text-align: center;
    }
    
    .payment-date {
        color: #495057;
        font-weight: 500;
    }
    
    .amount {
        font-weight: 600;
        color: #2c3e50;
        text-align: right;
    }
    
    .principal {
        color: #27ae60;
    }
    
    .interest {
        color: #e74c3c;
    }
    
    .processing-fee {
        color: #f39c12;
    }
    
    .balance {
        color: #3498db;
        font-weight: 700;
    }
    
    .cumulative-interest {
        color: #9b59b6;
        font-weight: 600;
    }
    
    .payment-status {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        border-radius: 20px;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    
    .status-paid {
        background: #d4edda;
        color: #155724;
    }
    
    .status-pending {
        background: #fff3cd;
        color: #856404;
    }
    
    .status-overdue {
        background: #f8d7da;
        color: #721c24;
    }
    
    .progress-section {
        background: #f8f9fa;
        padding: 2rem;
        border-top: 1px solid #e9ecef;
    }
    
    .progress-title {
        font-size: 1.5rem;
        font-weight: 700;
        color: #2c3e50;
        margin-bottom: 1.5rem;
        text-align: center;
    }
    
    .progress-stats {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }
    
    .progress-stat {
        text-align: center;
        padding: 1.5rem;
        background: white;
        border-radius: 15px;
        box-shadow: 0 5px 15px rgba(0,0,0,0.08);
    }
    
    .progress-stat .number {
        font-size: 2rem;
        font-weight: 700;
        color: #667eea;
        margin-bottom: 0.5rem;
    }
    
    .progress-stat .label {
        font-size: 0.9rem;
        color: #6c757d;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    
    .progress-bar-container {
        background: white;
        padding: 2rem;
        border-radius: 15px;
        box-shadow: 0 5px 15px rgba(0,0,0,0.08);
    }
    
    .progress-bar {
        width: 100%;
        height: 20px;
        background: #e9ecef;
        border-radius: 10px;
        overflow: hidden;
        margin-bottom: 1rem;
    }
    
    .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        border-radius: 10px;
        transition: width 0.8s ease;
        position: relative;
    }
    
    .progress-fill::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(90deg, transparent 0%, rgba(255,255,255,0.3) 50%, transparent 100%);
        animation: shimmer 2s infinite;
    }
    
    @keyframes shimmer {
        0% { transform: translateX(-100%); }
        100% { transform: translateX(100%); }
    }
    
    .progress-text {
        text-align: center;
        font-size: 1.1rem;
        font-weight: 600;
        color: #2c3e50;
    }
    
    .footer-info {
        background: #2c3e50;
        color: white;
        padding: 1.5rem;
        text-align: center;
        font-size: 0.9rem;
    }
    
    .footer-info .generated-at {
        opacity: 0.8;
    }
    
    @media (max-width: 768px) {
        .amortization-header h1 {
            font-size: 2rem;
        }
        
        .summary-grid {
            grid-template-columns: 1fr;
        }
        
        .schedule-header {
            flex-direction: column;
            gap: 1rem;
            text-align: center;
        }
        
        .export-buttons {
            justify-content: center;
        }
        
        .schedule-table {
            font-size: 0.8rem;
        }
        
        .schedule-table th,
        .schedule-table td {
            padding: 0.75rem 0.5rem;
        }
        
        .progress-stats {
            grid-template-columns: repeat(2, 1fr);
        }
    }
    
    @media (max-width: 480px) {
        .amortization-container {
            padding: 1rem 0;
        }
        
        .amortization-header {
            padding: 1.5rem;
        }
        
        .loan-summary,
        .schedule-container,
        .progress-section {
            padding: 1.5rem;
        }
        
        .schedule-table th,
        .schedule-table td {
            padding: 0.5rem 0.25rem;
            font-size: 0.75rem;
        }
        
        .progress-stats {
            grid-template-columns: 1fr;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="amortization-container">
    <div class="container">
        <div class="amortization-card">
            <!-- Header -->
            <div class="amortization-header">
                <h1><span>🧮</span> Loan Amortization Schedule</h1>
                <div class="subtitle">{{ loan.loan_number }} - {{ loan.borrower.get_full_name }}</div>
            </div>
            
            <!-- Loan Summary -->
            <div class="loan-summary">
                <div class="summary-grid">
                    <div class="summary-card">
                        <h3>Principal Amount</h3>
                        <div class="value">KES {{ loan.principal_amount|floatformat:2 }}</div>
                        <div class="label">Original loan amount</div>
                    </div>
                    
                    <div class="summary-card">
                        <h3>Interest Amount</h3>
                        <div class="value">KES {{ total_interest|floatformat:2 }}</div>
                        <div class="label">Total interest to be paid</div>
                    </div>
                    
                    <div class="summary-card">
                        <h3>Processing Fee</h3>
                        <div class="value">KES {{ total_processing_fee|floatformat:2 }}</div>
                        <div class="label">One-time processing fee</div>
                    </div>
                    
                    <div class="summary-card">
                        <h3>Total Amount</h3>
                        <div class="value">KES {{ total_amount|floatformat:2 }}</div>
                        <div class="label">Total amount to be repaid</div>
                    </div>
                    
                    <div class="summary-card">
                        <h3>Amount Paid</h3>
                        <div class="value">KES {{ total_paid|floatformat:2 }}</div>
                        <div class="label">Total amount paid so far</div>
                    </div>
                    
                    <div class="summary-card">
                        <h3>Remaining Balance</h3>
                        <div class="value">KES {{ remaining_balance|floatformat:2 }}</div>
                        <div class="label">Outstanding balance</div>
                    </div>
                </div>
            </div>
            
            <!-- Schedule -->
            <div class="schedule-container">
                <div class="schedule-header">
                    <h2 class="schedule-title">Payment Schedule</h2>
                    <div class="export-buttons">
                        <button class="btn-export btn-export-pdf" onclick="window.print()">
                            <span>📄</span> Print PDF
                        </button>
                        <button class="btn-export btn-export-excel" onclick="exportToExcel()">
                            <span>📊</span> Export Excel
                        </button>
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="schedule-table">
                        <thead>
                            <tr>
                                <th>Payment #</th>
                                <th>Payment Date</th>
                                <th>Beginning Balance</th>
                                <th>Scheduled Payment</th>
                                <th>Principal</th>
                                <th>Interest</th>
                                <th>Processing Fee</th>
                                <th>Amount Paid</th>
                                <th>Ending Balance</th>
                                <th>Cumulative Interest</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for payment in amortization_schedule %}
                            <tr>
                                <td class="payment-number">{{ payment.payment_number }}</td>
                                <td class="payment-date">{{ payment.payment_date|date:"M d, Y" }}</td>
                                <td class="amount">KES {{ payment.beginning_balance|floatformat:2 }}</td>
                                <td class="amount">KES {{ payment.scheduled_payment|floatformat:2 }}</td>
                                <td class="amount principal">KES {{ payment.principal|floatformat:2 }}</td>
                                <td class="amount interest">KES {{ payment.interest|floatformat:2 }}</td>
                                <td class="amount processing-fee">KES {{ payment.processing_fee|floatformat:2 }}</td>
                                <td class="amount principal">KES {{ payment.amount_paid|default:"0.00"|floatformat:2 }}</td>
                                <td class="amount balance">KES {{ payment.ending_balance|floatformat:2 }}</td>
                                <td class="amount cumulative-interest">KES {{ payment.cumulative_interest|floatformat:2 }}</td>
                                <td>
                                    {% if payment.payment_number <= total_payments_made %}
                                        <span class="payment-status status-paid">Paid</span>
                                    {% elif payment.payment_date|date:"Y-m-d" < today|date:"Y-m-d" %}
                                        <span class="payment-status status-overdue">Overdue</span>
                                    {% else %}
                                        <span class="payment-status status-pending">Pending</span>
                                    {% endif %}
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Progress Section -->
            <div class="progress-section">
                <h3 class="progress-title">Payment Progress</h3>
                
                <div class="progress-stats">
                    <div class="progress-stat">
                        <div class="number">{{ total_payments_made }}</div>
                        <div class="label">Payments Made</div>
                    </div>
                    
                    <div class="progress-stat">
                        <div class="number">{{ total_scheduled_payments }}</div>
                        <div class="label">Total Payments</div>
                    </div>
                    
                    <div class="progress-stat">
                        <div class="number">{{ payments_remaining }}</div>
                        <div class="label">Payments Remaining</div>
                    </div>
                    
                    <div class="progress-stat">
                        <div class="number">{{ loan.repayment_method|title }}</div>
                        <div class="label">Payment Frequency</div>
                    </div>
                </div>
                
                <div class="progress-bar-container">
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: {% widthratio total_paid total_amount 100 %}%"></div>
                    </div>
                    <div class="progress-text">
                        {{ total_paid|floatformat:2 }} of {{ total_amount|floatformat:2 }} KES paid 
                        ({% widthratio total_paid total_amount 100 %}%)
                    </div>
                </div>
            </div>
            
            <!-- Footer -->
            <div class="footer-info">
                <div class="generated-at">
                    Generated on {{ generated_at|date:"F d, Y \a\t g:i A" }} | 
                    Haven Grazuri Investment Limited Loan Management System
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function exportToExcel() {
    // Create a simple Excel export functionality
    const table = document.querySelector('.schedule-table');
    const rows = Array.from(table.querySelectorAll('tr'));
    
    let csvContent = '';
    rows.forEach(row => {
        const cells = Array.from(row.querySelectorAll('th, td'));
        const rowData = cells.map(cell => {
            let text = cell.textContent.trim();
            // Remove KES prefix and clean up
            text = text.replace('KES ', '');
            // Escape commas and quotes
            if (text.includes(',') || text.includes('"')) {
                text = '"' + text.replace(/"/g, '""') + '"';
            }
            return text;
        });
        csvContent += rowData.join(',') + '\n';
    });
    
    // Create and download file
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', 'loan_amortization_{{ loan.loan_number }}.csv');
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// Add print styles
window.addEventListener('beforeprint', function() {
    document.body.style.background = 'white';
    document.querySelector('.amortization-container').style.background = 'white';
    document.querySelector('.amortization-container').style.padding = '0';
});

window.addEventListener('afterprint', function() {
    document.body.style.background = '';
    document.querySelector('.amortization-container').style.background = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
    document.querySelector('.amortization-container').style.padding = '2rem 0';
});
</script>
{% endblock %}
