<?php

namespace App\Http\Controllers\Api\Student;

use App\Http\Controllers\Controller;
use App\Models\Announcement;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Models\Quiz;
use App\Models\QuizStudent;
use App\Models\QuizTopicQuestion;
use App\Models\StudentClass;
use App\Models\StudentQuiz;
use App\Models\StudentRegister;
use App\Models\StudyGuide;
use App\Models\TeacherClass;
use Carbon\Carbon;
use Exception;

class DashboardController extends Controller
{
    // public function statsFetch()
    // {

    //     try {
    //         $data = [];

    //         // Get the authenticated student's ID
    //         $studentId = Auth::guard('sanctum')->user()->id;


    //         // Fetch student registration details
    //         $studentRegister = StudentRegister::where('student_id', $studentId)->first();
    //         // Check if the student not register exists
    //         if (!$studentRegister) {
    //             // If student is not registered, return empty data
    //             return response()->json([
    //                 'data' => ['stats' => $data],
    //                 'response_status' => 200,
    //             ], 200);
    //         }

    //         // Check if the student register exists
    //         if ($studentRegister) {

    //             $studentClass = StudentClass::where('student_register_id', $studentRegister->id)->first();

    //             if ($studentClass) {
    //                 $section = $studentClass->section;
    //                 $student_register_id = $studentRegister->id;
    //                 $class = $studentClass->class_id;

    //                 // // Fetch top 3 scorers in the class where the teacher_class matches the class_id
    //                 // $topScorers = StudentQuiz::selectRaw('student_id, teacher_class_id, AVG(score) as avg_score')
    //                 //     ->whereHas('teacherClass', function ($query) use ($class) {
    //                 //         $query->where('class_id', $class);
    //                 //     })
    //                 //     ->groupBy('student_id', 'teacher_class_id')
    //                 //     ->orderByDesc('avg_score')
    //                 //     ->with([
    //                 //         'student.student' => function ($query) {
    //                 //             $query->select('id', 'first_name', 'last_name', 'image');
    //                 //         },
    //                 //         'teacherClass.classRelation' => function ($query) {
    //                 //             $query->select('id', 'class_name');
    //                 //         }
    //                 //     ])
    //                 //     ->limit(3)
    //                 //     ->get()
    //                 //     ->map(function ($quizScore, $index) {
    //                 //         return [
    //                 //             'student_id' => $quizScore->student_id,
    //                 //             'first_name' => $quizScore->student->first_name ?? null,
    //                 //             'last_name' => $quizScore->student->last_name ?? null,
    //                 //             'score' => round($quizScore->avg_score, 2),
    //                 //             'position' => $index + 1,
    //                 //             'student_image' => $quizScore->student->student->image ?? null,
    //                 //             'class_name' => $quizScore->teacherClass->classRelation->class_name ?? null,
    //                 //             'teacher_class_id' => $quizScore->teacher_class_id,
    //                 //         ];
    //                 // });
    //                 // // Add top scorers to response data
    //                 // $data = array_merge($data, ['topScorers' => $topScorers]);

    //                 // Fetch all quizzes the student has taken
    //                 $studentQuizzes = StudentQuiz::where('student_id', $student_register_id)
    //                     ->whereNotNull('score')
    //                     ->with(['teacherClass' => function ($query) {
    //                         $query->select('id', 'subject_id')
    //                             ->with('subject:id,subject_name'); // Fetching subject details
    //                     }])
    //                     ->get();

    //                 // Calculate averages by subject and prepare data
    //                 $subjectAverages = $studentQuizzes->groupBy('teacherClass.subject_id')->map(function ($quizzes, $subjectId) use ($studentRegister, $studentClass) {
    //                     $totalScore = $quizzes->sum('score');
    //                     $quizCount = $quizzes->count();
    //                     $averageScore = $quizCount > 0 ? round($totalScore / $quizCount, 2) : 0;

    //                     $teacherClass = $quizzes->first()->teacherClass;

    //                     return [
    //                         'student_id' => $studentRegister->student_id,
    //                         'first_name' => $studentRegister->student->first_name,
    //                         'last_name' => $studentRegister->student->last_name,
    //                         'score' => $averageScore,
    //                         'student_image' => $studentRegister->student->image ?? null,
    //                         'class_name' => $studentClass->classRelation->class_name,
    //                         'subject_name' => $teacherClass->subject->subject_name ?? 'N/A',
    //                         'teacher_class_id' => $teacherClass->id,
    //                         'section' => $studentClass->section,
    //                     ];
    //                 });

    //                 // Sort subjects by average score in descending order
    //                 $sortedSubjects = $subjectAverages->sortByDesc('score')->values();

    //                 // Add sorted subjects to data
    //                 $data['topScorers'] = $sortedSubjects;

    //                 // Announcements
    //                 $announcements = Announcement::select('id', 'title', 'description', 'subject_id')->where('end_date', '>=', Carbon::now())->where('class_id', $class)->where('section', $section)->with('subject:id,subject_name')->limit(4)->latest()->get();
    //                 $data = array_merge($data, ['announcements' => $announcements]);

