<?php

use \Firebase\JWT\JWT;

class nowconnectModel extends nowconnect
{

	/**
	 * 현재 접속자 모듈 설정을 가져옵니다
	 */
	public function getNowconnectInfo()
	{
		static $module_info;
		
		if(is_null($module_info) === true)
		{
			$output = executeQuery('nowconnect.getNowconnect');

			if(!$output->data->module_srl)
			{
				return new stdClass();
			}

			$module_info = getModel('module')->getModuleInfoByModuleSrl($output->data->module_srl);
		}

		return $module_info;
	}

	/**
	 * 토큰 생성
	 *
	 * @return string
	 */
	public function getToken()
	{
		static $payload = null;
		if(is_null($payload))
		{
			$payload = [];
		}
		
		$logged_info = Context::get('logged_info');

		$member_srl = (int) $logged_info->member_srl;

		$payload = [
			'iss' => getNotEncodedUrl(),
			'exp' => strtotime('+1 hour'),
			"iat" => getNotEncodedUrl(),
			"member_srl" => $member_srl,
			'nickname' => $logged_info->nick_name,
			'is_admin' => $logged_info->is_admin,
			'session_id' => session_id(),
			'user_id' => $member_srl,
			'ipaddress' => $_SERVER['REMOTE_ADDR']
		];

		// API 키
		$key = $this->getServerKey();

		$jwt = JWT::encode($payload, base64_decode(strtr($key, '-_', '+/')), 'HS256');

		return $jwt;
	}

	public function decodeToken($token, $key, $allowed_algs)
	{
		// API 키
		$key = $this->getServerKey();

		$decoded = JWT::decode($token, base64_decode(strtr($key, '-_', '+/')), ['HS256']);

		return $decoded;
	}


	/**
	 * 서버 KEY를 반환합니다
	 */
	public function getServerKey()
	{
		return ($this->getNowconnectInfo()->api_key);
	}
}