from django.shortcuts import render,get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from decimal import Decimal

@login_required
def interest_schedule(request, pk):
    """Display interest schedule for a loan"""
    from loans.models import Loan
    
    loan = get_object_or_404(Loan, pk=pk)
    
    # Get payment schedule
    try:
        schedule = loan.get_payment_schedule()
    except:
        schedule = []
    
    # Calculate interest breakdown
    principal = loan.principal_amount or Decimal('0.00')
    interest_amount = loan.get_display_interest_amount()
    processing_fee = loan.get_display_processing_fee_amount()
    total_amount = principal + interest_amount + processing_fee
    
    # Calculate interest paid vs outstanding
    amount_paid = loan.amount_paid or Decimal('0.00')
    if total_amount > 0:
        interest_portion = interest_earned / total_amount
        interest_paid = min(interest_amount, amount_paid * interest_portion)
        interest_outstanding = interest_amount - interest_paid
    else:
        interest_paid = Decimal('0.00')
        interest_outstanding = Decimal('0.00')
    
    context = {
        'loan': loan,
        'schedule': schedule,
        'interest_breakdown': {
            'total_interest': interest_amount,
            'interest_paid': interest_paid,
            'interest_outstanding': interest_outstanding,
            'interest_rate': loan.get_display_interest_rate(),
        }
    }
    
    return render(request, 'loans/interest_schedule.html', context)
