<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use App\Models\User;
use App\Models\Avatar;
use App\Models\Category;
use App\Models\Guest;
use App\Models\Quiz;
use App\Models\QuizQuestion;
use App\Models\QuizQuestionChoice;
use App\Models\UserQuiz;
use App\Models\UserQuizResult;
use Illuminate\Pagination\Paginator;

class ApiController extends Controller
{



    public  function generateRandomString($length = 10)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[random_int(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    public function guest(Request $request)
    {
        $validation = Validator::make($request->all(),[
           'name'     => 'required',
           'country'  => 'required',
        ]);
       if($validation->fails())
       {
        $error = $validation->errors()->first();
        return response()->json([
            'errors' => $validation->errors(),
             'message' => $error,
              'status_code' => '400'
              ],400);
       }

       $user = new User();
       $user->name = $request->name;
       $user->email = $this->generateRandomString(6)."@test.com";
       $user->role = 3;
       $user->plateform = 'Guest';
       $user->country = $request->country;
       $user->country_code = $request->country_code;
       $user->firebase_token = $request->firebase_token;
       if ($request->avatar)
       {
            $avaterinfo = Avatar::where('id',$request->avatar)->first();
            $user->photo = asset('assets/avatar')."/". $avaterinfo->title;
       }
       if ($request->photo)
       {
            $photo = $request->photo;
            $name = mt_rand(100000, 999999) . time() . '.' . $photo->getClientOriginalExtension();
            $destinationPath = public_path('assets/uploads');
            $photo->move($destinationPath, $name);
            $user->photo = asset('assets/uploads')."/".$name;
       }
       if($user->save())
       {
                // if($user->avatar!='')
                // {
                //     $avatarinfo = Avatar::find($user->avatar);
                //     $user->avatar = asset('assets/avatar/')."/".$avatarinfo->title;
                // }

            return response()->json([
             'status_code' => '200',
             'token' => $user->createToken('authToken')->plainTextToken,
             'user' => $user,
             'message' => 'Guest has been saved successfully',
             // 'profilepath' => asset('images/uploads'),
             //  'avatarpath' => asset('images/avatar'),
            ],200);
       }
       else
       {
            return response()->json([
             'message' => "Try Again",
             'status_code' => '400',
              'error' => 1
            ],400);
       }
    }

    public function avatarlist(Request $request)
    {
        $list = Avatar::select('id','title')->get();
        return response()->json([
             'status_code' => '200',
             'list' => $list,
             'path' => asset('/assets/avatar/'),
            ],200);

    }
    public function categorylist(Request $request)
    {
        $list = Category::select('id','name','image')->get();
        return response()->json([
             'status_code' => '200',
             'list' => $list,
             'path' => asset('/assets/avatar/'),
            ],200);

    }

    public function getAvatarById($id)
    {
       if(empty($id))
       {
            return response()->json([
             'message' => "ID Missing",
             'status_code' => '400',
              'error' => 1
            ],400);
       }
       else
       {
         $avatar = Avatar::select('id','title')->where('id',$id)->first();
         return response()->json([
             'status_code' => '200',
             'avatar' => $avatar,
             'path' => asset('/assets/avatar/'),
            ],200);

       }
    }

    public function profile()
    {
        $user_id = Auth()->user()->id;
        $uinfo = User::where(['id'=>$user_id])->first();
        $country = Auth()->user()->country;


            $exist = UserQuiz::where('user_id',$user_id)->exists();
            if($exist)
            {
                $score = UserQuiz::select('score')->where(['user_id'=>$user_id])->first();
                $scorelocalrank = UserQuiz::select('user_id','score')->where(['country'=>$country])->orderBy('score','DESC')->pluck('user_id')->toArray();
                $scoreglobalrank = UserQuiz::select('user_id','score')->orderBy('score','DESC')->pluck('user_id')->toArray();
                $localrank = array_search($user_id,$scorelocalrank)+1;
                $globalrank = array_search($user_id,$scoreglobalrank)+1;
                $uinfo['score']= intval($score->score);
                $uinfo['localrank']=intval($localrank);
                $uinfo['globalrank']=intval($globalrank);
                $level =  UserQuiz::select('level')->where('user_id',Auth()->user()->id)->first();
                $uinfo['level'] = intval($level->level);
            }
            else
            {
                $count = UserQuiz::where('country',$country)->count();
                $gcount = UserQuiz::count();
                $uinfo['score']=0;
                $uinfo['localrank']=$count+1;
                $uinfo['globalrank']=$gcount+1;
                $uinfo['level'] = 1;
            }




        // if($uinfo->avatar!='')
        //         {
        //             $avatarinfo = Avatar::find($uinfo->avatar);
        //             $uinfo->avatar = asset('assets/avatar/')."/".$avatarinfo->title;
        //         }
            return response()->json([
                'profile' => $uinfo,
                'message' => "Profile display successfully.",
                'status_code' => '200',
               ],200);
    }


    public function profileUpdate(Request $request)
    {

        if($request->email!='')
        {
            $validation = Validator::make($request->all(),[
                'email' => 'required|email|max:255|unique:users,email,' . auth()->user()->id,
            ]);
            if($validation->fails()){
                $error = $validation->errors()->first();
                return response()->json([
                    'errors' => $validation->errors(),
                    'message' => $error,
                    'status_code' => '400'
                    ],400);
            }
         }
        $user = User::where('id', auth()->user()->id)->first();

        if($request->name){
            $user->name = $request->name;
        }

        if($request->avatar){
            $avaterinfo = Avatar::where('id',$request->avatar)->first();
            $user->photo = asset('assets/avatar')."/". $avaterinfo->title;
        }

        if ($request->photo) {
            $id_photo = $request->photo;
            $name = mt_rand(100000, 999999) . time() . '.' . $id_photo->getClientOriginalExtension();
            $destinationPath = public_path('assets/uploads');
            $id_photo->move($destinationPath, $name);
            $user->photo = asset('assets/uploads')."/".$name;
        }

        if($user->save()){
            return response()->json([
                'status_code' => '200',
                'user' => $user,
                'message' => 'Profile has been updated successfully',
                ],200);
          }else{
            return response()->json([
                'message' => "Try Again",
                'status_code' => '400',
                'error' => 1
               ],400);
          }
    }

    public function logout(Request $request)
    {
        $check = Auth()->user()->currentAccessToken()->delete();
        if($check)
        {
            return response()->json([
                'message' => 'User has been logout successfully',
                'status_code' => '200',
            ],200);
        }
        else
        {
            return response()->json([
                'message' => 'Try again later',
                'status_code' => '400',
                'error'      => 1,
            ],400);
        }

    }

    public function SocialLogin(Request $request)
    {
        $validation = Validator::make($request->all(), [
            'email'            => 'required',
            'name'             => 'required',
            'photo'            => 'required',
            'token'            => 'required',

        ]);
        if ($validation->fails()) {
            return response()->json(['errors' => $validation->errors()->first(), 'error' => true, 'status_code' => 400],400);
        }


        $chechUser = User::where('email',$request->email)->first();

        if(!empty($chechUser)){

                $credentials = [
                    'email' => $request->email,
                    'password' => 'gotspace',
                ];
                if (!Auth::attempt($credentials)) {
                        // return response()->json([
                        //     'message'=>"Email already exit",
                        //     'error' => true,
                        //     'status_code' => 400,
                        // ],400);
                        return response()->json(['message' => "Something is not right", 'error' => true, 'status_code' => 400],400);
                    }

                    $user = $request->user();
                    $user->name = $request->name;
                    $user->email = $request->email;
                    if ($request->photo)
                    {
                        // $photo = $request->photo;
                        // $name = mt_rand(100000, 999999) . time() . '.' . $photo->getClientOriginalExtension();
                        // $destinationPath = public_path('assets/uploads');
                        // $photo->move($destinationPath, $name);
                        // $user->photo = $name;
                        $user->photo = $request->photo;
                    }
                    $user->firebase_token = $request->token;
                    $user->save();
                    $token = $user->createToken('authToken')->plainTextToken;


                return response()->json(
                ['status_code'=>'200',
                  'token'=> $token,
                  'user' => $user,
                  //'path' => asset('/assets/uploads/'),
                  'message' => 'Login successfully'
                ],200);


        }else{
            $user = new User;
            $user->email  = $request->email;
            $user->name = $request->name;
            $user->country = $request->country;
            $user->country_code = $request->country_code;
            $user->role = 2;
            $user->status = 1;
            $user->plateform = 'Social';
            if ($request->photo)
            {
               // $photo = $request->photo;
               // $name = mt_rand(100000, 999999) . time() . '.' . $photo->getClientOriginalExtension();
               // $destinationPath = public_path('assets/uploads');
               // $photo->move($destinationPath, $name);
               // $user->photo = $name;
                $user->photo = $request->photo;
            }
            $user->firebase_token  = $request->token;
            $user->password  = bcrypt('gotspace');
            $user->save();
            if($user->save()){

                if (!Auth::attempt(['email' => $request->email , 'password' => 'gotspace' ])) {
                    return response()->json(['message' => "Something is not right", 'error' => true, 'status_code' => 400],400);
                }
                $logUser = $request->user();
                $logUserToken = $user->createToken('authToken')->plainTextToken;

               return response()->json(
                ['status_code'=>'200',
                  'token'=> $logUserToken,
                  'user' => $user,
                 // 'path' => asset('/assets/uploads/'),
                  'message' => 'User is registered succesfully'
                ],200);

            }else{
                return response()->json([
                    'message' => "Try Again",
                    'status_code' => 400,
                    'error' => true,
                ],400);
            }
        }
    }


    public function getQuizByCategory($id)
    {
        $is_quiz_exist = Quiz::where('cat_id',$id)->exists();
        if($is_quiz_exist)
        {
            $quiz = Quiz::where('cat_id',$id)->first();
             return response()->json(
                ['status_code'=>'200',
                  'quiz'=> $quiz,
                  'message' => 'Quiz has been fetched succesfully'
                ],200);
        }
        else
        {
            return response()->json([
                    'message' => "No Quiz Found",
                    'status_code' => 200,
                ],200);
        }
    }


    public function getQuestions($id)
    {
        $is_question_eixst = QuizQuestion::where('cat_id',$id)->exists();
        if($is_question_eixst)
        {
            $question  = QuizQuestion::where('cat_id',$id)
            ->inRandomOrder()
            ->limit(10)
            ->get();
            foreach($question as $key=>$val)
            {
                $question[$key]['choices'] = QuizQuestionChoice::where('question_id',$val->id)->get();
            }
            return response()->json(
                ['status_code'=>'200',
                  'questions'=> $question,
                  'message' => 'Questions has been fetched succesfully'
                ],200);
        }
        else
        {
            return response()->json([
                    'message' => "No Quiz Question Found",
                    'status_code' => 200,
                ],200);
        }
    }



    public function submitquiz(Request $request)
    {
        $user_id = Auth()->user()->id;
     //   $cat_id = $request->cat_id;
        $correct_answers = $request->correct_answers;
        $uinfo = User::where('id',$user_id)->first();
        $exist = UserQuiz::where('user_id',$user_id)->exists();
        if($exist)
        {
            $quiz = UserQuiz::where('user_id',$user_id)->first();
            $quiz->user_id = $user_id;
            $quiz->cat_id = 0;
            $quiz->country = $uinfo->country;
            //$quiz->totalquestion = 10;//$totalquestion;
            $quiz->correct =  $quiz->correct + $correct_answers;
           // $quiz->wrong = 10 -  $correct_answers;
            $quiz->score = $quiz->score + ($correct_answers*2);
            if($quiz->save())
            {
                return response()->json([
                    'message' => "Result has been saved successfully.",
                    'result' => $quiz,
                    'status_code' => 200,
                  ],200);
            }
        }
        else
        {
            $quiz = new UserQuiz();
            $quiz->user_id = $user_id;
            $quiz->cat_id = 0;//$cat_id;
            $quiz->country = $uinfo->country;
            //$quiz->totalquestion = 10;//$totalquestion;
            $quiz->correct =  $correct_answers;
           // $quiz->wrong = 10 -  $correct_answers;
            $quiz->score = $correct_answers*2;
            if($quiz->save())
            {
                return response()->json([
                    'message' => "Result has been saved successfully.",
                    'result' => $quiz,
                    'status_code' => 200,
                  ],200);
            }
        }


    }

    public function getScore()
    {
        $user_id = Auth()->user()->id;
        $exist = UserQuiz::select('score')->where(['user_id'=>$user_id])->exists();
        if($exist)
            {

                $score = UserQuiz::select('score')->where(['user_id'=>$user_id])->first();
                 return response()->json([
                        'message' => "Score has been fetched successfully.",
                        'score' => $score->score,
                        'status_code' => 200,
                      ],200);
            }
        else
            {
                return response()->json([
                    'message' => "Score has been fetched successfully.",
                    'score' => 0,
                    'status_code' => 200,
                  ],200);
            }

    }


    public function getLocalRanking($country)
    {
        $user_id = Auth()->user()->id;
        $exist = UserQuiz::where(['user_id'=>$user_id,'country'=>$country])->exists();
        $alluserscore = UserQuiz::leftjoin('users','user_quizzes.user_id','=','users.id')->where(['user_quizzes.country'=>$country])->orderBy('user_quizzes.score','DESC')->paginate(30);
        $rankcounter = 0;
        foreach($alluserscore as $key=>$val)
        {
            $rankcounter++;
            $alluserscore[$key]['localrank'] = $rankcounter;

        }
        if($exist)
            {

                $score = UserQuiz::select('user_id','score')->where(['country'=>$country])->orderBy('score','DESC')->pluck('user_id')->toArray();
                // $score2 = UserQuiz::select('user_id','score')->where(['country'=>$country])->orderBy('score','DESC')->get();

                 $uscore = UserQuiz::select('score')->where(['country'=>$country,'user_id'=>$user_id])->orderBy('score','DESC')->first();

                 $userobj = User::where('id',$user_id)->first();
                 $userobj['localrank'] = array_search($user_id,$score)+1;
                 $userobj['score'] = intval($uscore->score);


                 return response()->json([
                        //'message' => "Score has been fetched successfully.",
                        'alluserranking' => $alluserscore,
                        //'rank' => array_search($user_id,$score)+1,
                        'currentuserranking' => $userobj,
                        'status_code' => 200,
                      ],200);
            }
        else
            {
                $count = UserQuiz::where('country',$country)->count();
                $userobj = User::where('id',$user_id)->first();
                $userobj['localrank'] = $count+1;
                $userobj['score'] = 0;
                return response()->json([
                    'message' => "Score has been fetched successfully.",
                        'alluserranking' => $alluserscore,
                        'currentuserranking' =>$userobj,
                        'status_code' => 200,
                  ],200);
            }



    }


   public function getWorldRanking()
    {
        $user_id = Auth()->user()->id;
        $exist = UserQuiz::where(['user_id'=>$user_id])->exists();
        $alluserscore = UserQuiz::leftjoin('users','user_quizzes.user_id','=','users.id')->orderBy('user_quizzes.score','DESC')->paginate(30);
        $rankcounter = 0;
        foreach($alluserscore as $key=>$val)
        {
            $rankcounter++;
            $alluserscore[$key]['globalrank'] = $rankcounter;

        }
        if($exist)
            {

                $score = UserQuiz::select('user_id','score')->orderBy('score','DESC')->pluck('user_id')->toArray();
                 // $score2 = UserQuiz::select('user_id','score')->orderBy('score','DESC')->get();
                $uscore = UserQuiz::select('score')->where(['user_id'=>$user_id])->orderBy('score','DESC')->first();


                 $userobj = User::where('id',$user_id)->first();
                 $userobj['globalrank'] = array_search($user_id,$score)+1;
                 $userobj['score'] = intval($uscore->score);

                 return response()->json([
                        'message' => "Score has been fetched successfully.",
                        // 'score' => $score2,
                        // 'rank' => array_search($user_id,$score)+1,
                        'alluserranking' => $alluserscore,
                        'currentuserranking' => $userobj,
                        'status_code' => 200,
                      ],200);
            }
        else
            {
                $count = UserQuiz::count();
                $userobj = User::where('id',$user_id)->first();
                $userobj['globalrank'] = $count+1;
                $userobj['score'] = 0;
                return response()->json([
                    'message' => "Score has been fetched successfully.",
                        'alluserranking' => $alluserscore,
                        'currentuserranking' =>$userobj,
                        'status_code' => 200,
                  ],200);
            }



    }


    function deleteuser(Request $request)
    {
        $validation = Validator::make($request->all(),[
            'user_id' => 'required',
        ]);
        if($validation->fails()){
            $error = $validation->errors()->first();
            return response()->json([
                'errors' => $validation->errors(),
                'message' => $error,
                'status_code' => '400'
                ],400);
        }
        $del = User::where('id',$request->user_id)->delete();
        if($del)
        {
            $delquiz = UserQuiz::where('user_id',$request->user_id)->delete();
            return response()->json([
                'message' => "User has been deleted successfully",
                'status_code' => '200',
                ],200);
        }
        else
        {
            return response()->json([
                'message' => "Some thing went wrong! Try again later.",
                'status_code' => '400'
                ],400);
        }
    }

    function swipeguest(Request $request)
    {
        $validation = Validator::make($request->all(),[
            'email' => 'required',
            'photo' => 'required',
            'name'  => 'required',
        ]);
        if($validation->fails()){
            $error = $validation->errors()->first();
            return response()->json([
                'errors' => $validation->errors(),
                'message' => $error,
                'status_code' => '400'
                ],400);
        }
        $checkEmail = User::where('email', $request->email)->exists();
        if($checkEmail)
        {
            return response()->json([
                'message' => "Email already exist",
                'status_code' => '400',
                ],400);
        }
        else
        {
      
            $user = User::where('id', Auth::user()->id)->first();
            $user->name = $request->name;
            $user->email = $request->email;
            $user->photo = $request->photo;
            $user->plateform = 'Social';
            $user->password  = bcrypt('gotspace');
            if($user->save())
            {
                return response()->json([
                    'message' => "User record has been updated successfully",
                    'status_code' => '200',
                    ],200);
            }
            else
            {
                return response()->json([
                    'message' => "Some thing went wrong! Try again later.",
                    'status_code' => '400'
                    ],400);
            }
        }
    }

}

?>

