# staff/views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView, TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
from core.permissions import ManagementRequiredMixin, BursarRequiredMixin, HeadRequiredMixin, can, is_support_only
from django.contrib.auth.views import LoginView, LogoutView
from django.contrib import messages
from django.urls import reverse_lazy
from django.db.models import Q, Count
from django.http import JsonResponse, HttpResponse
from django.contrib.auth import get_user_model
from datetime import datetime
from datetime import date 
import csv
import io

from .models import Staff, StaffLeave, StaffAttendance, StaffDocument
from .forms import StaffForm, StaffUserForm, StaffLeaveForm, StaffAttendanceForm
from core.models import School

User = get_user_model()

# ========== MAIN STAFF VIEWS ==========

class StaffListView(LoginRequiredMixin, ListView):
    """List all staff members"""
    model = Staff
    template_name = 'staff/staff_list.html'
    context_object_name = 'staff_members'
    paginate_by = 20
    
    def get_queryset(self):
        queryset = super().get_queryset().select_related('user', 'school')
        
        # Search
        search_query = self.request.GET.get('q')
        if search_query:
            queryset = queryset.filter(
                Q(user__first_name__icontains=search_query) |
                Q(user__last_name__icontains=search_query) |
                Q(employee_id__icontains=search_query) |
                Q(phone_number__icontains=search_query) |
                Q(user__email__icontains=search_query)
            )
        
        # Filter by role
        role = self.request.GET.get('role')
        if role:
            queryset = queryset.filter(role=role)
        
        # Filter by department
        department = self.request.GET.get('department')
        if department:
            queryset = queryset.filter(department=department)
        
        # Filter by status
        status = self.request.GET.get('status')
        if status == 'active':
            queryset = queryset.filter(is_active=True)
        elif status == 'inactive':
            queryset = queryset.filter(is_active=False)
        
        return queryset.order_by('role', 'user__first_name')
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['total_staff'] = Staff.objects.count()
        context['active_staff'] = Staff.objects.filter(is_active=True).count()
        context['role_choices'] = Staff.ROLE_CHOICES
        context['department_choices'] = Staff.DEPARTMENT_CHOICES
        return context

class StaffDetailView(LoginRequiredMixin, DetailView):
    """View staff member details"""
    model = Staff
    template_name = 'staff/staff_detail.html'
    context_object_name = 'staff'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # Get leave requests
        context['leave_requests'] = StaffLeave.objects.filter(staff=self.object).order_by('-created_at')[:5]
        
        # Get attendance records
        context['attendance'] = StaffAttendance.objects.filter(staff=self.object).order_by('-date')[:30]
        
        # Get documents
        context['documents'] = StaffDocument.objects.filter(staff=self.object)
        
        return context

class StaffCreateView(ManagementRequiredMixin, CreateView):
    """Create a new staff member — creates User account + Staff profile together."""
    model = Staff
    form_class = StaffForm
    template_name = 'staff/staff_form.html'
    success_url = reverse_lazy('staff:staff_list')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Add New Staff Member'
        if self.request.POST:
            context['user_form'] = StaffUserForm(self.request.POST)
        else:
            context['user_form'] = StaffUserForm()
        return context

    def form_valid(self, form):
        user_form = StaffUserForm(self.request.POST)
        if not user_form.is_valid():
            return self.render_to_response(self.get_context_data(form=form))
        if not user_form.cleaned_data.get('password'):
            user_form.add_error('password', 'A password is required when creating a new account.')
            return self.render_to_response(self.get_context_data(form=form))
        user = user_form.save()
        form.instance.user = user
        school = School.objects.first()
        if school:
            form.instance.school = school
        messages.success(self.request, f'Staff member {user.get_full_name()} added successfully.')
        return super().form_valid(form)

class StaffUpdateView(ManagementRequiredMixin, UpdateView):
    """Update staff member information — saves both User name fields and Staff profile."""
    model = Staff
    form_class = StaffForm
    template_name = 'staff/staff_form.html'
    success_url = reverse_lazy('staff:staff_list')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = f'Edit {self.object.get_full_name()}'
        if self.request.POST:
            context['user_form'] = StaffUserForm(self.request.POST, instance=self.object.user)
        else:
            context['user_form'] = StaffUserForm(instance=self.object.user)
        return context

    def form_valid(self, form):
        user_form = StaffUserForm(self.request.POST, instance=self.object.user)
        if not user_form.is_valid():
            return self.render_to_response(self.get_context_data(form=form))
        user_form.save()
        messages.success(self.request, f'Staff member {self.object.get_full_name()} updated successfully.')
        return super().form_valid(form)


