<?php

namespace App\Http\Controllers\APIs;

use App\Http\Controllers\Controller;
use App\Models\User;
use Hash;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
use Validator;

class UsersController extends Controller
{
    public function register(Request $request){

        $validator = Validator::make($request->all(),[
            'name' =>'required|string|max:255',
            'email' =>'required|string|email|max:255|unique:users,email',
            'password' =>'required|string|min:8|max:12',
        ]);

        if($validator->fails()){
            return response()->json(['error'=>$validator->errors()],422);
        }

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' =>  Hash::make($request->password),
        ]);

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

        return response()->json(['message' => 'User Registered',
           'user' => $user,
           'token' => $token
    ], 201);

    }

    public function login(Request $request){

        $request-> validate([

            'email' =>'required|email',
            'password' =>'required|string|min:8|max:12',
        ]);

        $user = User::where('email', $request->email) ->first();

        if(!$user){
            return response()->json(['error'=>'Invalid Email'],401);
        }elseif(!Hash::check($request->password, $user->password)){
            return response()->json(['error'=>'Incorrect Password'],401);
        }


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

        return response()->json(['message' => 'Login Successful',
           'user' => $user->makeHidden(['password']),
           'token' => $token
    ], 201);

    }

    public function dashboard(Request $request){

        try{
            $user = JWTAuth::parseToken()->authenticate();
        }catch(\Tymon\JWTAuth\Exceptions\TokenInvalidException $e){
            return response()->json(['error'=>'Token is Invalid'],401);
        }
        catch(\Tymon\JWTAuth\Exceptions\TokenExpiredException $e){
            return response()->json(['error'=>'Token Has Expired'],401);
        }

        return response()->json(['message' => 'Login Successful',
           'user' => $user,
           'message' => 'Welcome to Dashboard'
    ], 201);

    }

    public function logout(Request $request){

        try{
            $token = JWTAuth::getToken();

            if(!$token){
                return response()->json(['error'=>'Token is Provided'],401);
            }

            JWTAuth::invalidate($token);
            return response()->json(['message' => 'Logout Successful'], 401);
        }
        catch(\Tymon\JWTAuth\Exceptions\TokenExpiredException $e){
            return response()->json(['error'=>'Token Has Expired'],401);
        }
    }
}
