<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\API\V1\BaseController as BaseController;
use App\Models\FirebaseUid;
// use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Kreait\Firebase;
use Firebase\Auth\Token\Exception\InvalidToken;
use Carbon\Carbon;
use App\Models\User;
use App\Models\UserDevice;

class FirebaseController extends BaseController
{
    public function verifyToken(Request $request) {
  
        // Launch Firebase Auth
        $auth = app('firebase.auth');
        // $auth = (new Firebase\Factory())->create();
        // Retrieve the Firebase credential's token
        // $idTokenString = $request->input('Firebasetoken');
        $idTokenString = $request->firebase_token;
        
      
        
        try { // Try to verify the Firebase credential token with Google
          
          $verifiedIdToken = $auth->verifyIdToken($idTokenString);
          
        } catch (\InvalidArgumentException $e) { // If the token has the wrong format     

          return $this->sendError('Unauthorised.', ['error'=>'Unauthorized - Can\'t parse the token: '.$e->getMessage()],401);
          
        } catch (InvalidToken $e) { // If the token is invalid (expired ...)

          return $this->sendError('Unauthorised.', ['error'=>'Unauthorized - Token is invalide: ' . $e->getMessage()],401);          

        }
        
        $uid = $verifiedIdToken->getClaim('sub');

        if($uid)
        {
          $user = $auth->getUser($uid);
        
          // Retrieve the user model linked with the Firebase UID
          $userInfo = User::where('firebase_user_id',$uid)->first();
        
          if($userInfo)
          {
            if($userInfo->isApproved == 1)
            {
              // Once we got a valid user model
              // Create a Personnal Access Token
              $tokenResult = $userInfo->createToken('suhu');
                
              // Store the created token
              $token = $tokenResult->token;

              // Add a expiration date to the token
              $token->expires_at = Carbon::now()->addWeeks(1);

              // Save the token to the user
              $token->save();

              $device = UserDevice::registerDevices($request);
              // return $device;
              $success = [
                'user_id' => $userInfo->id,
                'access_token' => $tokenResult->accessToken,
                'token_type' => 'Bearer',
                'expires_at' => Carbon::parse(
                      $tokenResult->token->expires_at
                    )->toDateTimeString()
              ];

              return $this->sendResponse($success, 'User login successfully.',200);
            }
            else if($userInfo->register_page == 1)
            {
              $success = [
                'redirect_to' => 'register_first_page',
                'redirect_url' => URL('api/v1/driver-register')
              ];
              return $this->sendResponse($success, 'New User',200);
            }
            else if($userInfo->register_page == 2)
            {
              $success['user_id'] =  $userInfo->id;
              $success['approve_status'] = 'Pending'; 
              $success['redirect_to'] = 'register_second_page';
              $success['redirect_url'] = URL('api/v1/add-vehicle'); 
              return $this->sendResponse($success, 'New User',200);
            }
            else if($userInfo->register_page == 3)
            {
              $success['user_id'] =  $userInfo->id;
              $success['approve_status'] = 'Pending'; 
              $success['redirect_to'] = 'register_third_page';
              $success['redirect_url'] = URL('api/v1/list-near-by-preferred-area');
              return $this->sendResponse($success, 'New User',200);
            }
            else
            {
              return $this->sendError('Not Approved.', ['error'=>'Not Approved - Profile Under Document Verification: '],400);          
            }
          }
          else
          {          
            $exist_firebase_token = FirebaseUid::find($uid);
            if(!$exist_firebase_token)
            {
              $createFBUid =  FirebaseUid::create([
                'firebase_uid'=>$uid,
                ]);
            }
            
            $success = [
              'redirect_to' => 'register_first_page',
              'redirect_url' => URL('api/v1/driver-register')
            ];
            return $this->sendResponse($success, "Verified. New User",200);
          }
        }
        else
        {
          $failed = [
            'redirect_to' => 'verify_firebase_token_page',
            'redirect_url' => URL('api/v1/verify-firebase-token')
          ];
          return $this->sendError($failed, "Not Verified. New User",400);
        }
    }    
}