class StaffDeleteView(HeadRequiredMixin, DeleteView):
    """Deactivate staff member"""
    model = Staff
    success_url = reverse_lazy('staff:staff_list')
    template_name = 'staff/staff_confirm_delete.html'
    
    def delete(self, request, *args, **kwargs):
        staff = self.get_object()
        staff.is_active = False
        staff.user.is_active = False
        staff.user.save()
        staff.save()
        messages.success(request, f'{staff.user.get_full_name()} has been deactivated.')
        return redirect(self.success_url)

class StaffDashboardView(LoginRequiredMixin, TemplateView):
    """Staff dashboard based on role — support staff get a limited view"""
    template_name = 'staff/dashboard.html'

    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated and hasattr(request.user, 'staff_profile'):
            from core.permissions import is_support_only
            if is_support_only(request.user):
                return self._support_dashboard(request)
        return super().dispatch(request, *args, **kwargs)

    def _support_dashboard(self, request):
        from datetime import date as _date
        from staff.models import StaffAttendance, StaffLeave
        staff = request.user.staff_profile
        today = _date.today()
        month_att = StaffAttendance.objects.filter(
            staff=staff, date__month=today.month, date__year=today.year)
        context = {
            'today': today,
            'my_leaves': StaffLeave.objects.filter(staff=staff).order_by('-start_date')[:5],
            'present_count': month_att.filter(status='present').count(),
            'absent_count':  month_att.filter(status='absent').count(),
            'late_count':    month_att.filter(status='late').count(),
        }
        from django.shortcuts import render as _render
        return _render(request, 'staff/support_dashboard.html', context)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        # Get current staff profile
        if hasattr(self.request.user, 'staff_profile'):
            staff = self.request.user.staff_profile
            
            # Basic stats
            context['total_staff'] = Staff.objects.count()
            context['active_staff'] = Staff.objects.filter(is_active=True).count()
            context['teachers_count'] = Staff.objects.filter(role__in=['teacher', 'class_teacher', 'subject_teacher']).count()
            context['class_teachers'] = Staff.objects.filter(role='class_teacher').count()
            
            # Leave stats
            context['pending_leaves'] = StaffLeave.objects.filter(status='pending').count()
            context['approved_leaves'] = StaffLeave.objects.filter(status='approved').count()
            
            # Today's attendance
            today = date.today()
            context['today_attendance'] = StaffAttendance.objects.filter(date=today).count()
            
            total_staff_active = Staff.objects.filter(is_active=True).count()
            if total_staff_active > 0:
                present_today = StaffAttendance.objects.filter(date=today, status='present').count()
                context['present_percent'] = round((present_today / total_staff_active) * 100, 1)
            else:
                context['present_percent'] = 0
            
            # Dashboard type based on role
            if staff.role == 'proprietor':
                context['dashboard_type'] = 'proprietor'
                from students.models import Student
                from academics.models import SchoolClass
                from finance.models import Invoice, Payment
                
                context['total_students'] = Student.objects.count()
                context['total_classes'] = SchoolClass.objects.count()
                context['total_parents'] = ParentGuardian.objects.count()
                
                # Monthly revenue
                from datetime import datetime, timedelta
                first_day = today.replace(day=1)
                payments = Payment.objects.filter(
                    payment_date__gte=first_day,
                    status='completed'
                )
                context['monthly_revenue'] = payments.aggregate(Sum('amount'))['amount__sum'] or 0
                context['pending_invoices'] = Invoice.objects.filter(status='pending').count()
                
            elif staff.role in ['head_master', 'head_mistress']:
                context['dashboard_type'] = 'head'
                context['department_name'] = staff.get_department_display()
                
                # Recent activities (you'd need to implement this)
                context['recent_activities'] = []
                
            elif staff.role == 'teacher' or staff.role == 'class_teacher':
                context['dashboard_type'] = 'teacher'
                from academics.models import ClassSubject
                assigned_classes = ClassSubject.objects.filter(teacher=staff).values_list('school_class', flat=True).distinct()
                context['my_classes'] = SchoolClass.objects.filter(id__in=assigned_classes)
                
            else:
                context['dashboard_type'] = 'staff'
            
            # Recent activities (example - you'd need to create an ActivityLog model)
            context['recent_activities'] = []
        
        # Current date and time
        from datetime import datetime
        context['current_date'] = datetime.now()
        context['current_time'] = datetime.now()
        
        return context
    
    # def get_context_data(self, **kwargs):
    #     context = super().get_context_data(**kwargs)
    #     staff = self.request.user.staff_profile
        
    #     context['staff'] = staff
    #     context['total_staff'] = Staff.objects.count()
    #     context['active_staff'] = Staff.objects.filter(is_active=True).count()
        
    #     if staff.role == 'proprietor':
    #         context['dashboard_type'] = 'proprietor'
    #         from students.models import Student
    #         context['total_students'] = Student.objects.count()
    #     elif staff.role in ['head_master', 'head_mistress']:
    #         context['dashboard_type'] = 'head'
    #         context['department_staff'] = Staff.objects.filter(department=staff.department)
    #     elif staff.role == 'bursar':
    #         context['dashboard_type'] = 'bursar'
    #         from finance.models import Invoice
    #         context['pending_invoices'] = Invoice.objects.filter(status='pending').count()
    #     else:
    #         context['dashboard_type'] = 'staff'
        
    #     return context

