<?php



namespace App\Http\Controllers\Frontend;



use App\Http\Controllers\Controller;

use App\Models\CardExam;

use App\Models\Cards;

use App\Models\User;

use App\Models\UserCard;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;

use App\Models\UserTest;

use App\Models\UserTestQuestion;

use App\Models\UserTestQuestionOption;

use Carbon\Carbon;

use Dompdf\Dompdf;

use Dompdf\Options;



class UserCardsController extends Controller

{

    public function all_cards()

{

    $user = auth('web')->user();



    $all_cards = Cards::with(['CardCategory', 'userCard', 'exam'])

        ->leftJoin('user_tests', function ($join) use ($user) {

            $join->on('cards.id', '=', 'user_tests.card_id')

                ->where('user_tests.user_id', '=', $user->id)

                ->where('user_tests.result', '>=', 50); 

        })

        ->select('cards.*', 'user_tests.result as test_result')

        ->groupBy('cards.id')

        ->latest()

        ->get();



    $data = array(

        'title' => 'All Cards',

        'sub_title' => 'All cards',

        'sidebar_menu' => 'all_cards',

        'all_data' => $all_cards,

    );



    return view('client.user_cards.all_cards')->with($data);

}



    public function buyCard(Request $request)

    {

        $user = auth('web')->user();

        $cardId = $request->input('card_id');



        $existingPurchase = DB::table('user_cards')

            ->where('user_id', $user->id)

            ->where('card_id', $cardId)

            ->first();



        if ($existingPurchase) {

            return response()->json([

                'message' => 'You have already purchased this card.'

            ], 400);

        }



        DB::table('user_cards')->insert([

            'user_id' => $user->id,

            'card_id' => $cardId,

            'card_name' => $request->input('card_name'),

            'exam_name' => $request->input('exam_name'),

            'card_price' => $request->input('card_price'),

            'created_at' => now(),

            'updated_at' => now()

        ]);



        return response()->json([

            'message' => 'Card successfully purchased!',

            'redirect' => route('user.cards.mycard')

        ]);

    }



    public function my_card()

    {

        $user = auth('web')->user();



        $all_data = UserCard::where('user_cards.user_id', $user->id)

            ->leftJoin('user_tests', function ($join) use ($user) {

                $join->on('user_cards.card_id', '=', 'user_tests.card_id')

                    ->where('user_tests.user_id', '=', $user->id);

            })

            ->select('user_cards.*', 'user_tests.result as test_result')

            ->groupBy('user_cards.card_id')

            ->get();
            
            // dd($all_data);



        $data = array(

            'title' => 'My Cards',

            'sub_title' => 'All cards',

            'sidebar_menu' => 'my_card',

            'all_data' => $all_data,

        );



        return view('client.user_cards.my_cards')->with($data);

    }



    public function save_exam($id)

    {

        $user = auth('web')->user();

        $exam_data = CardExam::with(['CardExamQuestion.QuestionOptions'])->where('card_id', hashids_decode($id))->first();

        $selected_questions = $exam_data->CardExamQuestion->random(50);



        $user_test = new UserTest();

        $user_test->user_id = $user->id;

        $user_test->exam_id = $exam_data->id;

        $user_test->card_id = $exam_data->card_id;

        $user_test->time = $exam_data->time;

        $user_test->save();



        foreach ($selected_questions as $val) {



            $user_test_question = new UserTestQuestion();

            $user_test_question->user_test_id = $user_test->id;

            $user_test_question->question = $val->question;

            $user_test_question->correct_answer = $val->correct_answer;

            $user_test_question->type = $val->type;

            $user_test_question->save();



            foreach ($val->QuestionOptions as $key => $option) {

                $UserTestQuestionOption = new UserTestQuestionOption();

                $UserTestQuestionOption->answer_options = $option->option;

                $UserTestQuestionOption->test_question_id = $user_test_question->id;

                $UserTestQuestionOption->save();

            }

        }



        return redirect()->route('user.cards.exam_start', hashids_encode($user_test->id));

    }

    public function start_exam($id)

    {

        $userTestId = hashids_decode($id);



        $UserTest = UserTest::with('exam')->where('id', $userTestId)->first();



        // $firstQuestion = UserTestQuestion::with('options')->where('user_test_id', $userTestId)->first();

        $firstQuestion = UserTestQuestion::with('options')

            ->where('user_test_id', $userTestId)

            ->where('status', 0)

            ->first();

        $totalQuestions = UserTestQuestion::where('user_test_id', $userTestId)->count();





        $answeredQuestionsCount = UserTestQuestion::where('user_test_id', $userTestId)

            ->where('status', 1)

            ->count();



        $data = array(

            'title' => 'My Exam',

            'sub_title' => 'Exam',

            'sidebar_menu' => 'my_card',

            'text' => $UserTest,

            'firstQuestion' => $firstQuestion,

            'user_test_id' => $userTestId,

            'examName' => $UserTest->exam->title,

            'totalQuestions' => $totalQuestions,

            'answeredQuestionsCount' => $answeredQuestionsCount,

        );



        return view('client.user_cards.exam')->with($data);

    }

    public function attempt_exam(Request $request)

