# core/views.py
from django.shortcuts import render
from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
from students.models import Student
from academics.models import SchoolClass, Attendance, Subject
from finance.models import Invoice, Payment
from communication.models import Announcement
from datetime import date, timedelta
from django.db.models import Sum, Count

class DashboardView(LoginRequiredMixin, TemplateView):
    template_name = 'dashboard.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # Basic stats
        today = date.today()
        context['total_students'] = Student.objects.count()
        context['total_classes'] = SchoolClass.objects.count()
        context['total_subjects'] = Subject.objects.count()
        
        # Today's attendance
        context['today_attendance'] = Attendance.objects.filter(date=today).count()
        present_today = Attendance.objects.filter(date=today, status='present').count()
        context['attendance_rate'] = round((present_today / context['today_attendance'] * 100) if context['today_attendance'] > 0 else 0, 1)
        
        # Finance stats
        context['total_revenue'] = Payment.objects.filter(status='completed').aggregate(Sum('amount'))['amount__sum'] or 0
        context['pending_invoices'] = Invoice.objects.filter(status='pending').count()
        context['overdue_invoices'] = Invoice.objects.filter(status='overdue').count()
        
        # Recent data
        context['recent_students'] = Student.objects.order_by('-created_at')[:5]
        context['recent_announcements'] = Announcement.objects.order_by('-publish_date')[:3]
        context['upcoming_birthdays'] = Student.objects.filter(
            date_of_birth__month=today.month,
            date_of_birth__day__gte=today.day
        ).order_by('date_of_birth')[:5]
        
        # Chart data (you can use Chart.js later)
        last_7_days = [today - timedelta(days=i) for i in range(6, -1, -1)]
        attendance_data = []
        for day in last_7_days:
            count = Attendance.objects.filter(date=day).count()
            attendance_data.append(count)
        
        context['attendance_labels'] = [d.strftime('%a') for d in last_7_days]
        context['attendance_data'] = attendance_data
        
        return context
    
class HomeView(TemplateView):
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['school_name'] = "Rapha-Bethel School BNPS"
        return context

def handler_403(request, exception=None):
    return render(request, '403.html', {'exception': str(exception) if exception else None}, status=403)

def handler_404(request, exception=None):
    return render(request, '404.html', {}, status=404)