class TeacherDashboardView(LoginRequiredMixin, TemplateView):
    """Teacher dashboard showing classes and attendance"""
    template_name = 'staff/teacher_dashboard.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        if not hasattr(self.request.user, 'staff_profile'):
            return context
        
        teacher = self.request.user.staff_profile
        
        # Get classes this teacher teaches
        from academics.models import ClassSubject, Attendance
        teacher_assignments = ClassSubject.objects.filter(
            teacher=teacher
        ).select_related('school_class', 'subject')
        
        # Group by class
        classes_dict = {}
        for assignment in teacher_assignments:
            class_id = assignment.school_class.id
            if class_id not in classes_dict:
                classes_dict[class_id] = {
                    'class': assignment.school_class,
                    'subjects': [],
                    'student_count': assignment.school_class.students.count(),
                    'today_attendance_taken': Attendance.objects.filter(
                        school_class=assignment.school_class,
                        date=date.today()
                    ).exists()
                }
            classes_dict[class_id]['subjects'].append(assignment.subject)
        
        context['my_classes'] = list(classes_dict.values())
        context['today'] = date.today()
        
        # Recent attendance by this teacher
        context['recent_attendance'] = Attendance.objects.filter(
            marked_by=teacher
        ).select_related('student').order_by('-date')[:10]
        
        return context
# ========== LEAVE MANAGEMENT ==========

class StaffLeaveListView(LoginRequiredMixin, ListView):
    """List all leave requests"""
    model = StaffLeave
    template_name = 'staff/leave_list.html'
    context_object_name = 'leaves'
    paginate_by = 20
    
    def get_queryset(self):
        queryset = StaffLeave.objects.all().select_related('staff', 'approved_by')
        
        # Filter by status
        status = self.request.GET.get('status')
        if status:
            queryset = queryset.filter(status=status)
        
        # Filter by staff
        staff_id = self.request.GET.get('staff')
        if staff_id:
            queryset = queryset.filter(staff_id=staff_id)
        
        return queryset.order_by('-created_at')
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['pending_count'] = StaffLeave.objects.filter(status='pending').count()
        context['approved_count'] = StaffLeave.objects.filter(status='approved').count()
        return context

class StaffLeaveCreateView(LoginRequiredMixin, CreateView):
    """Create a leave request"""
    model = StaffLeave
    fields = ['leave_type', 'start_date', 'end_date', 'reason']
    template_name = 'staff/leave_form.html'
    success_url = reverse_lazy('staff:leave_list')
    
    def form_valid(self, form):
        form.instance.staff = self.request.user.staff_profile
        form.instance.status = 'pending'
        messages.success(self.request, 'Leave request submitted successfully!')
        return super().form_valid(form)

