<?php
include_once __ROOT_DIR . '/libs/php-jwt/src/BeforeValidException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/ExpiredException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/SignatureInvalidException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/JWT.php';
use \Firebase\JWT\JWT;

class UserController extends Controller
{
    public function __construct($name, $request)
    {
        parent::__construct($name, $request);
    }

    /**
    * Process incoming request for the /user endpoint
    *
    * @return    Response
    */
    public function processRequest()
    {
        switch ($this->request->getHttpMethod()) {
            case 'GET':
                if ($this->request->getUriParams()) {
                    return $this->getUser($this->request->getUriParams()[0]);
                }

                return $this->getAllUsers();
                break;
            case 'PUT':
                if ($this->request->getUriParams()) {
                    return $this->updateUser(array_merge($this->request->getData(), ['id'=>$this->request->getUriParams()[0]]));
                }
                break;
        }
        return Response::errorResponse("unsupported parameters or method in users");
    }

    /**
    * Get all users in USER table
    *
    * @return    Response
    */
    protected function getAllUsers()
    {
        $users = User::getList();
        $response = Response::okResponse(json_encode($users, JSON_PRETTY_PRINT));
        return $response;
    }

    /**
    * Get a specific user in USER table based on id
    *
    * @return    Response
    */
    protected function getUser($id)
    {
        $user = User::getRow($id);
        $response = Response::okResponse(json_encode($user));
        return $response;
    }

    /**
    * Update a specific user in USER table based on id
    *
    * @return    Response
    */
    protected function updateUser($array)
    {
        try {
            $jwt_token = $this->request->getJwtToken();
            $decodedJWT = JWT::decode($jwt_token, JWT_BACKEND_KEY, array('HS256'));
        } catch (Exception $e) {
            header('WWW-Authenticate: Bearer realm="'.JWT_ISSUER.'"');
   
            $jsonResult =  json_encode(array(
                "message" => "Access denied.",
                "error" => $e->getMessage()
            ));
            return Response::unauthorizedResponse($jsonResult);
        }
        
        if ($decodedJWT->data->id != $array['id']) {
            return Response::unauthorizedResponse("You don't have access to this account.");
        }
        User::updateUser($array);
        $response = Response::okResponse('User succesfully updated !');
        return $response;
    }
}