    //                 // Enrolled Classes
    //                 $enrolledClasses = StudentClass::select('id', 'section', 'subject_id', 'teacher_id', 'class_id')->where('student_id', $studentId)->with('classRelation:id,class_name', 'subject:id,subject_name', 'teacher:id,first_name,last_name')->limit(6)->latest()->get();
    //                 $data = array_merge($data, ['enrolledClasses' => $enrolledClasses]);

    //                 // Study Guides
    //                 $studyGuides = StudyGuide::select('id', 'study_guide_name', 'file')->where('class_id', $class)->where('section', $section)->limit(3)->latest()->get();
    //                 $data = array_merge($data, ['studyGuides' => $studyGuides]);

    //                 // Quizzes
    //                 $student_register_id = $studentClass->student_register_id;

    //                 // // Fetch quiz IDs for the student
    //                 $quizStudents = QuizStudent::where('student_register_id', $student_register_id)->get();

    //                 if ($quizStudents->isEmpty()) {
    //                     // If no quizzes found for the student
    //                     return response()->json([
    //                         // 'data' => ['quizzes' => [], 'message' => 'No quizzes found for this student.'],
    //                         'response_status' => 200,
    //                     ], 200);
    //                 }

    //                 // Collect quiz IDs that are assigned to the student
    //                 $assignedQuizIds = $quizStudents->pluck('quiz_id')->toArray();

    //                 // Fetch attempted quizzes by the student
    //                 $attemptedQuizIds = StudentQuiz::where('student_id', $student_register_id)
    //                     ->whereNotNull('score') // Only fetch quizzes with a score (attempted)
    //                     ->pluck('quiz_id')->toArray();

    //                 // Fetch quizzes that have been assigned but not attempted
    //                 $quizzes = Quiz::whereIn('id', $assignedQuizIds) // Only assigned quizzes
    //                     ->whereNotIn('id', $attemptedQuizIds)->where('end_date', '>', Carbon::now())->where('class_id', $class)->where('section', $section)->with([
    //                         'teacher',
    //                         'classRelation',
    //                         'subject',
    //                         'links',
    //                         'students' => function ($query) {
    //                             $query->with([
    //                                 'student:id,first_name,last_name,upn,email,student_id'
    //                             ]);
    //                         },
    //                         'units' => function ($query) {
    //                             $query->with([
    //                                 'unit:id,unit_name',
    //                                 'topics' => function ($query) {
    //                                     $query->with([
    //                                         'topic:id,topic_name',
    //                                         'questions' => function ($query) {
    //                                             $query->with([
    //                                                 'question:id,question,type_id,difficulty_level_id',
    //                                             ]);
    //                                         }
    //                                     ]);
    //                                 }
    //                             ]);
    //                         }
    //                     ])->limit(3)->latest()->get();
    //                 $data = array_merge($data, ['quizzes' => $quizzes]);


    //                 $student_quiz = StudentQuiz::where('student_id', $student_register_id)
    //                     ->whereNotNull('score')
    //                     ->with(['TeacherClass.subject:id,subject_name', 'quiz:id,quiz_name'])
    //                     ->limit(3)->latest()->get();

    //                 $data = array_merge($data, ['student_quiz' => $student_quiz]);


    //                 return response()->json([
    //                     'data' => ['stats' => $data],
    //                     'response_status' => 200,
    //                 ], 200);
    //             } else {
    //                 // No section found for the student
    //                 return response()->json([
    //                     'validation_errors' => ['error' => ['No class or section found for this student.']],
    //                     'response_status' => 400,
    //                 ], 200);
    //             }
    //         } else {
    //             // No student register record found
    //             // return response()->json([
    //             //     'validation_errors' => ['error' => ['Student not Registered!']],
    //             //     'response_status' => 400,
    //             // ], 200);
    //         }
    //     } catch (Exception $exception) {
    //         // Handle any errors that occur
    //         return response()->json([
    //             'validation_errors' => ['error' => [$exception->getMessage()]],
    //             'response_status' => 400,
    //         ], 200);
    //     }
    // }
    
