<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
  /**
   * Create a new AuthController instance.
   *
   * @return void
   */
  public function __construct()
  {
      $this->middleware('auth:api', ['except' => ['login','refresh']]);
  }

  /**
   * Get a JWT token via given credentials.
   *
   * @param  \Illuminate\Http\Request  $request
   *
   * @return \Illuminate\Http\JsonResponse
   */
  public function login(Request $request)
  {
      $credentials = $request->only('email', 'password');

      if ($request->rememberMe) {
           auth()->factory()->setTTL(30 * 24 * 120);
      }

      if ($token = auth()->attempt($credentials)) {
        if (auth()->user() instanceof MustVerifyEmail && !auth()->user()->hasVerifiedEmail()) {
            return response()->json([
                'errors' => [
                    'message' => [
                        __('errors.email_not_verified'),
                    ],
                ],
                'message' => __('errors.email_not_verified'),
            ], 403);
        }

        if (auth()->user() instanceof MustVerifyEmail && !auth()->user()->hasVerifiedEmail()) {
            return response()->json([
                'errors' => [
                    'message' => [
                        __('errors.email_not_verified'),
                    ],
                ],
                'message' => __('errors.email_not_verified'),
            ], 403);
        }
        return $this->respondWithToken($token);
    }
    return response()->json(['error' => 'Unauthorized'], 401);
  }

  /**
   * Get the authenticated User
   *
   * @return \Illuminate\Http\JsonResponse
   */
  public function user()
  {
      return response()->json(auth()->user());
  }

  /**
   * Log the user out (Invalidate the token)
   *
   * @return \Illuminate\Http\JsonResponse
   */
  public function logout()
  {
      auth()->logout();

      return response()->json(['message' => 'Successfully logged out']);
  }

  /**
   * Refresh a token.
   *
   * @return \Illuminate\Http\JsonResponse
   */
  public function refresh()
  {
      return $this->respondWithToken(auth()->refresh());
  }

  /**
   * Get the token array structure.
   *
   * @param  string $token
   *
   * @return \Illuminate\Http\JsonResponse
   */
  protected function respondWithToken($token)
  {
      return response()->json([
          'access_token' => $token,
          'token_type' => 'bearer',
          'expires_in' => auth()->factory()->getTTL() * 60
      ])
      ->header('Authorization', $token);
  }
}
