<?php

namespace App\Http\Controllers\Auth;

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

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 = $this->validateCredentials($request);

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

		if (!$token = auth()->attempt($credentials)) {
            return response()->json([
                'errors' => [
                        'message' => [
                                'Contraseña incorrecta',
                        ],
                ],
                'message' => __('errors.unauthorized'),
            ], 401);
        }
        return $this->respondWithToken($token);
  }

  /**
   * 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);
  }

		/**
     * Get credentials.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function validateCredentials(Request $request)
    {
        if(is_numeric($request->get('email'))){
            $request->validate([
                'email' => [
                    new ExistsPhone(__('validation.attributes.phone_number')),
                    'regex:/^([0-9\s\-\+\(\)]*)$/',
                    'min:10',
                    'max:11',
                ],
                'password' => [
                    'required',
                    'min:6',
                ]
            ]);
            return ['phone_number'=>'+52'.$request->get('email'),'password'=>$request->get('password')];
        }
        else {
            $request->validate([
                'email' => 'required|exists:users,email|email|max:255',
                'password' => 'required|min:5',
            ]);
            return ['email' => $request->get('email'), 'password'=>$request->get('password')];
        }
    }
}
