from django.shortcuts import render
from .models import Account, Ledger, Invoice, Bill
from django.db.models import Sum

def account_list(request):
    accounts = Account.objects.all()
    return render(request, 'accounting/account_list.html', {'accounts': accounts})

def trial_balance(request):
    accounts = Account.objects.all()
    report_data = []
    total_debits = 0
    total_credits = 0

    for account in accounts:
        debit_total = Ledger.objects.filter(account=account).aggregate(Sum('debit'))['debit__sum'] or 0
        credit_total = Ledger.objects.filter(account=account).aggregate(Sum('credit'))['credit__sum'] or 0

        balance = debit_total - credit_total

        report_data.append({
            'number': account.number,
            'name': account.name,
            'debit': debit_total,
            'credit': credit_total,
        })

        total_debits += debit_total
        total_credits += credit_total

    return render(request, 'accounting/trial_balance.html', {
        'report_data': report_data,
        'total_debits': total_debits,
        'total_credits': total_credits,
    })

def invoice_list(request):
    invoices = Invoice.objects.all()
    return render(request, 'accounting/invoice_list.html', {'invoices': invoices})

def bill_list(request):
    bills = Bill.objects.all()
    return render(request, 'accounting/bill_list.html', {'bills': bills})