<?php

namespace App\Http\Controllers\Auth;

use Auth;
use App\User;
use Socialite;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SocialAuthController extends Controller
{
  /**
   * Obtain the user information from Provider.
   *
   * @return JsonResponse
   */
  public function handleProviderCallback(Request $request, $provider)
  {
      // this user we get back is not our user model, but a special user object that has all the information we need
      $providerUser = Socialite::driver($provider)->userFromToken($request->input('token'));

      // we have successfully authenticated via facebook at this point and can use the provider user to log us in.

      // for example we might do something like... Check if a user exists with the email and if so, log them in.
      $user = User::query()->firstOrNew(['email' => $providerUser->getEmail()]);

      // maybe we can set all the values on our user model if it is new... right now we only have name
      // but you could set other things like avatar or gender
      if (!$user->exists) {
          $user->name = $providerUser->getName();
          $user->avatar = $providerUser->getAvatar();
          $user->save();
      }

      /**
       * At this point we done.  You can use whatever you are using for authentication here...
       * for example you might do something like this if you were using JWT
       */

      $token = \JWTAuth::fromUser($user);

      return response()->json([
          'access_token' => $token,
          'token_type' => 'bearer',
          'expires_in' => auth()->factory()->getTTL() * 60
      ])
      ->header('Authorization', $token);
  }
}
