<?php

namespace App\Http\Controllers;

use App\Http\Requests\LoginRequest;
use App\Http\Requests\RegisterRequest;
use App\Repositories\UsersRepositoryInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Validator, DB, Hash, Mail;

class UsersController extends Controller
{
    private UsersRepositoryInterface $usersRepository;

    public function __construct(UsersRepositoryInterface $usersRepository)
    {
        $this->usersRepository = $usersRepository;
    }

    public function register(RegisterRequest $request)
    {
        $email = $request->input('email');
        $password = $request->input('password');

        $this->usersRepository->create([
            'email' => $email,
            'password' => bcrypt($password),
        ]);

        $token = auth()->attempt($request->only(['email', 'password']));

        return response()->json([
            'success' => true,
            'data' => ['token' => $token]
        ]);
    }

    /**
     * API Login, on success return JWT Auth token
     *
     * @param LoginRequest $request
     * @return JsonResponse
     */
    public function login(LoginRequest $request)
    {

        if (!$request->validated()) {
            return response()->json(['success' => false, 'error' => $request->messages()], 401);
        }

        try {
            if (!$token = auth()->attempt($request->only('email', 'password'))) {
                return response()->json(['success' => false, 'error' => 'We cant find an account with this credentials. Please make sure you entered the right information and you have verified your email address.'], 404);
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return response()->json(['success' => false, 'error' => 'Failed to login, please try again.'], 500);
        }
        // all good so return the token
        return response()->json(['success' => true, 'data' => ['token' => $token]], 200);
    }


    /**
     * Log out
     * Invalidate the token, so user cannot use it anymore
     * They have to login again to get a new token
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function logout(Request $request)
    {
        $this->validate($request, ['token' => 'required']);

        try {
            auth()->invalidate($request->input('token'));
            return response()->json(['success' => true, 'message' => "You have successfully logged out."]);
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return response()->json(['success' => false, 'error' => 'Failed to logout, please try again.'], 500);
        }
    }


    public function me()
    {
        $requestedBy = auth()->user();

        return response()->json([
            'success' => true, 'data' => $requestedBy
        ]);
    }

}