<?php

namespace App\Http\Controllers\Teacher;

use App\Http\Controllers\Controller;
use App\Models\Grade;
use App\Models\SchoolClass;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AnalyticsController extends Controller
{
    public function index(Request $request)
    {
        $teacher = Auth::user();
        $myClasses = $teacher->taughtClasses()->get();
        
        $classId = $request->get('class_id', $myClasses->first()->id ?? null);
        
        $stats = [];
        if ($classId) {
            // Overall Subject Averages
            $subjectAverages = Grade::where('school_class_id', $classId)
                ->where('teacher_id', $teacher->id)
                ->join('subjects', 'grades.subject_id', '=', 'subjects.id')
                ->select('subjects.name', DB::raw('AVG(score) as avg_score'))
                ->groupBy('subjects.id', 'subjects.name')
                ->get();

            // Grade Distributions (E.E, M.E, A.E, B.E)
            // Based on CBC grading rules provided by the user:
            // E.E >= 80
            // M.E >= 60 AND < 80
            // A.E >= 40 AND < 60
            // B.E < 40
            
            $grades = Grade::where('school_class_id', $classId)
                ->where('teacher_id', $teacher->id)
                ->get();
                
            $distribution = [
                'E.E (Exceeds Expectation)' => 0,
                'M.E (Meets Expectation)' => 0,
                'A.E (Approaches Expectation)' => 0,
                'B.E (Below Expectation)' => 0,
            ];
            
            foreach ($grades as $grade) {
                if ($grade->score >= 80) $distribution['E.E (Exceeds Expectation)']++;
                elseif ($grade->score >= 60) $distribution['M.E (Meets Expectation)']++;
                elseif ($grade->score >= 40) $distribution['A.E (Approaches Expectation)']++;
                else $distribution['B.E (Below Expectation)']++;
            }
            
            $stats = [
                'subjectAverages' => $subjectAverages,
                'distribution' => $distribution,
                'totalGrades' => $grades->count(),
            ];
        }

        return view('teacher.analytics.index', compact('myClasses', 'classId', 'stats'));
    }
}