    public function statsFetch()
    {

        try {
            $data = [];

            // Get the authenticated student's ID
            $studentId = Auth::guard('sanctum')->user()->id;


            // Fetch student registration details
            $studentRegister = StudentRegister::where('student_id', $studentId)->first();
            // Check if the student not register exists
            if (!$studentRegister) {
                // If student is not registered, return empty data
                return response()->json([
                    'data' => ['stats' => $data],
                    'response_status' => 200,
                ], 200);
            }

            // Check if the student register exists
            if ($studentRegister) {

                $studentClass = StudentClass::where('student_register_id', $studentRegister->id)->first();

                if ($studentClass) {
                    $section = $studentClass->section;
                    $student_register_id = $studentRegister->id;
                    $class = $studentClass->class_id;


                    // Announcements
                    $announcements = Announcement::select('id', 'title', 'description', 'subject_id')->where('end_date', '>=', Carbon::now()->toDateString())->where('class_id', $class)->where('section', $section)->with('subject:id,subject_name')->limit(4)->latest()->get();
                    $data = array_merge($data, ['announcements' => $announcements]);

                    // Enrolled Classes
                    $enrolledClasses = StudentClass::select('id', 'section', 'subject_id', 'teacher_id', 'class_id')->where('student_id', $studentId)->with('classRelation:id,class_name', 'subject:id,subject_name', 'teacher:id,first_name,last_name')->limit(6)->latest()->get();
                    $data = array_merge($data, ['enrolledClasses' => $enrolledClasses]);

                    // Study Guides
                    $studyGuides = StudyGuide::select('id', 'study_guide_name', 'file')->where('class_id', $class)->where('section', $section)->limit(3)->latest()->get();
                    $data = array_merge($data, ['studyGuides' => $studyGuides]);
                    
                    // Fetch all quizzes the student has taken
                    $studentQuizzes = StudentQuiz::where('student_id', $student_register_id)
                        ->whereNotNull('score')
                        ->with(['teacherClass' => function ($query) {
                            $query->select('id', 'subject_id')
                                ->with('subject:id,subject_name'); // Fetching subject details
                        }])
                        ->get();

                    // Calculate averages by subject and prepare data
                    $subjectAverages = $studentQuizzes->groupBy('teacherClass.subject_id')->map(function ($quizzes, $subjectId) use ($studentRegister, $studentClass) {
                        $totalScore = $quizzes->sum('score');
                        $quizCount = $quizzes->count();
                        $averageScore = $quizCount > 0 ? round($totalScore / $quizCount, 2) : 0;

                        $teacherClass = $quizzes->first()->teacherClass;

                        return [
                            'student_id' => $studentRegister->student_id,
                            'first_name' => $studentRegister->student->first_name,
                            'last_name' => $studentRegister->student->last_name,
                            'score' => $averageScore,
                            'student_image' => $studentRegister->student->image ?? null,
                            'class_name' => $studentClass->classRelation->class_name,
                            'subject_name' => $teacherClass->subject->subject_name ?? 'N/A',
                            'teacher_class_id' => $teacherClass->id,
                        ];
                    });

                    // Sort subjects by average score in descending order
                    $sortedSubjects = $subjectAverages->sortByDesc('score')->values();

                    // Add sorted subjects to data
                    $data['topScorers'] = $sortedSubjects;


                    // Quizzes
                    $student_register_id = $studentClass->student_register_id;

                    // // Fetch quiz IDs for the student
                    $quizStudents = QuizStudent::where('student_register_id', $student_register_id)->get();


                    // Collect quiz IDs that are assigned to the student
                    $assignedQuizIds = $quizStudents->pluck('quiz_id')->toArray();

                    // Fetch attempted quizzes by the student
                    $attemptedQuizIds = StudentQuiz::where('student_id', $student_register_id)
                        ->whereNotNull('score') // Only fetch quizzes with a score (attempted)
                        ->pluck('quiz_id')->toArray();

                    // Fetch quizzes that have been assigned but not attempted
                    $quizzes = Quiz::whereIn('id', $assignedQuizIds) // Only assigned quizzes
                        ->whereNotIn('id', $attemptedQuizIds)->where('end_date', '>=', Carbon::now()->toDateString())->where('class_id', $class)->where('section', $section)->with([
                            'teacher',
                            'classRelation',
                            'subject',
                            'links',
                            'students' => function ($query) {
                                $query->with([
                                    'student:id,first_name,last_name,upn,email,student_id'
                                ]);
                            },
                            'units' => function ($query) {
                                $query->with([
                                    'unit:id,unit_name',
                                    'topics' => function ($query) {
                                        $query->with([
                                            'topic:id,topic_name',
                                            'questions' => function ($query) {
                                                $query->with([
                                                    'question:id,question,type_id,difficulty_level_id',
                                                ]);
                                            }
                                        ]);
                                    }
                                ]);
                            }
                        ])->limit(3)->latest()->get();
                    $data = array_merge($data, ['quizzes' => $quizzes]);


                    $student_quiz = StudentQuiz::where('student_id', $student_register_id)
                        ->whereNotNull('score')
                        ->with(['TeacherClass.subject:id,subject_name', 'quiz:id,quiz_name'])
                        ->limit(3)->latest()->get();

                    $data = array_merge($data, ['student_quiz' => $student_quiz]);


                    return response()->json([
                        'data' => ['stats' => $data],
                        'response_status' => 200,
                    ], 200);
                } else {
                    // No section found for the student
                    return response()->json([
                        // 'validation_errors' => ['error' => ['No class or section found for this student.']],
                        'response_status' => 400,
                    ], 200);
                }
            } else {
                // No student register record found
                // return response()->json([
                //     'validation_errors' => ['error' => ['Student not Registered!']],
                //     'response_status' => 400,
                // ], 200);
            }
        } catch (Exception $exception) {
            // Handle any errors that occur
            return response()->json([
                'validation_errors' => ['error' => [$exception->getMessage()]],
                'response_status' => 400,
            ], 200);
        }
    }
}
