<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\UserExam;
use App\Models\PasswordReset;
use App\Models\AttemptExam;
use App\Models\Exam;
use App\Models\ExamResult;
use App\Models\Category;
use App\Models\AttemptExamSubject;
use App\Models\Subject;
use App\Models\UserSubject;
use App\Models\Question;
use App\Models\Answer;
use Illuminate\Support\Str;
use DB;
use Hash;

class Controller extends BaseController
{

    function resp($data = null, $msg = null, $status = true, $code = 200): array{
        return [
            "status"=> $status,
            "code"=> $code,
            "data"=> $data,
            "message"=> $msg
        ];
    }

    public function authenticate(Request $request){
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);
        if (Auth::attempt($credentials)) {
            return response()->json($this->resp(Auth::user(), "successful"));
        }
        return response()->json($this->resp(null, "user not exist! please check your details", false, 422));
    }

    /*public function freeExams($id): RedirectResponse{
        response()->json($this->resp(UserExam::where(["user_id"=> $id, "exam_type"=> "free"])->latest()->get(), "data fetched succefully"));
    }

    public function paidExams($id): RedirectResponse{
        response()->json($this->resp(UserExam::where(["user_id"=> $id, "exam_type"=> "paid"])->latest()->get(), "data fetched succefully"));
    }*/

    
    public function attemptPaidExams($id) {
    
            $subQuery = DB::table('exam_results as er1')
                ->select('er1.user_id', 'er1.user_exam_id', DB::raw('MAX(er1.created_at) as latest_created_at'))
                ->groupBy('er1.user_id', 'er1.user_exam_id');
        
            
            $attemptExams = AttemptExam::from('attempt_exams as ae')
                ->select(
                    'ae.id', 
                    'ae.user_id', 
                    'ae.created_at', 
                    'ue.exam_type', 
                    'ex.name', 
                    DB::raw('SUM(er.result) as overal_result')
                )
                
                ->join('user_exams as ue', 'ue.id', '=', 'ae.user_exam_id')  
                ->join('exams as ex', 'ex.id', '=', 'ue.exam_id')
                ->leftJoin('exam_results as er', function($join) use ($subQuery) {
                    $join->on('er.user_id', '=', 'ae.user_id')
                         ->on('er.user_exam_id', '=', 'ae.user_exam_id')
                         ->joinSub($subQuery, 'latest_results', function ($join) {
                            $join->on('er.user_id', '=', 'latest_results.user_id')
                                 ->on('er.user_exam_id', '=', 'latest_results.user_exam_id')
                                 ->on('er.created_at', '=', 'latest_results.latest_created_at');
                         });
                })
                
                ->where(['ae.user_id' => $id, 'ue.exam_type' => 'paid'])
                ->groupBy('ae.id', 'ae.user_id', 'ex.name', 'ae.created_at', 'ue.exam_type')
                ->orderBy('ae.created_at', 'desc')
                ->first();
                
                $exams = Exam::where("is_popular", 1)->get([
                'id', 
                'image', 
                'name'
            ]);
                
            return response()->json($this->resp([$exams, $attemptExams] , "data fetched successfully"));
            
        }

    public function paidExams($id){
        $userExams = UserExam::from('user_exams as e' )
        ->select(
            'e.id',
            'e.user_id',
            'ex.name',
            'ex.image',
            'ex.body',
            'e.created_at'
            )
        ->join('exams as ex', 'ex.id', '=', 'e.exam_id') 
        ->where(["e.user_id"=> $id, "e.exam_type"=> "paid"])
        ->get();
        collect($userExams)->map(function ($exam) {
            $exams = UserSubject::from('user_subjects as usj')
            ->Join("subjects as sj", "sj.id", "=", "usj.subject_id")
            ->where("usj.user_exam_id", $exam["id"])->get();
            $exam["subjects"] =  $exams;
            return $exam;
        });
        return response()->json($this->resp($userExams, "data fetched successfully"));
    }

    public function userExamSubjects($id, $trial){
        $userSubjects = UserSubject::from("user_subjects as us")
        ->Join("subjects as s")
        ->where("us.exam_id", $id)->get();
        collect($userSubjects)->map(function ($subject) use($trial) {
            $attemptSubject = AttemptExamSubject::where(["user_exam_id"=> $subject["exam_id"], "trial"=>$trial])->first();
            $subject["is_completed"] =  $attemptSubject ? "Completed" : "Not written" ;
            return $userSubjects;
        });
        return response()->json($this->resp($userSubjects, "data fetched succefully"));
    }

    public function submitExamination(Request $request){
        $credentials = $request->validate([
            'user_id' => ['required'],
            'subject_id' => ['required'],
            'exam_id' => ['required'],
            'user_exam_id' => ['required'],
            'attempt_exam_id' => ['required'],
            'trail' => ['required'],
            'answers' => ['required', 'array'],
        ]);
    
        $mark = 0;
    
        foreach($request->answers as $answer) {
            // Retrieve the question from the questions table
            $questionFromSubject = Question::where("id", $answer["question_id"])->first();
    
            // Update or create an answer in the answers table
            Answer::updateOrCreate([
                "user_id" => $request->user_id,
                "question_id" => $answer["question_id"],
                "attempt_exams_id" => $request->attempt_exam_id,
                "subject_id" => $request->subject_id,
                "category_id" => $questionFromSubject->category_id,
            ], [
                "user_id" => $request->user_id,
                "question_id" => $answer["question_id"],
                "attempt_exams_id" => $request->attempt_exam_id,
                "subject_id" => $request->subject_id,
                "category_id" => $questionFromSubject->category_id,
                "my_answer" => $answer["my_answer"],
                "correct_answer" => $questionFromSubject->correct_answer
            ]);
    
            // Check if the given answer is correct
            if (in_array($answer["my_answer"], json_decode($questionFromSubject->correct_answer, true))) {
                Answer::where([
                    "user_id" => $request->user_id,
                    "question_id" => $answer["question_id"],
                    "attempt_exams_id" => $request->attempt_exam_id,
                    "subject_id" => $request->subject_id,
                    "category_id" => $questionFromSubject->category_id,
                ])->update(["my_score" => $questionFromSubject->scores]);
    
                $mark += $questionFromSubject->scores;
            }
        }
    
        // Update or create the exam result in the exam_results table
        ExamResult::updateOrCreate([
            "user_id" => $request->user_id,
            "user_exam_id" => $request->user_exam_id,
            "subject_id" => $request->subject_id,
            "trail" => $request->trail,
        ], [
            "user_id" => $request->user_id,
            "user_exam_id" => $request->user_exam_id,
            "subject_id" => $request->subject_id,
            "trail" => $request->trail,
            "result" => $mark
        ]);
    
        return response()->json($this->resp($mark, "Data submitted"));
    }

    public function submitExaminationX(Request $request) {
        DB::beginTransaction();
    
        $user_id = $request->input('user_id');
        $user_exam_id = $request->input('user_exam_id');
        $subject_id = $request->input('subject_id');
        $attempt_exam_id = $request->input('attempt_exam_id');
        $answers = $request->input('answers');
        $totalScore = 0;
    
        // Retrieve the trail value from the attempt_exams table
        $attempt_exam = AttemptExam::find($attempt_exam_id);
        $trail = $attempt_exam->trail;
    
        foreach ($answers as $answer) {
            // Extract question_id and my_answer from the current answer object
            $question_id = $answer['question_id'];
            $my_answer = $answer['my_answer'];
    
            // Fetch the correct answer and score for the question
            $question = Question::find($question_id);
            $correct_answer = json_decode($question->correct_answer, true);
            $scores = $question->scores;
            $category_id = $question->category_id;
    
            // Determine if the answer is correct
            $is_correct = ($my_answer == $correct_answer[0]); // Comparing with the first element of correct_answer array
    
            if ($is_correct) {
                $totalScore += $scores;
            }
    
            // Save the answer to the answers table
            Answer::create([
                'user_id' => $user_id,
                'question_id' => $question_id,
                'attempt_exams_id' => $attempt_exam_id,
                'subject_id' => $subject_id,
                'category_id' => $category_id,
                'my_answer' => $my_answer,
                'correct_answer' => json_encode($correct_answer), // Correctly encoding the correct answer as JSON string
            ]);
        }
    
        // Save the result to the exam_results table
        ExamResult::create([
            'user_id' => $user_id,
            'user_exam_id' => $user_exam_id,
            'subject_id' => $subject_id,
            'result' => $totalScore,
            'trail' => $trail,
        ]);
    
        DB::commit();
    
        return response()->json($this->resp(['result' => $totalScore], "Data submitted successfully"));
    }

    public function submitExamSubjects(Request $request){
        $credentials = $request->validate([
            'subjects' => ['required'],
            'user_id' => ['required'],
            'exam_id' => ['required'],
            'attempt_exam_id' => ['required'],
            'subject_id' => ['required'],
            'trail' => ['required'],
        ]);

        foreach($request->subjects as $subject){
            $attemptExams = (new AttemptExam())->where("user_exam_id", $subject["user_exam_id"])->first();
            $attemptExamSubjects = (new AttemptExamSubject());
            $examResults = (new ExamResult());
            if(!$attemptExams){
                AttemptExam::create([
                    "user_id"=> $request->user_id,
                    "user_exam_id"=> $subject["user_exam_id"]
                ]);
            }
            $attemptExams = (new AttemptExam())->where("user_exam_id", $subject["user_exam_id"])->first();
            if(!$attemptExamSubjects->where(["attempt_exam_id"=> $attemptExams->id, "trail"=>$request->trail])->first()){
                $attemptExamSubjects->create([
                    "user_id"=> $request->user_id,
                    "attempt_exam_id"=> $attemptExams->id,
                    "subject_id"=> $subject["id"],
                    "trail"=> $request->trail
                ]);
            }
            if(!$examResults->where(["user_exam_id"=> $subject["user_exam_id"], "trail" =>$request->trail])->first()){
                $examResults->create([
                    "user_id"=> $request->user_id,
                    "user_exam_id"=> $subject["user_exam_id"],
                    "subject_id"=> $subject["id"],
                    "result"=> 0,
                    "trail"=> $request->trail
                ]);
            }

        }
        UserExam::where("exam_id", $request->exam_id)->Update(["exam_trial"=>$request->trail]);
       return response()->json($this->resp(null, "Data submited"));
    }

    public function subjectQuestions($id = null){
        $subject = Subject::where("id",  $id)->first();
        $subjectCats = Category::where("subject_id", $id)->get();
        $questions = [];
        //get remainder value here
        $remainder = $subject->number_of_questions % $subjectCats->count();
        //divide the value here
        $numberToDiv = round($subject->number_of_questions / $subjectCats->count(), 0, PHP_ROUND_HALF_DOWN);
        return response()->json($this->resp($numberToDiv, "Data fetched"));
        foreach($subjectCats as $subjectCat){
            //divide by number from subject
            $qus = Question::where(["subject_id"=> $id, "category_id"=> $subjectCat["id"]])->take($numberToDiv)->get()->shuffle();

            foreach( $qus as  $qu){
                $questions[] = $qu;
            }
        }
        if($remainder == 0){
            return response()->json($this->resp($questions, "Data fetched"));
        }
        //do the remainder here
        $questionsRem = [];
        $subjectRemCats = Category::where("subject_id", $id)->take($remainder)->get()->shuffle();
        foreach($subjectRemCats as $subjectRemCat){
            $qusRems = Question::where(["subject_id"=> $id, "category_id"=> $subjectRemCat["id"]])->take($numberToDiv)->get();
            foreach( $qusRems as  $qusRem){
                $questionsRem[] = $qusRems;
            }
        }

        return response()->json($this->resp(array_merge($questions, $questionsRem), "Data fetched"));
    }

    public function subjectQuestions2($id = null){

        $subject = Subject::where("id",  $id)->get();
        $subjectCats = Category::where("subject_id", $id)->where("number_of_question", "!=", 0)->get();

        $questions = [];
        foreach($subjectCats as $subjectCat){
            $qus = Question::where(["subject_id"=> $id, "category_id"=> $subjectCat["id"]])->take($subjectCat["number_of_questions"])->get()->shuffle()->toArray();
           foreach( $qus as  $qu){
            $questions[] = $qu;
           }
        }

        return response()->json($this->resp($questions, "Data fetched"));
    }

    public function userResults($id) {
        $examsResults = ExamResult::where("user_id", $id)->latest()->get();
        $results = [];
        $examsResultX = [];
    
        foreach($examsResults as $examsResult) {
            $examID = UserExam::where("id", $examsResult["user_exam_id"])->first();
            $exams = Exam::where("id", $examID->exam_id)->first();
            $attemptExams = AttemptExam::where(["user_exam_id" => $examsResult["user_exam_id"], "trail"=> $examsResult["trail"] ])->first();
            $examName = $exams->name;
            $attempt_exam_id = $attemptExams->id;
            $examPickSubject = $exams->pick_subject;
            
            if($examPickSubject == 0){
                $exam_type = 'professional';
            } else {
                $exam_type = 'non-professional';
            }
            
            $key = $examName . '|' . $examsResult->trail . '|' . $examsResult->user_exam_id;
    
            if (!isset($examsResultX[$key])) {
                $examsResultX[$key] = [
                    'attempt_exam_id' => $attempt_exam_id,
                    'name' => $examName,
                    'overall_score' => 0,
                    'subjects' => [],
                    'trail' => $examsResult->trail,
                    'created_at' => $attemptExams->created_at,
                    'exam_type' => $exam_type,
                ];
            }
    
            if ($examsResult["subject_id"] != 0) {
                $subject = Subject::where('id', $examsResult["subject_id"])->first();
    
                if (!isset($examsResultX[$key]['subjects'][$subject->subject])) {
                    $examsResultX[$key]['subjects'][$subject->subject] = [
                        'subject_id' => $subject->id,
                        'subject' => $subject->subject,
                        'score' => 0,
                        'created_at' => $attemptExams->created_at,
                    ];
                }
    
                $examsResultX[$key]['subjects'][$subject->subject]['score'] += $examsResult->result;
                $examsResultX[$key]['overall_score'] += $examsResult->result;
            } else {
                $examsResultX[$key]['overall_score'] += $examsResult->result;
            }
        }
        
        foreach ($examsResultX as $key => $trailData) {
            $result = [
                "name" => $trailData['name'],
                "overall_score" => $trailData['overall_score'],
                "trail" => $trailData['trail'],
                "created_at" => $trailData['created_at'],
                "exam_type" => $trailData['exam_type'],
                "attempt_exam_id" => $trailData['attempt_exam_id'],
            ];
    
            if (!empty($trailData['subjects'])) {
                $result['subjects'] = array_values($trailData['subjects']);
            }
    
            $results[] = $result;
        }
    
        return response()->json($this->resp($results, "data fetched successfully"));
    }

    public function userResultSubjects($id, $attempt_exam_id){
        $subjects = AttemptExamSubject::
        from("attempt_exam_subjects as aes")->join("subjects as s", "s.id", "=", "aes.subject_id")
        ->select("aes.*", "s.subject")
        ->where(["aes.user_id"=> $id, "aes.attempt_exam_id"=> $attempt_exam_id])->get();
        return response()->json($this->resp($subjects, "data fetched succefully"));
    }

    public function userResultSubjectQuestionsReview($id, $attempt_exam_id, $subject_id) {
        // Fetch answers from the answers table
        $answers = Answer::where('user_id', $id)
            ->where('attempt_exams_id', $attempt_exam_id)
            ->where('subject_id', $subject_id)
            ->get();
            
        // Fetch subject from the subject table
        $subject = Subject::find($subject_id);
    
    
        // Format the answers data
        $formattedAnswers = $answers->map(function ($answer) {
            // Retrieve the question details from the questions table
            $question = Question::find($answer->question_id);
    
            // Decode the correct_answer JSON array
            $correct_answer = json_decode($answer->correct_answer, true);
    
            // Decode options and format them as array of key-value pairs
            $options = json_decode($question->options, true);
            $formattedOptions = [];
            foreach ($options as $key => $value) {
                $formattedOptions[] = [$key => $value];
            }
    
            // Determine the result (correct or wrong)
            $result = in_array($answer->my_answer, $correct_answer) ? 'correct' : 'wrong';
            
            // Retrieve explanation from the question
            $explanation = $question->explanation;
    
            return [
                'question_id' => $question->id,
                'question' => $question->question,
                'category_id' => $question->category_id,
                'options' => $formattedOptions, // Return formatted options
                'answer' => $answer->my_answer,
                'correctAnswer' => $correct_answer, // Return as an array
                'scores' => $question->scores,
                'question_type' => $question->question_type,
                'result' => $result,
                'explanation' => $explanation
            ];
        });
    
        // Prepare the response data
        $response = [
            'user_id' => $id,
            'subject_id' => $subject_id,
            'subject_name' => $subject->subject,
            'attempt_exam_id' => $attempt_exam_id,
            'created_at' => $answers->first()->created_at->toISOString(), // Assuming all answers have the same created_at
            'answers' => $formattedAnswers
        ];
    
        return response()->json($this->resp($response, "Data fetched successfully"));
    }

    public function calculateCategoryPercentages($id, $attempt_exam_id, $subject_id) {
        // Fetch answers for the given user_id, attempt_exam_id, and subject_id
        $answers = Answer::where('user_id', $id)
            ->where('attempt_exams_id', $attempt_exam_id)
            ->where('subject_id', $subject_id)
            ->get();
            
              
        // Fetch subject from the subject table
        $subject = Subject::find($subject_id);
    
        // Initialize an array to store category totals and counts
        $categoryTotals = [];
        $categoryCounts = [];
    
        // Initialize variables to calculate overall accuracy
        $total_correct = 0;
        $total_questions = $answers->count();
    
        // Iterate through each answer to calculate totals and counts
        foreach ($answers as $answer) {
            $category_id = $answer->category_id;
    
            // Retrieve category name from the categories table
            $category = Category::find($category_id);
            $category_name = $category->name;
    
            // Initialize category totals and counts if not already set
            if (!isset($categoryTotals[$category_id])) {
                $categoryTotals[$category_id] = 0;
                $categoryCounts[$category_id] = 0;
            }
    
            // Increment the total count for the category
            $categoryCounts[$category_id]++;
    
            // Decode the correct_answer JSON array
            $correct_answer = json_decode($answer->correct_answer);
    
            // Check if the answer is correct
            if (in_array($answer->my_answer, $correct_answer)) {
                // Increment the correct total for the category
                $categoryTotals[$category_id]++;
                $total_correct++;
            }
        }
    
        // Initialize an array to store category percentages
        $categories = [];
    
        // Calculate percentages and format the response
        foreach ($categoryTotals as $category_id => $total) {
            $count = $categoryCounts[$category_id];
            $percentage = ($count > 0) ? round(($total / $count) * 100) : 0;
    
            // Retrieve category name from the categories table
            $category = Category::find($category_id);
            $category_name = $category->category;
    
            // Build the category data array
            $categories[] = [
                'id' => $category_id,
                'name' => $category_name,
                'percentage' => $percentage
            ];
        }
    
        // Calculate overall accuracy
        $accuracy = ($total_questions > 0) ? round(($total_correct / $total_questions) * 100) : 0;
    
        // Prepare the response data
        $response = [
            'status' => true,
            'code' => 200,
            'data' => [
                'user_id' => $id,
                'subject_id' => $subject_id,
                'subject_name' => $subject->subject,
                'attempt_exam_id' => $attempt_exam_id,
                'categories' => $categories,
                'accuracy' => $accuracy,
                'total_correct' => $total_correct,
                'total_questions' => $total_questions,
                
            'message' => 'Data fetched successfully'
            ]
        ];
    
        return response()->json($response);
    }

    public function register(Request $request){
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
            'name' => ['required'],
            'phone' => ['required'],
        ]);
        if (User::where("email", $request->email)->orWhere("phone", $request->phone)->first()) {
            return  response()->json($this->resp(null, "user exist! Login instead", false, 422));
        }
        $user = User::create([
            'name' => $request->name,
            'phone' => $request->phone,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);
       return response()->json($this->resp($user, "user successfully enroled"));
    }

    public function passwordReset(Request $request){
        $credentials = $request->validate([
            'email' => ['required', 'email'],
        ]);
        $user = User::where("email", $request->email)->first();
        if (!$user) {
            return  response()->json($this->resp(null, "user not exist! this user record is not with us", false, 422));
        }
        PasswordReset::create([
            'email' => $request->email,
            'token' => Str::random(40)
        ]);
        return response()->json($this->resp(null, "user successfully enroled"));
    }

    public function changePassword(Request $request){
        $credentials = $request->validate([
            'email' => ['required'],
            'old_password' => ['required'],
            'password' => ['required'],
        ]);
        $user = User::where('email', $request->email)->first();
        if (!$user)return response()->json($this->resp(null, "failed to change password!", false, 422));
        if (!Hash::check($request->old_password, $user->password ))return response()->json($this->resp(null, "failed to change password!!!!", false, 422));
        $user->update(["password" => bcrypt($request->password)]);
        return response()->json($this->resp($user, "Password successfully changed", true));
    }

    public function exams($popular = null){
        $exams = is_null($popular) ? Exam::get([
                'id', 
                'image', 
                'name'
            ]) : Exam::where("is_popular", $popular)->get([
                'id', 
                'image', 
                'name'
            ]);
        return response()->json($this->resp($exams, "data fetched"));
    }
    
    public function examSubjects($id = null){
        return response()->json($this->resp(Subject::where("exam_id", $id)->get(), "data fetched"));
    }

    public function logPaidSubject(Request $request){
        $credentials = $request->validate([
            'exam_id' => ['required'],
            'subjects' => ['required'],
            'user_id' => ['required'],
            'exam_type' => ['required'],
            //'exam_trial' => ['required']
        ]);
       $exam = UserExam::create([
            "user_id"=>$request->user_id,
            "exam_id"=>$request->exam_id,
            "exam_type"=>$request->exam_type,
            //"exam_trial"=>$request->exam_trial,
        ]);
        foreach($request->subjects as $subject){
            UserSubject::create([
                "user_id"=>$request->user_id,
                "user_exam_id"=>$exam->id,
                "subject_id"=> $subject["id"],
            ]);
        }


        return response()->json($this->resp(null, "data submitted"));
    }

    public function getQuestions($exam_id, $id) {
    if (is_null($exam_id)) {
        return response()->json(['error' => 'Exam ID cannot be null'], 400);
    }

    if ($id == 0) {
        // Fetch total questions from the Exams table using exam_id
        $exam = Exam::findOrFail($exam_id);
        $totalQuestions = $exam->number_of_questions;

        // Fetch categories associated with the exam_id
        $categories = Category::where('exam_id', $exam_id)->get();
    } else {
        // Fetch total questions from the Subjects table using subject_id
        $subject = Subject::findOrFail($id);
        $totalQuestions = $subject->number_of_questions;

        // Fetch categories associated with the subject_id
        $categories = Category::where('subject_id', $id)->get();
    }

    $questions = collect();

    foreach ($categories as $category) {
        $categoryQuestionsCount = $category->number_of_questions;
        $randomQuestions = Question::where('category_id', $category->id)
                                   ->inRandomOrder()
                                   ->take($categoryQuestionsCount)
                                   ->get();
        $questions = $questions->merge($randomQuestions);
    }

    if ($questions->count() > $totalQuestions) {
        $questions = $questions->random($totalQuestions);
    }

    return response()->json($questions);
}

    public function freeCheck($user_id){
        $freeCount = UserExam::where('user_id', $user_id)
            ->where('exam_type', 'free')
            ->count();

        // Create a response array
        $response = [
            'count' => $freeCount
        ];

        // Return the response as JSON
        return response()->json($response);
    }
    
    public function getFreeQuestions($exam_id, $subject_id){
        $questions = Question::where('exam_id', $exam_id)
            ->where('subject_id', $subject_id)
            ->inRandomOrder()
            ->take(10)
            ->get([
                'id', 
                'question', 
                'exam_id', 
                'subject_id', 
                'category_id', 
                'options', 
                'correct_answer', 
                'scores', 
                'question_type'
            ]);

        return response()->json($questions);
    }
    
    public function examsDetails($id){
        $exam = Exam::where("id", $id)->first([
                'id', 
                'image', 
                'name',
                'description', 
                'body',
                'pick_subject', 
                'number_of_questions',
                'total_score', 
                'is_popular',
            ]);
            
            // Check pick_subject field
        if ($exam->pick_subject == '1') {
            // Get subjects related to this exam
            $subjects = Subject::where('exam_id', $exam->id)->get(['id', 'subject']);
        } else {
            // Use the exam name as the subject
            $subjects = collect([['subject' => $exam->name]]);
        }

        // Append subjects to exam data
        $exam->subjects = $subjects;

        return response()->json($this->resp($exam, "data fetched"));
    }
    
    public function freeExamSubject($exam_id, $subject_id){
        $subjects = Subject::where('exam_id', $exam_id)
            ->where('id', $subject_id)
            ->get([
                'subject'
            ]);

        return response()->json($subjects);
    }
    
    public function startFreeExam($user_id, $exam_id, $subject_id) {
            DB::beginTransaction();
        
            // Insert into user_exams table
            $userExam = UserExam::create([
                'user_id' => $user_id,
                'exam_id' => $exam_id,
            ]);
        
            // Insert into user_subjects table
            $userSubject = UserSubject::create([
                'user_id' => $user_id,
                'subject_id' => $subject_id,
                'user_exam_id' => $userExam->id,
            ]);
        
            // Insert into attempt_exams table
            $attemptExam = AttemptExam::create([
                'user_id' => $user_id,
                'user_exam_id' => $userExam->id,
                'trail' => 1,
            ]);
        
            // Insert into attempt_exam_subjects table
            $attemptExamSubject = AttemptExamSubject::create([
                'user_id' => $user_id,
                'attempt_exam_id' => $attemptExam->id,
                'subject_id' => $subject_id,
                'trail' => 1,
            ]);
        
        
            // Retrieve the subject details
            $subject = Subject::find($subject_id);
                
                 // Retrieve 10 random questions from the questions table
            $questions = Question::where('exam_id', $exam_id)
                ->where('subject_id', $subject_id)
                ->inRandomOrder()
                ->take(10)
                ->get([
                    'id',
                    'question',
                    'exam_id',
                    'subject_id',
                    'category_id',
                    'options',
                    'scores',
                    'question_type'
                ]);
        
            // Format the questions array as needed
            $formattedQuestions = $questions->map(function ($question) {
                $options = json_decode($question->options, true);
                $formattedOptions = [];
                foreach ($options as $key => $value) {
                    $formattedOptions[] = [$key => $value];
                }
        
                return [
                    'id' => $question->id,
                    'question' => $question->question,
                    'exam_id' => $question->exam_id,
                    'subject_id' => $question->subject_id,
                    'category_id' => $question->category_id,
                    'options' => $formattedOptions, // Format options as array of key-value objects
                    'scores' => $question->scores,
                    'question_type' => $question->question_type
                ];
            });
        
            DB::commit();
        
            // Create a response array with the required format
            $response = [
                'user_id' => $user_id,
                'subject_id' => $subject_id,
                'user_exam_id' => $userExam->id,
                'attempt_exam_id' => $attemptExam->id,
                'allocated_time' => $subject->allocated_time,
                'questions' => $formattedQuestions,
            ];
        
            return response()->json($this->resp($response, "Data fetched successfully"));
        }


}