class StaffLeaveUpdateView(LoginRequiredMixin, UpdateView):
    """Edit a pending leave request"""
    model = StaffLeave
    fields = ['leave_type', 'start_date', 'end_date', 'reason']
    template_name = 'staff/leave_form.html'
    success_url = reverse_lazy('staff:leave_list')

    def get_queryset(self):
        # Staff can only edit their own pending requests; admins can edit any
        qs = StaffLeave.objects.filter(status='pending')
        if not self.request.user.is_staff:
            qs = qs.filter(staff=self.request.user.staff_profile)
        return qs

    def form_valid(self, form):
        messages.success(self.request, 'Leave request updated successfully!')
        return super().form_valid(form)


class StaffLeaveDetailView(LoginRequiredMixin, DetailView):
    """View leave request details"""
    model = StaffLeave
    template_name = 'staff/leave_detail.html'
    context_object_name = 'leave'

def approve_leave(request, pk):
    """Approve a leave request"""
    leave = get_object_or_404(StaffLeave, pk=pk)
    
    if request.method == 'POST':
        leave.status = 'approved'
        leave.approved_by = request.user.staff_profile
        leave.approved_date = datetime.now().date()
        leave.save()
        messages.success(request, 'Leave request approved.')
    
    return redirect('staff:leave_detail', pk=pk)

def reject_leave(request, pk):
    """Reject a leave request"""
    leave = get_object_or_404(StaffLeave, pk=pk)
    
    if request.method == 'POST':
        leave.status = 'rejected'
        leave.save()
        messages.success(request, 'Leave request rejected.')
    
    return redirect('staff:leave_list')

# ========== STAFF ATTENDANCE ==========

# class StaffAttendanceListView(LoginRequiredMixin, ListView):
#     """List staff attendance records"""
#     model = StaffAttendance
#     template_name = 'staff/attendance_list.html'
#     context_object_name = 'attendances'
#     paginate_by = 50
    
#     def get_queryset(self):
#         queryset = StaffAttendance.objects.all().select_related('staff')
        
#         date = self.request.GET.get('date')
#         if date:
#             queryset = queryset.filter(date=date)
        
#         return queryset.order_by('-date')

# def mark_staff_attendance(request):
#     """Mark staff attendance"""
#     if request.method == 'POST':
#         staff_id = request.POST.get('staff_id')
#         status = request.POST.get('status')
#         date = request.POST.get('date')
        
#         if staff_id and status and date:
#             staff = get_object_or_404(Staff, id=staff_id)
#             attendance, created = StaffAttendance.objects.get_or_create(
#                 staff=staff,
#                 date=date,
#                 defaults={'status': status}
#             )
            
#             if not created:
#                 attendance.status = status
#                 attendance.save()
            
#             messages.success(request, f'Attendance marked for {staff.user.get_full_name()}')
        
#         return redirect('staff:attendance_list')
    
#     staff_members = Staff.objects.filter(is_active=True)
#     return render(request, 'staff/mark_attendance.html', {
#         'staff_members': staff_members,
#         'today': datetime.now().date()
#     })

class StaffAttendanceListView(LoginRequiredMixin, ListView):
    """List staff attendance records"""
    model = StaffAttendance
    template_name = 'staff/attendance_list.html'
    context_object_name = 'attendances'
    paginate_by = 20
    
    def get_queryset(self):
        queryset = StaffAttendance.objects.all().select_related('staff__user')
        
        # Filter by date
        date = self.request.GET.get('date')
        if date:
            queryset = queryset.filter(date=date)
        
        # Filter by staff
        staff_id = self.request.GET.get('staff')
        if staff_id:
            queryset = queryset.filter(staff_id=staff_id)
        
        return queryset.order_by('-date')
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['staff_members'] = Staff.objects.filter(is_active=True)
        context['today'] = date.today()
        return context

def mark_staff_attendance(request):
    """Mark staff attendance"""
    if request.method == 'POST':
        staff_id = request.POST.get('staff_id')
        status = request.POST.get('status')
        attendance_date = request.POST.get('date', date.today())
        
        if staff_id and status:
            staff = get_object_or_404(Staff, id=staff_id)
            attendance, created = StaffAttendance.objects.update_or_create(
                staff=staff,
                date=attendance_date,
                defaults={'status': status}
            )
            messages.success(request, f'Attendance marked for {staff.user.get_full_name()}')
        
        return redirect('staff:attendance_list')
    
    staff_members = Staff.objects.filter(is_active=True)
    return render(request, 'staff/mark_attendance.html', {
        'staff_members': staff_members,
        'today': datetime.today()
    })

