<?php

namespace App\Http\Controllers\User;

use App\Helpers\ValidationHelper;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

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

    /**
     * Get a JWT token via given credentials.
     *
     *
     * @return JsonResponse
     */
    public function login(Request $request)
    {
        $validator = ValidationHelper::validator($request, [
            'email_or_phone' => 'required',
            'password' => 'required',
        ]);
        if ($validator->fails()) {
            return validationErrorResponse($validator);
        }
        $fieldType = filter_var($request->email_or_phone, FILTER_VALIDATE_EMAIL) ? 'email' : 'phone';
        if ($token = $this->guard()->attempt([
            $fieldType => $request->email_or_phone,
            'password' => $request->password,
            'status' => '1',
        ])) {
            return $this->respondWithToken($token);
        }

        return response()->json(['error' => 'Unauthorized'], 401);
    }

    /**
     * Get the authenticated User
     *
     * @return JsonResponse
     */
    public function me()
    {
        $user = $this->guard()->user();

        return response()->json([
            'profile' => asset($user->profile),
            'name' => $user->name,
            'email' => $user->email,
            'phone' => $user->phone,
            'role' => $user->role,
        ]);
    }

    /**
     * Log the user out (Invalidate the token)
     */
    public function logout(): JsonResponse
    {
        $this->guard()->logout();

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

    /**
     * Refresh a token.
     */
    public function refresh(): JsonResponse
    {
        return $this->respondWithToken($this->guard()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string  $token
     */
    protected function respondWithToken($token): JsonResponse
    {
        $user = $this->guard()->user();

        return response()->json([
            'access_token' => $token,
            'profile' => asset($user->profile),
            'name' => $user->name,
            'email' => $user->email,
            'phone' => $user->phone,
            'role' => $user->role,
            'token_type' => 'bearer',
            'expires_in' => $this->guard()->factory()->getTTL() * 72,
        ]);
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return Guard
     */
    public function guard()
    {
        return Auth::guard();
    }
}
