<?php

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
        $verifyArray = $this->request->verifyJwtToken();
        if ($verifyArray['message']!=="Valid token.") {
            return Response::unauthorizedResponse($jsonResult);
        }
        // Auth phase
        if ($verifyArray['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;
    }
}