class StaffAttendanceDetailView(LoginRequiredMixin, DetailView):
    """View staff attendance details"""
    model = StaffAttendance
    template_name = 'staff/attendance_detail.html'
    context_object_name = 'attendance'

# ========== IMPORT/EXPORT ==========

def export_staff_csv(request):
    """Export staff to CSV"""
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="staff_export.csv"'
    
    writer = csv.writer(response)
    writer.writerow(['Employee ID', 'Full Name', 'Role', 'Department', 'Phone', 'Email', 'Status', 'Hire Date'])
    
    for staff in Staff.objects.select_related('user').all():
        writer.writerow([
            staff.employee_id,
            staff.user.get_full_name(),
            staff.get_role_display(),
            staff.get_department_display(),
            staff.phone_number,
            staff.user.email,
            'Active' if staff.is_active else 'Inactive',
            staff.hire_date
        ])
    
    return response

def staff_import(request):
    """Import staff from CSV"""
    if request.method == 'POST' and request.FILES.get('file'):
        csv_file = request.FILES['file']

        if not csv_file.name.endswith('.csv'):
            messages.error(request, 'Please upload a CSV file')
            return redirect('staff:staff_import')

        # Known honorifics that must never end up in first_name
        HONORIFICS = {'mr', 'mr.', 'mrs', 'mrs.', 'ms', 'ms.', 'mme', 'mme.',
                      'dr', 'dr.', 'prof', 'prof.', 'rev', 'sis'}

        try:
            decoded_file = csv_file.read().decode('utf-8-sig')
            io_string = io.StringIO(decoded_file)
            reader = csv.DictReader(io_string)

            imported = 0
            errors = []
            school = School.objects.first()

            if not school:
                messages.error(request, 'No school found. Please create a school first.')
                return redirect('staff:staff_list')

            for row_num, row in enumerate(reader, start=2):
                try:
                    title      = row.get('Title', '').strip()
                    first_name = row.get('First Name', '').strip()
                    last_name  = row.get('Last Name', '').strip()

                    # Guard: if title column was left empty but someone put
                    # an honorific as the first name, detect and move it
                    if first_name.lower() in HONORIFICS and not title:
                        title = first_name
                        first_name = ''

                    if not first_name or not last_name:
                        errors.append(f"Row {row_num}: Missing first or last name")
                        continue

                    # Username: firstname.lastname (no title, no spaces)
                    username = f"{first_name.lower()}.{last_name.lower()}".replace(' ', '_')

                    # Make username unique if collision
                    base_username = username
                    counter = 1
                    while User.objects.filter(username=username).exists():
                        username = f"{base_username}{counter}"
                        counter += 1

                    user, user_created = User.objects.get_or_create(
                        username=username,
                        defaults={
                            'first_name': first_name,
                            'last_name':  last_name,
                            'email': row.get('Email', f"{username}@raphabethel.org"),
                            'is_staff': True,
                        }
                    )

                    staff, staff_created = Staff.objects.get_or_create(
                        user=user,
                        defaults={
                            'title':       title,
                            'role':        row.get('Role', 'teacher').lower(),
                            'department':  row.get('Department', 'english').lower(),
                            'phone_number': row.get('Phone', '').strip(),
                            'school':      school,
                            'hire_date':   row.get('Hire Date') or None,
                            'is_active':   True,
                        }
                    )

                    if staff_created:
                        imported += 1

                except Exception as e:
                    errors.append(f"Row {row_num}: {str(e)}")

            if errors:
                messages.warning(request, f"Imported {imported} staff with {len(errors)} errors")
            else:
                messages.success(request, f"Successfully imported {imported} staff members!")

        except Exception as e:
            messages.error(request, f"Error processing file: {str(e)}")

        return redirect('staff:staff_list')

    return render(request, 'staff/import.html')