    {

        $user = auth('web')->user();



        $request->validate([

            'question_id' => 'required|integer',

            'user_test_id' => 'required|integer',

        ]);



        $selectedAnswer = $request->input('user_selected_answer');

        $questionId = $request->input('question_id');

        $userTestId = $request->input('user_test_id');



        $userTestQuestion = UserTestQuestion::where('id', $questionId)->first();



        if ($userTestQuestion) {

            if ($selectedAnswer === $userTestQuestion->correct_answer) {

                $userTestQuestion->correct_status = 1;

            } else {

                $userTestQuestion->correct_status = 0;

            }



            $userTestQuestion->user_selected_answer = $selectedAnswer;

            $userTestQuestion->status = 1;

            $userTestQuestion->save();



            $totalQuestions = UserTestQuestion::where('user_test_id', $userTestId)->count();

            $answeredQuestionsCount = UserTestQuestion::where('user_test_id', $userTestId)

                ->where('status', 1)

                ->count();



            $lastQuestionId = UserTestQuestion::where('user_test_id', $userTestId)

                ->orderBy('id', 'desc')

                ->pluck('id')

                ->first();



            if ($questionId == $lastQuestionId) {

                $correctAnswersCount = UserTestQuestion::where('user_test_id', $userTestId)

                    ->where('correct_status', 1)

                    ->count();



                $percentage = ($correctAnswersCount / $totalQuestions) * 100;



                $userTest = UserTest::where('id', $userTestId)->first();

                if ($userTest) {

                    $userTest->result = $percentage;

                    $userTest->save();

                }



                return response([

                    'status' => true,

                    'complete' => true,

                    'percentage' => $percentage,

                ]);

            } else {

                $firstQuestion = UserTestQuestion::with('options')

                    ->where('status', 0)

                    ->where('user_test_id', $userTestId)

                    ->first();



                $data = [

                    'firstQuestion' => $firstQuestion,

                    'user_test_id' => $userTestId,

                    'answeredQuestionsCount' => $answeredQuestionsCount,

                    'totalQuestions' => $totalQuestions,

                ];



                return response([

                    'status' => true,

                    'complete' => false,

                    'question' => view('client.user_cards.question')->with($data)->render(),

                ]);

            }

        } else {

            return response()->json(['error' => 'Question not found.'], 404);

        }

    }

    public function updateExamStatus(Request $request)

    {

        $userTestId = $request->input('user_test_id');

        $status = $request->input('status');



        $userTest = UserTest::find($userTestId);

        if ($userTest) {

            $userTest->exam_status = $status;



            $totalQuestions = UserTestQuestion::where('user_test_id', $userTestId)->count();

            $correctAnswersCount = UserTestQuestion::where('user_test_id', $userTestId)

                ->where('correct_status', 1)

                ->count();



            $percentage = ($correctAnswersCount / $totalQuestions) * 100;



            $userTest->result = $percentage;

            $userTest->save();



            return response()->json(['success' => true, 'result' => $percentage]);

        }



        return response()->json(['success' => false], 400);

    }



    public function pass_certificate($id)

    {

        $user = auth('web')->user();

        $cards = UserCard::findOrFail($id);
        $user_data = User::where('id', $user)->first();
        $data = [

            'cards' => $cards,

            'title' => 'Certificate of Completion',
            'user_data' => $user_data,

        ];
        return view('client.user_certificate.card')->with($data);
        exit;
        
        // Initialize Dompdf with options

        $options = new Options();

        $options->set('isHtml5ParserEnabled', true);

        $options->set('isPhpEnabled', true);
        $dompdf = new Dompdf($options);
        $dompdf->setPaper('A4', 'portrait');

        $dompdf->loadHtml($pdfContent);

        $dompdf->render();
        $pdfPath = 'pdfs/' . 'pass_certificate-' . $cards->id . '.pdf';

        file_put_contents(storage_path('app/' . $pdfPath), $dompdf->output());
        return response()->download(storage_path('app/' . $pdfPath));
    }

    public function special_certificate($id)

    {

        $user = auth('web')->user();

        // Fetch the user card along with the user and userTests relationships

        $user = auth('web')->user();
        $cards = UserCard::with(['user', 'testUser' => function ($query) {
            $query->orderBy('created_at', 'desc');
        }])->findOrFail($id);

        // dd($cards);

        // Get the latest userTest

        $latestUserTest = $cards->testUser->first();
        // dd($latestUserTest);



        // Pass the data to the view, including the latest test

        $data = [

            'cards' => $cards,

            'latestUserTest' => $latestUserTest, // Pass latest test

            'title' => 'Certificate of Completion',

        ];



        return view('client.user_certificate.certificate')->with($data);
        exit;



        // Initialize Dompdf with options

        $options = new Options();

        $options->set('isHtml5ParserEnabled', true);

        $options->set('isPhpEnabled', true);



        $dompdf = new Dompdf($options);

        $dompdf->setPaper('A4', 'portrait');

        $dompdf->loadHtml($pdfContent);

        $dompdf->render();



        $pdfPath = 'pdfs/' . 'special_certificate-' . $cards->id . '.pdf';

        file_put_contents(storage_path('app/' . $pdfPath), $dompdf->output());



        return response()->download(storage_path('app/' . $pdfPath));

    }

}

