from django.shortcuts import render, redirect
from .forms import ExpenseForm
from .models import Expense, Category
from django.db.models import Sum

def home(request):
    """Render the landing screen and handle expense form submission."""
    if request.method == 'POST':
        form = ExpenseForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = ExpenseForm()
    
    expenses = Expense.objects.all()
    
    # Filtering logic
    category_id = request.GET.get('category')
    if category_id:
        expenses = expenses.filter(category_id=category_id)
        
    expenses = expenses.order_by('-date')
    
    # Analysis
    total_expenses = expenses.aggregate(Sum('amount'))['amount__sum'] or 0
    category_summary = expenses.values('category__name').annotate(total=Sum('amount')).order_by('-total')

    categories = Category.objects.all()
    
    return render(request, "core/index.html", {
        'form': form, 
        'expenses': expenses,
        'categories': categories,
        'total_expenses': total_expenses,
        'category_summary': category_summary,
    })

