# api/views.py
from rest_framework import viewsets, permissions, generics
from rest_framework.response import Response
from rest_framework.views import APIView
from django.db.models import Count, Sum
from datetime import date

from students.models import Student
from staff.models import Staff
from academics.models import SchoolClass, Attendance
from finance.models import Invoice, Payment
from .serializers import (
    StudentSerializer, StaffSerializer, 
    SchoolClassSerializer, InvoiceSerializer
)

class StudentViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer
    permission_classes = [permissions.IsAuthenticated]

class StaffViewSet(viewsets.ModelViewSet):
    queryset = Staff.objects.all()
    serializer_class = StaffSerializer
    permission_classes = [permissions.IsAuthenticated]

class ClassViewSet(viewsets.ModelViewSet):
    queryset = SchoolClass.objects.all()
    serializer_class = SchoolClassSerializer
    permission_classes = [permissions.IsAuthenticated]

class InvoiceViewSet(viewsets.ModelViewSet):
    queryset = Invoice.objects.all()
    serializer_class = InvoiceSerializer
    permission_classes = [permissions.IsAuthenticated]

class DashboardStats(APIView):
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request):
        data = {
            'total_students': Student.objects.count(),
            'total_staff': Staff.objects.count(),
            'total_classes': SchoolClass.objects.count(),
            'today_attendance': Attendance.objects.filter(date=date.today()).count(),
            'pending_invoices': Invoice.objects.filter(status='pending').count(),
            'total_revenue': Payment.objects.filter(status='completed').aggregate(Sum('amount'))['amount__sum'] or 0,
        }
        return Response(data)