<?php
class LoginController{
    private $model;

    function __construct(){
        $this->model = new LoginModel();
    }

    /**
     * get JWT Token for app
     * @return json token
     */
    public function getToken(){
        global $user;
        if(isset($_POST['login'])){
            $login = $user->login($_POST['username'], $_POST['password'], true);
            $login['userInfo'] = $user->getUserInfo();
            $login['serverTime'] = time();
            echo json_encode($login);
        }else{
            echo json_encode(['status' => 'fail', 'errorMessage' => 'invalid request']);
        }
    }

    /**
     * validate the token
     * @return json status => status for token validation, errorMessage => error message
     */
    public function validateToken(){
        global $user;
        if($user->isLoggedIn()){
            $refreshToken = $user->getRefreshToken();
            $message = ['status' => 'success', 'userInfo' => $user->getUserInfo(), 'refreshToken' => $refreshToken, 'serverTime' => time()];
        }else{
            $message = ['status' => 'fail', 'errorMessage' => $user->getErrorMessage()];
        }

        echo json_encode($message);
    }

    public function refreshToken(){
        global $user;

        $refreshToken = isset($_REQUEST['refreshToken']) ? $_REQUEST['refreshToken'] : '';
        $lastActivity = isset($_REQUEST['lastActivity']) ? $_REQUEST['lastActivity'] : '1000';
        $message = $user->refreshToken($refreshToken, $lastActivity);
        $message['serverTime'] = time();
        $message['userInfo'] = $user->getUserInfo();

        echo json_encode($message);
    }

    /**
     * get allowed modues for user type
     * @return json modules array
     */
    public function getModules(){
        global $user, $route;
        if($user->isLoggedIn()){
            echo json_encode(['modules' => $route::getModules()]);
        }else{
            echo json_encode(['modules' => []]);
        }
    }

    /**
     * generate new token for user
     * @return json update message
     */
      public function forgotPassword(){
        $mail = isset($_POST['mail']) ? $_POST['mail'] : '';
        echo json_encode($this->model->forgotPassword($mail));
      }

      public function changePassword(){
          $token = isset($_REQUEST['token']) ? $_REQUEST['token'] : '';
          $passwords = [
              'newPassword' => isset($_REQUEST['newPassword']) ? $_REQUEST['newPassword'] : '',
              'confirmPassword' => isset($_REQUEST['confirmPassword']) ? $_REQUEST['confirmPassword'] : ''
          ];
          echo json_encode($this->model->changePassword($token, $passwords));
      }
}
?>
