<?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);
    }

    // ==============
    // Actions
    // ==============

    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");
    }

    protected function getAllUsers()
    {
        $users = User::getList();
        $response = Response::okResponse(json_encode($users));
        //var_dump($json);die;
        // TODO
        return $response;
    }

    protected function getUser($id){
        $user = User::getRow($id);
        $response = Response::okResponse(json_encode($user));
        return $response;
    }
    protected function updateUser($array){
        try {
            //var_dump($array);die;
            $jwt_token = $this->request->getJwtToken();
            // echo "jwt = $jwt_token";
            $decodedJWT = JWT::decode($jwt_token, JWT_BACKEND_KEY, array('HS256'));
            
            if($decodedJWT->data->id != $array['id']){
                throw new Exception("You don't have access to this account.", 1);
            } 
            
            User::updateUser($array);
   
         } catch (Exception $e){
            header('WWW-Authenticate: Bearer realm="'.JWT_ISSUER.'"');
   
            $jsonResult =  json_encode(array(
                "message" => "Access denied.",
                "error" => $e->getMessage()
            ));
            return Response::unauthorizedResponse($jsonResult);
         }
         $response = Response::okResponse('User succesfully updated !');
         return $response;
    }
}