<?php

namespace App\Http\Controllers\Teacher;

use App\Http\Controllers\Concerns\RestrictsTeacherLessons;
use App\Http\Controllers\Controller;
use App\Models\ExamSession;
use App\Models\Grade;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    use RestrictsTeacherLessons;

    public function __invoke(Request $request)
    {
        $lessonIds = $this->teacherLessonIds();

        $lessons = auth()->user()->lessons()
            ->withCount('questions')
            ->orderBy('title')
            ->get();

        $latestExams = $this->teacherExams()
            ->with('lesson', 'classroom')
            ->latest()
            ->limit(5)
            ->get();

        $activeSessions = ExamSession::with('exam.lesson', 'exam.classroom')
            ->whereHas('exam', fn ($query) => $query->whereIn('lesson_id', $lessonIds))
            ->latest('start_time')
            ->limit(5)
            ->get();

        $recentGrades = Grade::with('exam.lesson', 'student')
            ->whereHas('exam', fn ($query) => $query->whereIn('lesson_id', $lessonIds))
            ->latest()
            ->limit(5)
            ->get();

        return inertia('Teacher/Dashboard/Index', [
            'lessonCount' => count($lessonIds),
            'questionCount' => $lessons->sum('questions_count'),
            'examCount' => $this->teacherExams()->count(),
            'sessionCount' => ExamSession::whereHas('exam', fn ($query) => $query->whereIn('lesson_id', $lessonIds))->count(),
            'lessons' => $lessons,
            'latestExams' => $latestExams,
            'activeSessions' => $activeSessions,
            'recentGrades' => $recentGrades,
        ]);
    }
}
