<?php

namespace App\Http\Controllers\Admin;

use App\Models\Exam;
use App\Models\Grade;
use App\Models\Student;
use App\Models\Classroom;
use App\Models\ExamSession;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class DashboardController extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {
        //count students
        $students = Student::count();

        //count exams
        $exams = Exam::count();

        //count exam sessions
        $exam_sessions = ExamSession::count();

        //count classrooms
        $classrooms = Classroom::count();

        // Aggregate exam statistics: top 10 exams by student participation
        $exam_stats = DB::table('grades')
            ->join('exams', 'grades.exam_id', '=', 'exams.id')
            ->select('exams.title', DB::raw('COUNT(grades.student_id) as total_students'))
            ->groupBy('exams.id', 'exams.title')
            ->orderBy('total_students', 'desc')
            ->limit(10)
            ->get();

        // Aggregate grade distribution: percentage of students scoring 0-20, 21-40, 41-60, 61-80, 81-100
        $grade_distribution = [
            '0-20' => Grade::whereBetween('grade', [0, 20])->count(),
            '21-40' => Grade::whereBetween('grade', [21, 40])->count(),
            '41-60' => Grade::whereBetween('grade', [41, 60])->count(),
            '61-80' => Grade::whereBetween('grade', [61, 80])->count(),
            '81-100' => Grade::whereBetween('grade', [81, 100])->count(),
        ];

        return inertia('Admin/Dashboard/Index', [
            'students' => $students,
            'exams' => $exams,
            'exam_sessions' => $exam_sessions,
            'classrooms' => $classrooms,
            'exam_stats' => $exam_stats,
            'grade_distribution' => $grade_distribution,
        ]);
    }
}