<?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':
                $id = $this->request->getURIParams()[0];
                return $this->getUser($id);
                break;
            
            case 'POST':
                $data = json_decode(file_get_contents("php://input"),TRUE);
                return $this->createUser($data);
                break;

            case 'PUT':
                $id = $this->request->getURIParams()[0];
                $data = json_decode(file_get_contents("php://input"),TRUE);
                return $this->updateUser($id,$data);
                break;

            case 'DELETE':
                $id = $this->request->getURIParams()[0];
                return $this->deleteUser($id);
                break;
            case 'OPTIONS':
                return Response::okresponse(json_encode("OPTIONS"));

        }
        return Response::errorResponse("unsupported parameters or method in user");
    }

    // Return one user's data
    protected function getUser($id)
    {
        $user = User::getUserById($id);
        if($user == Array()){
            $response = Response::errorInParametersResponse("User not found");
        }else{
            $response = new Response(200,json_encode($user));
        }
        return $response;
    }

    // Delete a user
    protected function deleteUser($id){
        $user = User::getUserById($id);
        if($user == Array()){
            $response = Response::errorInParametersResponse("User not found");
        }else{
            User::deleteUser($id);
            $response = Response::okResponse("User deleted");
        }
        return $response;
    }

    // Update the data of a user
    protected function updateUser($id,$data){
        try {
            $jwt_token = $this->request->getJwtToken();

            $decodedJWT = JWT::decode($jwt_token, JWT_BACKEND_KEY, array('HS256'));

            $userValues = User::getUserById($id);
            $userValues=($userValues[0]);
            if($userValues == []){
                $response = Response::errorResponse("User not found");
                return $response;
            }else{
                if(array_key_exists('USER_LOGIN',$data)){
                    $login = $data['USER_LOGIN'];
                }else{
                    $login = $userValues->USER_LOGIN;
                }

                if(array_key_exists('USER_EMAIL',$data)){
                    $email = $data['USER_EMAIL'];
                }else{
                    $email = $userValues->USER_EMAIL;
                }

                if(array_key_exists('USER_LASTNAME',$data)){
                    $lastname = $data['USER_LASTNAME'];
                }else{
                    $lastname = $userValues->USER_LASTNAME;
                }

                if(array_key_exists('USER_FIRSTNAME',$data)){
                    $firstname = $data['USER_FIRSTNAME'];
                }else{
                    $firstname = $userValues->USER_FIRSTNAME;
                }

                if(array_key_exists('USER_ROCK',$data)){
                    $rock = $userValues->USER_ROCK + $data['USER_ROCK'];
                }else{
                    $rock = $userValues->USER_ROCK ;
                }

                if(array_key_exists('USER_PAPER',$data)){
                    $paper = $userValues->USER_PAPER + $data['USER_PAPER'];
                }else{
                    $paper = $userValues->USER_PAPER ;
                }

                if(array_key_exists('USER_SCISSORS',$data)){
                    $scissors = $userValues->USER_SCISSORS + $data['USER_SCISSORS'] ;
                }else{
                    $scissors = $userValues->USER_SCISSORS;
                }

                if(array_key_exists('USER_WIN',$data)){
                    $win = $userValues->USER_WIN + $data['USER_WIN'] ;
                }else{
                    $win = $userValues->USER_WIN;
                }

                if(array_key_exists('USER_LOST',$data)){
                    $lost = $userValues->USER_LOST + $data['USER_LOST'] ;
                }else{
                    $lost = $userValues->USER_LOST;
                }

                $user = User::updateUser(array("id" => $id, "login" => $login,"email" => $email,"lastname" => $lastname,"firstname" => $firstname, "paper" => $paper, "scissors" => $scissors, "rock" => $rock, "win" => $win, "lost" => $lost));
                $response = new Response(200,json_encode($user));
                return $response;
            }

        } catch (Exception $e){
            header('WWW-Authenticate: Bearer realm="'.JWT_ISSUER.'"');

            $jsonResult =  json_encode(array(
                "message" => "Access denied.",
                "error" => $e->getMessage()
            ));
            return Response::unauthorizedResponse($jsonResult);
        }
        
    }

    // Create a new user in the database
    protected function createUser($data)
    {
        if(array_key_exists("USER_LOGIN", $data) && array_key_exists("USER_PASSWORD", $data) && array_key_exists("USER_ROLE", $data) && array_key_exists("USER_EMAIL", $data) && array_key_exists("USER_LASTNAME", $data) && array_key_exists("USER_FIRSTNAME", $data)){
            $user = User::createUser(array( "login" => $data['USER_LOGIN'], "password" => $data['USER_PASSWORD'], "role" => $data['USER_ROLE'], "email" => $data['USER_EMAIL'],"lastname" => $data['USER_LASTNAME'],"firstname" => $data['USER_FIRSTNAME']));
            $response = new Response(200,json_encode($user));
        }else{
            $response = Response::errorInParametersResponse("Parameters missing");
        }
        
        return $response;
    }
}