<?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()
    {
        $httpMethod=$this->request->getHttpMethod();
        $uriParams=$this->request->getUriParams();

        switch ($httpMethod) {
            case 'GET':
                // If there is a uriParams, it is the /user/{id} endpoint
                if ($uriParams) {
                    return $this->getUser($uriParams[0]);
                }
                // Else, it is the /user endpoint
                return $this->getAllUsers();
                break;
            case 'PUT':
                // If there is a uriParams, it is the /user/{id} endpoint
                if ($uriParams) {
                    $body = $this->request->getData();
                    return $this->updateUser(array_merge($body, ['id'=>$uriParams[0]]));
                }
                break;
        }
        $message = json_encode(["message" => "unsupported parameters or method in users"]);
        return Response::errorResponse($message);
    }

    /**
    * 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)
    {
        // Token phase
        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);
        }
        
        // Auth phase
        if ($decodedJWT->data->id != $array['id']) {
            $message = json_encode(["message" => "You don't have access to this account."]);
            return Response::unauthorizedResponse($message);
        }

        // Update phase
        User::updateUser($array);

        $message = json_encode(["message" => 'User succesfully updated !']);
        $response = Response::okResponse($message);

        return $response;
    }
}
