<?php

namespace App\Http\Controllers\Api\V1\Student;

use App\Http\Controllers\Api\V1\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use App\Models\Quiz;
use App\Models\QuizAttempt;
use App\Models\QuizQuestion;
use App\Models\QuizAnswer;
use App\Models\QuizAttemptAnswer;
use App\Models\QuestionBookmark;

class QuizController extends BaseController
{
    /**
     * Get list of quizzes.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        try {
            $user = Auth::user();
            
            $query = Quiz::with(['course', 'book', 'creator']);
            
            // Show active quizzes, or all if none are active
            $hasActiveQuizzes = Quiz::where('is_active', true)->exists();
            if ($hasActiveQuizzes) {
                $query->where('is_active', true);
            }
            
            // Filter by level
            if ($request->has('level') && $request->level) {
                $query->where('level', $request->level);
            }
            
            
            $quizzes = $query->orderBy('level')->orderBy('title')
                ->paginate($request->get('per_page', 20));
            
            $data = $quizzes->map(function($quiz) use ($user) {
                // Get user's best score
                $bestAttempt = QuizAttempt::where('user_id', $user->id)
                    ->where('quiz_id', $quiz->id)
                    ->where('mode', 'regular')
                    ->whereNotNull('completed_at')
                    ->orderBy('score', 'desc')
                    ->first();
                
                // Get total attempts
                $totalAttempts = QuizAttempt::where('user_id', $user->id)
                    ->where('quiz_id', $quiz->id)
                    ->where('mode', 'regular')
                    ->count();
                
                return [
                    'id' => $quiz->id,
                    'title' => $quiz->title,
                    'description' => $quiz->description,
                    'level' => $quiz->level,
                    'total_questions' => $quiz->total_questions,
                    'time_limit_minutes' => $quiz->time_limit_minutes,
                    'is_active' => $quiz->is_active,
                    'has_attempted' => $bestAttempt !== null,
                    'best_score' => $bestAttempt ? $bestAttempt->score : null,
                    'total_attempts' => $totalAttempts,
                ];
            });
            
            return $this->paginated($data, $quizzes);
        } catch (\Exception $e) {
            Log::error('Student Quizzes API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching quizzes.', null, 500);
        }
    }
    
    /**
     * Get quiz details.
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        try {
            $user = Auth::user();
            
            $quiz = Quiz::with(['course', 'book', 'creator'])->findOrFail($id);
            
            // Check for incomplete attempt
            $incompleteAttempt = QuizAttempt::where('user_id', $user->id)
                ->where('quiz_id', $quiz->id)
                ->whereNull('completed_at')
                ->first();
            
            // Get best score
            $bestAttempt = QuizAttempt::where('user_id', $user->id)
                ->where('quiz_id', $quiz->id)
                ->where('mode', 'regular')
                ->whereNotNull('completed_at')
                ->orderBy('score', 'desc')
                ->first();
            
            return $this->success([
                'id' => $quiz->id,
                'title' => $quiz->title,
                'description' => $quiz->description,
                'level' => $quiz->level,
                'total_questions' => $quiz->total_questions,
                'time_limit_minutes' => $quiz->time_limit_minutes,
                'is_active' => $quiz->is_active,
                'has_attempted' => $bestAttempt !== null,
                'best_score' => $bestAttempt ? $bestAttempt->score : null,
                'total_attempts' => QuizAttempt::where('user_id', $user->id)
                    ->where('quiz_id', $quiz->id)
                    ->where('mode', 'regular')
                    ->count(),
                'incomplete_attempt' => $incompleteAttempt ? [
                    'id' => $incompleteAttempt->id,
                    'mode' => $incompleteAttempt->mode,
                    'questions_answered' => count($incompleteAttempt->getAnsweredQuestionIds()),
                    'started_at' => $incompleteAttempt->started_at ?? $incompleteAttempt->created_at,
                ] : null,
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Quiz not found.', null, 404);
        } catch (\Exception $e) {
            Log::error('Student Quiz API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching quiz details.', null, 500);
        }
    }
    
    /**
     * Start quiz attempt.
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function start(Request $request, $id)
    {
        try {
            $user = Auth::user();
            
            $validated = $request->validate([
                'mode' => 'required|in:regular,study',
                'start_over' => 'nullable|boolean',
            ]);
            
            $quiz = Quiz::findOrFail($id);
            
            // Check for existing incomplete attempt
            $existingAttempt = QuizAttempt::where('user_id', $user->id)
                ->where('quiz_id', $quiz->id)
                ->where('mode', $validated['mode'])
                ->whereNull('completed_at')
                ->first();
            
            $currentAttempt = null;
            $questionOrder = [];
            
            if ($existingAttempt && !($validated['start_over'] ?? false)) {
                // Resume existing attempt
                $currentAttempt = $existingAttempt;
                
                // Ensure started_at is set if it's null (for older attempts)
                if (!$currentAttempt->started_at) {
                    $currentAttempt->started_at = $currentAttempt->created_at ?? now();
                    $currentAttempt->save();
                }
                
                $questionOrder = $existingAttempt->question_order ?? [];
                $currentQuestionId = !empty($questionOrder) ? $questionOrder[0] : null;
            } else {
                // Create new attempt
                if ($existingAttempt) {
                    $existingAttempt->delete(); // Delete old attempt if starting over
                }
                
                // Get question IDs in random order
                $questionIds = QuizQuestion::where('quiz_id', $quiz->id)
                    ->pluck('id')
                    ->shuffle()
                    ->toArray();
                
                $currentAttempt = QuizAttempt::create([
                    'user_id' => $user->id,
                    'quiz_id' => $quiz->id,
                    'mode' => $validated['mode'],
                    'question_order' => $questionIds,
                    'score' => 0,
                    'started_at' => now(),
                ]);
                
                $questionOrder = $questionIds;
                $currentQuestionId = !empty($questionIds) ? $questionIds[0] : null;
            }
            
            // Get current question
            if ($currentQuestionId) {
                $question = QuizQuestion::with('answers')->find($currentQuestionId);
                
                if (!$question) {
                    return $this->error('Question not found.', null, 404);
                }
                
                $answeredQuestions = $currentAttempt->attemptAnswers->pluck('question_id')->toArray();
                
                $selectedAnswer = $currentAttempt->attemptAnswers()
                    ->where('question_id', $currentQuestionId)
                    ->first();
                
                return $this->success([
                    'attempt_id' => $currentAttempt->id,
                    'quiz' => [
                        'id' => $quiz->id,
                        'title' => $quiz->title,
                        'total_questions' => $quiz->total_questions,
                        'time_limit_minutes' => $quiz->time_limit_minutes,
                    ],
                    'current_question' => [
                        'question_id' => $question->id,
                        'question_order' => array_search($currentQuestionId, $questionOrder) + 1,
                        'question' => $question->question,
                        'answers' => $question->answers->map(function($answer) {
                            return [
                                'id' => $answer->id,
                                'answer' => $answer->answer_text,
                            ];
                        }),
                        'selected_answer_id' => $selectedAnswer ? $selectedAnswer->answer_id : null,
                        'is_correct' => $selectedAnswer ? ($selectedAnswer->is_correct ?? null) : null,
                    ],
                    'progress' => [
                        'current' => array_search($currentQuestionId, $questionOrder) + 1,
                        'total' => count($questionOrder),
                        'percentage' => round(((array_search($currentQuestionId, $questionOrder) + 1) / count($questionOrder)) * 100, 2),
                    ],
                    'question_order' => $questionOrder,
                ]);
            }
            
            return $this->error('No questions available for this quiz.', null, 404);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->error('Validation failed', $e->errors(), 422);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Quiz not found.', null, 404);
        } catch (\Exception $e) {
            Log::error('Student Quiz Start API error: ' . $e->getMessage());
            return $this->error('An error occurred while starting quiz.', null, 500);
        }
    }
    
    /**
     * Submit answer.
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function submitAnswer(Request $request, $id)
    {
        try {
            $user = Auth::user();
            
            $validated = $request->validate([
                'attempt_id' => 'required|exists:quiz_attempts,id',
                'question_id' => 'required|exists:quiz_questions,id',
                'answer_id' => 'required|exists:quiz_answers,id',
            ]);
            
            // Verify attempt belongs to user
            $attempt = QuizAttempt::where('id', $validated['attempt_id'])
                ->where('user_id', $user->id)
                ->where('quiz_id', $id)
                ->whereNull('completed_at')
                ->firstOrFail();
            
            $question = QuizQuestion::with('answers')->findOrFail($validated['question_id']);
            $selectedAnswer = QuizAnswer::findOrFail($validated['answer_id']);
            
            // Check if answer is correct
            $isCorrect = $selectedAnswer->is_correct ?? false;
            
            // Save or update attempt answer
            QuizAttemptAnswer::updateOrCreate(
                [
                    'attempt_id' => $attempt->id,
                    'question_id' => $question->id,
                ],
                [
                    'answer_id' => $selectedAnswer->id,
                    'is_correct' => $isCorrect,
                ]
            );
            
            // Get next question
            $questionOrder = $attempt->question_order ?? [];
            $currentIndex = array_search($question->id, $questionOrder);
            $nextIndex = $currentIndex + 1;
            $isLastQuestion = $nextIndex >= count($questionOrder);
            
            $nextQuestion = null;
            if (!$isLastQuestion && isset($questionOrder[$nextIndex])) {
                $nextQuestionData = QuizQuestion::with('answers')
                    ->find($questionOrder[$nextIndex]);
                
                $nextSelectedAnswer = $attempt->attemptAnswers()
                    ->where('question_id', $questionOrder[$nextIndex])
                    ->first();
                
                $nextQuestion = [
                    'question_id' => $nextQuestionData->id,
                    'question_order' => $nextIndex + 1,
                    'question' => $nextQuestionData->question,
                    'answers' => $nextQuestionData->answers->map(function($answer) {
                        return [
                            'id' => $answer->id,
                            'answer' => $answer->answer_text,
                        ];
                    }),
                    'selected_answer_id' => $nextSelectedAnswer ? $nextSelectedAnswer->answer_id : null,
                ];
            }
            
            // Get correct answer for feedback
            $correctAnswer = $question->answers->where('is_correct', true)->first();
            
            return $this->success([
                'is_correct' => $isCorrect,
                'correct_answer_id' => $correctAnswer->id ?? null,
                'explanation' => $question->explanation ?? null,
                'next_question' => $nextQuestion,
                'progress' => [
                    'current' => $nextIndex + 1,
                    'total' => count($questionOrder),
                    'percentage' => round((($nextIndex + 1) / count($questionOrder)) * 100, 2),
                ],
                'is_last_question' => $isLastQuestion,
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->error('Validation failed', $e->errors(), 422);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Attempt or question not found.', null, 404);
        } catch (\Exception $e) {
            Log::error('Student Quiz Submit Answer API error: ' . $e->getMessage());
            return $this->error('An error occurred while submitting answer.', null, 500);
        }
    }
    
    /**
     * Complete quiz.
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function complete(Request $request, $id)
    {
        try {
            $user = Auth::user();
            
            $validated = $request->validate([
                'attempt_id' => 'required|exists:quiz_attempts,id',
            ]);
            
            $attempt = QuizAttempt::where('id', $validated['attempt_id'])
                ->where('user_id', $user->id)
                ->where('quiz_id', $id)
                ->whereNull('completed_at')
                ->firstOrFail();
            
            // Calculate score
            $totalQuestions = count($attempt->question_order ?? []);
            $correctAnswers = $attempt->attemptAnswers()->where('is_correct', true)->count();
            $score = $totalQuestions > 0 ? round(($correctAnswers / $totalQuestions) * 100, 2) : 0;
            
            // Update attempt
            $attempt->score = $score;
            $attempt->completed_at = now();
            $attempt->save();
            
            return $this->success([
                'attempt_id' => $attempt->id,
                'score' => $score,
                'total_questions' => $totalQuestions,
                'correct_answers' => $correctAnswers,
                'incorrect_answers' => $totalQuestions - $correctAnswers,
                'percentage' => $score,
                'completed_at' => $attempt->completed_at,
            ], 'Quiz completed successfully');
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->error('Validation failed', $e->errors(), 422);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Attempt not found.', null, 404);
        } catch (\Exception $e) {
            Log::error('Student Quiz Complete API error: ' . $e->getMessage());
            return $this->error('An error occurred while completing quiz.', null, 500);
        }
    }
    
    /**
     * Get quiz result.
     *
     * @param int $id
     * @param int $attemptId
     * @return \Illuminate\Http\JsonResponse
     */
    public function result($id, $attemptId)
    {
        try {
            $user = Auth::user();
            
            $attempt = QuizAttempt::where('id', $attemptId)
                ->where('user_id', $user->id)
                ->where('quiz_id', $id)
                ->whereNotNull('completed_at')
                ->with(['quiz', 'attemptAnswers.question', 'attemptAnswers.answer'])
                ->firstOrFail();
            
            $questions = [];
            foreach ($attempt->question_order ?? [] as $questionId) {
                $question = QuizQuestion::with('answers')->find($questionId);
                if (!$question) continue;
                
                $attemptAnswer = $attempt->attemptAnswers()
                    ->where('question_id', $questionId)
                    ->first();
                
                $correctAnswer = $question->answers->where('is_correct', true)->first();
                
                $questions[] = [
                    'question_id' => $question->id,
                    'question' => $question->question,
                    'selected_answer' => $attemptAnswer ? [
                        'id' => $attemptAnswer->answer->id ?? null,
                        'answer' => $attemptAnswer->answer->answer_text ?? null,
                    ] : null,
                    'correct_answer' => $correctAnswer ? [
                        'id' => $correctAnswer->id,
                        'answer' => $correctAnswer->answer_text,
                    ] : null,
                    'is_correct' => $attemptAnswer ? $attemptAnswer->is_correct : false,
                    'explanation' => $question->explanation ?? null,
                ];
            }
            
            return $this->success([
                'attempt_id' => $attempt->id,
                'quiz' => [
                    'id' => $attempt->quiz->id,
                    'title' => $attempt->quiz->title,
                ],
                'score' => $attempt->score,
                'total_questions' => count($attempt->question_order ?? []),
                'correct_answers' => $attempt->attemptAnswers()->where('is_correct', true)->count(),
                'incorrect_answers' => $attempt->attemptAnswers()->where('is_correct', false)->count(),
                'percentage' => $attempt->score,
                'completed_at' => $attempt->completed_at,
                'mode' => $attempt->mode,
                'questions' => $questions,
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Result not found.', null, 404);
        } catch (\Exception $e) {
            Log::error('Student Quiz Result API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching quiz result.', null, 500);
        }
    }
    
    /**
     * Get quiz history.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function history(Request $request)
    {
        try {
            $user = Auth::user();
            
            $query = QuizAttempt::where('user_id', $user->id)
                ->whereNotNull('completed_at')
                ->with('quiz');
            
            // Filter by quiz
            if ($request->has('quiz_id')) {
                $query->where('quiz_id', $request->quiz_id);
            }
            
            // Filter by date range
            if ($request->has('date_from')) {
                $query->whereDate('completed_at', '>=', $request->date_from);
            }
            
            if ($request->has('date_to')) {
                $query->whereDate('completed_at', '<=', $request->date_to);
            }
            
            $attempts = $query->orderBy('completed_at', 'desc')
                ->paginate($request->get('per_page', 20));
            
            $data = $attempts->map(function($attempt) {
                return [
                    'attempt_id' => $attempt->id,
                    'quiz' => [
                        'id' => $attempt->quiz->id,
                        'title' => $attempt->quiz->title,
                    ],
                    'score' => $attempt->score,
                    'percentage' => $attempt->score,
                    'mode' => $attempt->mode,
                    'completed_at' => $attempt->completed_at,
                ];
            });
            
            return $this->paginated($data, $attempts);
        } catch (\Exception $e) {
            Log::error('Student Quiz History API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching quiz history.', null, 500);
        }
    }
    
    /**
     * Toggle question bookmark.
     *
     * @param Request $request
     * @param int $questionId
     * @return \Illuminate\Http\JsonResponse
     */
    public function toggleBookmark(Request $request, $questionId)
    {
        try {
            $user = Auth::user();
            
            $validated = $request->validate([
                'notes' => 'nullable|string|max:1000',
            ]);
            
            $bookmark = QuestionBookmark::where('user_id', $user->id)
                ->where('question_id', $questionId)
                ->first();
            
            if ($bookmark) {
                // Remove bookmark
                $bookmark->delete();
                return $this->success(['bookmarked' => false], 'Bookmark removed');
            } else {
                // Create bookmark
                $bookmark = QuestionBookmark::create([
                    'user_id' => $user->id,
                    'question_id' => $questionId,
                    'notes' => $validated['notes'] ?? null,
                ]);
                
                return $this->success([
                    'bookmarked' => true,
                    'bookmark_id' => $bookmark->id,
                ], 'Question bookmarked');
            }
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->error('Validation failed', $e->errors(), 422);
        } catch (\Exception $e) {
            Log::error('Student Quiz Bookmark API error: ' . $e->getMessage());
            return $this->error('An error occurred while toggling bookmark.', null, 500);
        }
    }
    
    /**
     * Get bookmarked questions.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bookmarks(Request $request)
    {
        try {
            $user = Auth::user();
            
            $bookmarks = QuestionBookmark::where('user_id', $user->id)
                ->with(['question.quiz'])
                ->orderBy('created_at', 'desc')
                ->paginate($request->get('per_page', 20));
            
            $data = $bookmarks->map(function($bookmark) {
                return [
                    'id' => $bookmark->id,
                    'question' => [
                        'id' => $bookmark->question->id,
                        'question' => $bookmark->question->question,
                        'quiz' => [
                            'id' => $bookmark->question->quiz->id ?? null,
                            'title' => $bookmark->question->quiz->title ?? 'N/A',
                        ],
                    ],
                    'notes' => $bookmark->notes,
                    'created_at' => $bookmark->created_at,
                ];
            });
            
            return $this->paginated($data, $bookmarks);
        } catch (\Exception $e) {
            Log::error('Student Quiz Bookmarks API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching bookmarks.', null, 500);
        }
    }
    
    /**
     * Get performance analytics.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function analytics(Request $request)
    {
        try {
            $user = Auth::user();
            
            // Overall statistics
            $totalAttempts = QuizAttempt::where('user_id', $user->id)
                ->whereNotNull('completed_at')
                ->count();
            
            $totalQuizzes = QuizAttempt::where('user_id', $user->id)
                ->whereNotNull('completed_at')
                ->distinct('quiz_id')
                ->count('quiz_id');
            
            $averageScore = QuizAttempt::where('user_id', $user->id)
                ->whereNotNull('completed_at')
                ->avg('percentage') ?? 0;
            
            $totalQuestions = QuizAttempt::where('user_id', $user->id)
                ->whereNotNull('completed_at')
                ->sum('total_questions') ?? 0;
            
            $totalCorrect = QuizAttempt::where('user_id', $user->id)
                ->whereNotNull('completed_at')
                ->sum('correct_answers') ?? 0;
            
            $overallAccuracy = $totalQuestions > 0 ? ($totalCorrect / $totalQuestions) * 100 : 0;
            
            // Performance over time (last 30 days)
            $performanceData = QuizAttempt::where('user_id', $user->id)
                ->whereNotNull('completed_at')
                ->where('completed_at', '>=', now()->subDays(30))
                ->orderBy('completed_at')
                ->get(['completed_at', 'percentage'])
                ->map(function($attempt) {
                    return [
                        'date' => $attempt->completed_at->format('M d'),
                        'score' => $attempt->percentage ?? 0
                    ];
                });
            
            // Performance by quiz
            $quizPerformance = QuizAttempt::where('user_id', $user->id)
                ->whereNotNull('completed_at')
                ->with('quiz')
                ->get()
                ->groupBy('quiz_id')
                ->map(function($attempts, $quizId) {
                    $quiz = $attempts->first()->quiz;
                    $bestScore = $attempts->max('percentage') ?? 0;
                    $avgScore = $attempts->avg('percentage') ?? 0;
                    $attemptCount = $attempts->count();
                    
                    return [
                        'quiz' => [
                            'id' => $quiz->id ?? null,
                            'title' => $quiz->title ?? 'N/A',
                        ],
                        'best_score' => round($bestScore, 2),
                        'avg_score' => round($avgScore, 2),
                        'attempts' => $attemptCount
                    ];
                })
                ->sortByDesc('best_score')
                ->take(10)
                ->values();
            
            return $this->success([
                'total_attempts' => $totalAttempts,
                'total_quizzes' => $totalQuizzes,
                'average_score' => round($averageScore, 2),
                'total_questions' => $totalQuestions,
                'total_correct' => $totalCorrect,
                'overall_accuracy' => round($overallAccuracy, 2),
                'performance_data' => $performanceData,
                'quiz_performance' => $quizPerformance,
            ]);
        } catch (\Exception $e) {
            Log::error('Student Quiz Analytics API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching analytics.', null, 500);
        }
    }
    
    /**
     * Get incorrect answers for review.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function reviewIncorrect(Request $request)
    {
        try {
            $user = Auth::user();
            
            $query = QuizAttemptAnswer::whereHas('attempt', function($q) use ($user) {
                $q->where('user_id', $user->id)
                  ->whereNotNull('completed_at');
            })
            ->where('is_correct', false)
            ->with(['attempt.quiz', 'question.answers', 'answer']);
            
            // Filter by quiz
            if ($request->has('quiz_id') && $request->quiz_id) {
                $query->whereHas('attempt', function($q) use ($request) {
                    $q->where('quiz_id', $request->quiz_id);
                });
            }
            
            // Filter by date range
            if ($request->has('date_from') && $request->date_from) {
                $query->whereHas('attempt', function($q) use ($request) {
                    $q->whereDate('completed_at', '>=', $request->date_from);
                });
            }
            
            if ($request->has('date_to') && $request->date_to) {
                $query->whereHas('attempt', function($q) use ($request) {
                    $q->whereDate('completed_at', '<=', $request->date_to);
                });
            }
            
            $incorrectAnswers = $query->orderBy('created_at', 'desc')
                ->paginate($request->get('per_page', 20));
            
            $data = $incorrectAnswers->map(function($attemptAnswer) {
                $question = $attemptAnswer->question;
                $correctAnswer = $question->answers->where('is_correct', true)->first();
                
                return [
                    'id' => $attemptAnswer->id,
                    'question' => [
                        'id' => $question->id,
                        'question_text' => $question->question,
                    ],
                    'quiz' => [
                        'id' => $attemptAnswer->attempt->quiz->id ?? null,
                        'title' => $attemptAnswer->attempt->quiz->title ?? 'N/A',
                    ],
                    'selected_answer' => $attemptAnswer->answer ? [
                        'id' => $attemptAnswer->answer->id,
                        'answer_text' => $attemptAnswer->answer->answer_text,
                    ] : null,
                    'correct_answer' => $correctAnswer ? [
                        'id' => $correctAnswer->id,
                        'answer_text' => $correctAnswer->answer_text,
                    ] : null,
                    'attempt' => [
                        'id' => $attemptAnswer->attempt->id,
                        'completed_at' => $attemptAnswer->attempt->completed_at,
                    ],
                ];
            });
            
            return $this->paginated($data, $incorrectAnswers);
        } catch (\Exception $e) {
            Log::error('Student Quiz Review Incorrect API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching incorrect answers.', null, 500);
        }
    }
}

