<?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 PerformanceSummaryController extends Controller
{
    // public function index()
    // {
    //     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();

    //         if (!$studentRegister) {
    //             // If student is not registered, return empty data
    //             return response()->json([
    //                 'data' => ['stats' => $data],
    //                 'response_status' => 200,
    //             ], 200);
    //         }

    //         // Check if student class exists
    //         $studentClass = StudentClass::where('student_register_id', $studentRegister->id)->first();

    //         if ($studentClass) {
    //             $student_quiz = StudentQuiz::where('student_id', $studentRegister->id)
    //                 ->with([
    //                     'quiz' => function ($query) {
    //                         $query->with([
    //                             'subject' => function ($query) {
    //                                 $query->select('id', 'subject_name');
    //                             },
    //                             'topics.topic' => function ($query) {
    //                                 $query->select('id', 'topic_name');
    //                             }
    //                         ])->select('id', 'quiz_name', 'subject_id');
    //                     }
    //                 ])
    //                 ->get();

    //             // Map data to desired structure
    //             $student_quiz = $student_quiz->map(function ($item) {
    //                 return [
    //                     'student_quiz_id' => $item->id,
    //                     'quiz_id' => $item->quiz->id,
    //                     'score' => $item->score,
    //                     'total_score' => "100",
    //                     'start_time' => $item->start_time,
    //                     'end_time' => $item->end_time,
    //                     'outcome' => $item->outcome,
    //                     'quiz_name' => $item->quiz->quiz_name,
    //                     'subject' => [
    //                         'id' => $item->quiz->subject->id,
    //                         'subject_name' => $item->quiz->subject->subject_name,
    //                     ],
    //                     'topics' => $item->quiz->topics->map(function ($topic) {
    //                         return [
    //                             'id' => $topic->topic->id,
    //                             'topic_name' => $topic->topic->topic_name,
    //                         ];
    //                     })->toArray(),
    //                 ];
    //             });

    //             return response()->json([
    //                 'data' => ['student_quiz' => $student_quiz],
    //                 'response_status' => 200,
    //             ], 200);
    //         } else {
    //             // No class or section found for the student
    //             return response()->json([
    //                 'validation_errors' => ['error' => ['No class or section found for this student.']],
    //                 '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 index()
    {
    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();

        if (!$studentRegister) {
            // If student is not registered, return empty data
            return response()->json([
                'data' => ['stats' => $data],
                'response_status' => 200,
            ], 200);
        }

        // Check if student class exists
        $studentClass = StudentClass::where('student_register_id', $studentRegister->id)->first();

        if ($studentClass) {
            // Fetch all quizzes for the student's class and section
            $quizzes = Quiz::where('class_id', $studentClass->class_id)
                ->where('section', $studentClass->section) // If section exists
                ->get();

            // Fetch student quiz attempts (those that have been attempted)
            $studentQuizzes = StudentQuiz::where('student_id', $studentRegister->id)->latest()->get();

            // Prepare the array to hold all quizzes (both attempted and non-attempted)
            $quizData = [];

            // Map the student's attempted quizzes (those with scores)
            $studentQuizData = $studentQuizzes->map(function ($item) {
                return [
                    'student_quiz_id' => $item->id,
                    'quiz_id' => $item->quiz->id,
                    'score' => $item->score,
                    'total_score' => 100,  // Assuming the total score is 100
                    'obtain_marks' => $item->obtain_marks,  // Assuming the total score is 100
                    'total_marks' => $item->total_marks,  // Assuming the total score is 100
                    'start_time' => $item->start_time,
                    'end_time' => $item->end_time,
                    'outcome' => $item->outcome,
                    'quiz_name' => $item->quiz->quiz_name,
                    'subject' => [
                        'id' => $item->quiz->subject->id,
                        'subject_name' => $item->quiz->subject->subject_name,
                    ],
                    'topics' => $item->quiz->topics->map(function ($topic) {
                        return [
                            'id' => $topic->topic->id,
                            'topic_name' => $topic->topic->topic_name,
                        ];
                    })->toArray(),
                ];
            });

            // Add attempted quizzes to the quizData array
            $quizData = $studentQuizData->toArray();

            // Add quizzes that have not been attempted
            // These are quizzes in the Quiz table that do not have corresponding entries in StudentQuiz
            $notAttemptedQuizzes = $quizzes->filter(function ($quiz) use ($studentQuizzes) {
                return !$studentQuizzes->contains('quiz_id', $quiz->id);
            });

            $notAttemptedQuizData = $notAttemptedQuizzes->map(function ($quiz) {
                return [
                    'student_quiz_id' => null,  // No attempt, so no student_quiz_id
                    'quiz_id' => $quiz->id,
                    'score' => 0,  // Not attempted, so score is 0
                    'total_score' => 100,  // Assuming the total score is 100
                    'start_time' => null,  // No start time
                    'end_time' => null,    // No end time
                    'outcome' => 'Not Attempted',  // Mark as not attempted
                    'quiz_name' => $quiz->quiz_name,
                    'subject' => [
                        'id' => $quiz->subject->id,
                        'subject_name' => $quiz->subject->subject_name,
                    ],
                    'topics' => $quiz->topics->map(function ($topic) {
                        return [
                            'id' => $topic->topic->id,
                            'topic_name' => $topic->topic->topic_name,
                        ];
                    })->toArray(),
                ];
            });

            // Merge the attempted quizzes and not attempted quizzes into a single array
            $quizData = array_merge($quizData, $notAttemptedQuizData->toArray());

            // Count total quizzes, attempted quizzes, and not attempted quizzes
            $totalQuizzes = $quizzes->count();
            $attemptedQuizzesCount = $studentQuizzes->count();
            $notAttemptedQuizzesCount = $totalQuizzes - $attemptedQuizzesCount;

            return response()->json([
                'data' => [
                    'student_quiz' => $quizData, // All quizzes (attempted + not attempted)
                    'quiz_stats' => [
                        'total_quizzes' => $totalQuizzes,
                        'attempted_quizzes' => $attemptedQuizzesCount,
                        'not_attempted_quizzes' => $notAttemptedQuizzesCount,
                    ],
                ],
                'response_status' => 200,
            ], 200);
        } else {
            // No class or section found for the student
            return response()->json([
                // 'validation_errors' => ['error' => ['No class or section found for this student.']],
                'response_status' => 400,
            ], 200);
        }
    } catch (Exception $exception) {
        // Handle any errors that occur
        return response()->json([
            'validation_errors' => ['error' => [$exception->getMessage()]],
            'response_status' => 400,
        ], 200);
    }
}
}
