<?php

namespace App\Http\Controllers;

use App\DimxDim;
use App\SysxUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Support\Facades\Auth;

class UserController extends ResponseController
{
    //
    public function login(Request $request)
    {
        $credentials = ['username' => $request->username, 'password_hash' => $request->password];
        $user = SysxUser::where('username','=',$request->username)->first();
        try {
            if($user != null){
                    if (!$token = \JWTAuth::attempt($credentials)) {
                        return response()->json(['error' => 'invalid_credentials'], 400);
                    }
            }else{
                return $this->errorResponse(400,null,'User doesn`t exist');
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'could_not_create_token'], 500);
        }
        $dim = DimxDim::where('user_id','=',$user->user_id)->first([
            "dimx_dim.dim_id as dimId",
            "dimx_dim.nama as nama",
            "dimx_dim.user_id as userId"
        ]);
        if($user->authentication_method_id == 2){
            $user1 = ["user" => $dim,"token" => $token,"role" => 1];
        }else{
            $user1 = ["user" => $dim, "token" => $token, "role" => 0];
        }
        return $this->successResponse(200,$user1);
    }

    public function getAuthenticatedUser()
    {
        try {
            if (!$user = \JWTAuth::parseToken()->authenticate()) {
                return response()->json(['user_not_found'], 404);
            }
        } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
            return response()->json(['token_expired'], $e->getStatusCode());
        } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
            return response()->json(['error'=>'token_invalid'], 404);
        } catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
            return response()->json(['error'=>'absent'], 404);
        }
        $dim = DimxDim::where('user_id','=',$user->user_id)->first();
        return $this->successResponse(200,$dim);
    }

    public function logout(){
        auth()->logout();
        JWTAuth::invalidate(JWTAuth::parseToken());
        return response()->json(['message' => 'Successfully logged out']);
    }

    public function guard(){
        return Auth::guard();
    }
}
