<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
use App\Models\ChatRoom;
use Carbon\Carbon;
use App\Models\Quiz;
use App\Models\QuizQuestion;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use MongoDB\BSON\ObjectId;

class QuizControllers extends Controller
{
    public function generate(Request $request)
    {
        $user   = $request->user();
        $id     = $user->id;
        $chat   = ChatRoom::where('user_id', $id)
                    ->orderBy('created_at', 'DESC')
                    ->limit(4)
                    ->pluck('chat_id')
                    ->toArray();

        if(count($chat)>0)
        {
            // DB::beginTransaction();
            $client = DB::connection('mongodb')->getMongoClient();
            $transaction = $client->startSession();
            $transaction->startTransaction([]);
            try 
            {
                $response = Http::withHeaders([
                    'X-API-Key'     => 'dGVjaHNhZ2FtYXRoc2Fp',
                    'Content-Type'  => 'application/json',
                ])->withBody(
                    json_encode([
                        'chat_ids'  => $chat,
                    ])
                )->post('https://maithsai.cdnmv.com/api/quiz');
    
                $quiz = $response->body();
                $quiz = json_decode($quiz);
                // dd($quiz);
                if($response->successful() && isset($quiz->quiz_id))
                {
                    
                    $time   = Carbon::now();
                    $q_id   = Quiz::insertGetId([
                                        'user_id'   => $id,
                                        'quiz_id'   => $quiz->quiz_id,
                                        'chat_ids'  => json_encode($chat),
                                        'created_at'=> $time
                                    ]);
                    
                    $qq_arr = array();
                    foreach($quiz->quiz as $qz)
                    {
                        $i = 0;
                        foreach($qz as $q2)
                        {
                            $q_k = 'Question';
                            $qq_arr[] = array(
                                                'user_id'   => $id,
                                                'q_id'      => $q_id,
                                                'question'  => $q2->$q_k,
                                                'option'    => json_encode($q2->options),
                                                'answer'    => $q2->answer,
                                                'created_at'=> $time,
                                            );
                        }
                    }

                    $quiz_q = QuizQuestion::insert($qq_arr);

                    if($quiz_q)
                    {
                        $list = QuizQuestion::select('id','question','option')
                                                ->where('q_id',$q_id)
                                                ->get()
                                                ->map(function($raw){
                                                            $raw->option = json_decode($raw->option);
                                                            return $raw;
                                                        });

                        // DB::commit();
                        $transaction->commitTransaction();
                        return response()->json([
                            'success'   => true,
                            'message'   => 'Quiz Generated',
                            'data'      => array('quiz_id'=>$q_id,'list'=>$list),
                        ], 200);
                    }
                    else{
                        // DB::rollBack(); // Undo all DB changes
                        $transaction->abortTransaction();
                        return response()->json([
                            'success'   => false,
                            'message' => 'Something went wrong',
                        ], 200);
                    }
                }
                else
                {
                    return response()->json([
                        'success'   => false,
                        'message' => 'Not Responding',
                        'cause'   => (isset($quiz->error) && $quiz->error!='') ? $quiz->error : '',
                    ], 200);
                }
                 
            } catch (\Exception $e) {
                Log::error('Transaction failed: ' . $e->getMessage());
                // DB::rollBack(); // Undo all DB changes
                $transaction->abortTransaction();
                return response()->json([
                    'success'   => false,
                    'message' => $e->getMessage()
                ], 200);
            }            
        }
        else{

            return response()->json([
                'success'   => false,
                'message'   => 'Chat not exist',
            ], 200);
        }
    }

    public function quizSubmit(Request $request)
    {
        $request->validate([
            'submission'    =>'required',
            'quiz_id'       =>'required',
        ]);

        // DB::beginTransaction();
        $client = DB::connection('mongodb')->getMongoClient();
        $transaction = $client->startSession();
        $transaction->startTransaction([]);

        $ids    = array();
        $data   = $request->submission;
        $error  = 0; 
        $quiz_id= $request->quiz_id;
        foreach($data as $q_id => $ans)
        {
            $ids[]  = $q_id;
            $row    = QuizQuestion::find($q_id);
            if($row == null)
            {
                $error = 1;
            }
            else{
                $row->submitted_answer  = $ans;
                $row->result            = ($row->answer == $ans) ? 1 : 0;
                $row->save();
            }
        }

        if($error==0)
        {
            $result = QuizQuestion::select('id','question','option','answer','submitted_answer','result')
                                        // ->whereIn('id',$ids)
                                        ->where('q_id',new ObjectId($quiz_id))
                                        ->get()
                                        ->map(function($raw){
                                                    $raw->option = json_decode($raw->option);
                                                    return $raw;
                                                });
            // DB::commit();
            $transaction->commitTransaction();
            return response()->json([
                'success'   => true,
                'message'   => 'Submit successfully',
                'result'      => $result,
            ], 200);
        }
        else{
            // DB::rollBack();
            $transaction->abortTransaction();
            return response()->json([
                'success'   => false,
                'message'   => 'Sorry something mismatch',
            ], 200);
        }
    }
}