def download_sample_csv(request):
    """Download sample CSV template — Title is a separate column"""
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="staff_sample.csv"'

    writer = csv.writer(response)
    # Title is now its own column — First Name must not contain the honorific
    writer.writerow(['Title', 'First Name', 'Last Name', 'Role', 'Department', 'Phone', 'Email', 'Hire Date'])
    writer.writerow(['Mme',  'Nchotu',     'Manka',     'proprietor',  'admin',   '651437143', 'proprietor@raphabethel.org',  '2025-01-01'])
    writer.writerow(['Mr',   'Ferdinand',  'Sunyin',    'head_master', 'english', '676662567', 'headmaster@raphabethel.org',  '2025-01-01'])
    writer.writerow(['Mme',  'Annie',      'Shey',      'class_teacher','english','670177979', 'annie.shey@raphabethel.org',  '2025-01-01'])
    writer.writerow(['Mr',   'Landry',     'Chesi',     'bursar',      'finance', '651620915', 'bursar@raphabethel.org',      '2025-01-01'])

    
    return response

def import_sample_data(request):
    """Import sample staff data"""
    school = School.objects.first()
    if not school:
        messages.error(request, 'Please create a school first')
        return redirect('staff:staff_list')
    
    sample_data = [
        {'title': 'Mme', 'first': 'Nchotu',    'last': 'Manka',   'role': 'proprietor',   'dept': 'admin',   'phone': '651437143'},
        {'title': 'Mr',  'first': 'Ferdinand',  'last': 'Sunyin',  'role': 'head_master',  'dept': 'english', 'phone': '676662567'},
        {'title': 'Mme', 'first': 'Landry',     'last': 'Chesi',   'role': 'bursar',       'dept': 'finance', 'phone': '651620915'},
    ]

    imported = 0
    for data in sample_data:
        username = f"{data['first'].lower()}.{data['last'].lower()}".replace(' ', '_')
        
        user, _ = User.objects.get_or_create(
            username=username,
            defaults={
                'first_name': data['first'],
                'last_name':  data['last'],
                'email': f"{username}@raphabethel.org",
                'is_staff': True,
            }
        )

        staff, created = Staff.objects.get_or_create(
            user=user,
            defaults={
                'title':       data.get('title', ''),
                'role':        data['role'],
                'department':  data['dept'],
                'phone_number': data['phone'],
                'school':      school,
                'is_active':   True,
            }
        )
        
        if created:
            imported += 1
    
    messages.success(request, f"Imported {imported} sample staff members")
    return redirect('staff:staff_list')

def import_staff_excel(request):
    """Redirect to Excel import"""
    messages.info(request, 'Excel import feature coming soon. Please use CSV for now.')
    return redirect('staff:staff_import')

# Add this custom login view at the top of your file
class CustomStaffLoginView(LoginView):
    """Custom login view that redirects based on user role"""
    template_name = 'staff/login.html'  # You'll need to create this
    
    def get_success_url(self):
        user = self.request.user
        
        # Superusers go to admin
        if user.is_superuser:
            return reverse_lazy('admin:index')
        
        # Check if user has staff profile
        if hasattr(user, 'staff_profile'):
            role = user.staff_profile.role

            TEACHER_ROLES = {'teacher', 'class_teacher', 'subject_teacher', 'assistant_teacher'}
            SUPPORT_ROLES = {'driver', 'cleaner', 'canteen', 'security', 'support', 'other'}
            MANAGEMENT_ROLES = {'proprietor', 'head_master', 'head_mistress', 'admin'}

            if role in TEACHER_ROLES:
                return reverse_lazy('staff:teacher_dashboard')
            elif role == 'bursar':
                return reverse_lazy('finance:bursar_dashboard')
            elif role in MANAGEMENT_ROLES:
                return reverse_lazy('staff:staff_dashboard')
            elif role in SUPPORT_ROLES:
                return reverse_lazy('staff:teacher_dashboard')  # support lands on teacher_dashboard too
            else:
                return reverse_lazy('staff:staff_dashboard')

        # Default fallback
        return reverse_lazy('dashboard')


# ========== API ENDPOINTS ==========

def get_staff_stats(request):
    """API endpoint for staff statistics"""
    stats = {
        'total': Staff.objects.count(),
        'active': Staff.objects.filter(is_active=True).count(),
        'by_role': list(Staff.objects.values('role').annotate(count=Count('id'))),
        'by_department': list(Staff.objects.values('department').annotate(count=Count('id'))),
    }
    return JsonResponse(stats)