from django.shortcuts import render, redirect, get_object_or_404
from django.utils import translation
from django.conf import settings
from django.http import JsonResponse
from django.contrib.admin.views.decorators import staff_member_required
from .models import EducationalLevel, Subject, Teacher

def index(request):
    # Fetch levels with their related subjects using prefetch_related for efficiency
    levels = EducationalLevel.objects.prefetch_related('subjects').all()
    
    context = {
        'levels': levels,
    }
    return render(request, 'core/index.html', context)

def set_language(request, lang_code):
    next_url = request.GET.get('next', '/')
    response = redirect(next_url)
    
    if lang_code in [lang[0] for lang in settings.LANGUAGES]:
        translation.activate(lang_code)
        if hasattr(request, 'session'):
            request.session['_language'] = lang_code
        response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
    
    return response

def subject_detail(request, pk):
    subject = get_object_or_404(Subject, pk=pk)
    return render(request, 'core/subject_detail.html', {'subject': subject})

@staff_member_required
def get_subjects_by_level(request):
    level_id = request.GET.get('level_id')
    if not level_id:
        return JsonResponse([], safe=False)
    subjects = Subject.objects.filter(level_id=level_id).values('id', 'name_en', 'name_ar')
    return JsonResponse(list(subjects), safe=False)