<?php

class URCJWTWork {
	
	public static function genJWTToken($username, $id, $level) {

		$key = Config::get('editorenv.jwtKey');

		$token = array(
		    "iss" => Config::get('editorenv.editor_addr'),
		    "sub" => $username,
		    "iat" => time(),
			"exp" => time() + Config::get('editorenv.jwtTTL'),
			"usr_id" => $id,
			"usr_level" => $level
		);
		
		return JWT::encode($token, $key);
	}

	public static function chkJWTToken(&$username, &$id, &$level, &$errMsg, &$errNo) {

		$aHeaders = getallheaders();
		if(!array_key_exists('Authorization', $aHeaders)) {
			$errMsg = 'You must sign in';
			$errNo = 401;
			return false;
		}

		$authorization = $aHeaders['Authorization'];
		if(strncmp($authorization, "Bearer ", 7)) {
			$errMsg = 'You must sign in';
			$errNo = 401;
			return false;
		}
		
		try {
			$token = substr($authorization, 7);	
			if(URCJWTWork::parseJWTToken($token, $username, $id, $level, $errMsg, $errNo) === false) {
				return false;
			}
	        
	    } catch (Exception $e) {
	    	if ($e->getMessage() === 'Expired Token') {
	    		$errMsg = 'Expired Token';
				$errNo = 401;
				return false;
	    	} else {
	    		$errMsg = 'user not found';
				$errNo = 404;
				return false;
	    	}
	    }

	    return true;
	}

	public static function parseJWTToken(&$token, &$username, &$id, &$level, &$errMsg, &$errNo) {

		$key = Config::get('editorenv.jwtKey');

        $payload = (array) JWT::decode($token, $key);
        //ErrorDebug::write(json_encode($payload));
		if(!isset($payload['sub']) || !isset($payload['usr_id'])
			|| !isset($payload['usr_level']) || !isset($payload['iss'])) {
			$errMsg = 'user not found';
			$errNo = 404;
			return false;
        }

        if($payload['iss'] !== Config::get('editorenv.editor_addr')) {
        	$errMsg = 'user not found';
			$errNo = 404;
			return false;
        }

        $username = $payload['sub'];
        $id = (int)$payload['usr_id'];
        $level = (int)$payload['usr_level'];

	    return true;
	}

	public static function genJWTTokenDealer($dealer_id, $dealer_grp_id, $dealer_grp_name) {

		$key = Config::get('editorenv.jwtKey');

		$token = array(
		    "iss" => Config::get('editorenv.editor_addr'),
		    "sub" => $dealer_id,
		    "iat" => time(),
			"exp" => time() + Config::get('editorenv.jwtTTL'),
			"group_id" => $dealer_grp_id,
			"company" => $dealer_grp_name,
			"usr_level" => URCValues::LOGIN_INSTALLER
		);
		
		return JWT::encode($token, $key);
	}

	public static function getTokenFromHeader() {
		
		$aHeaders = getallheaders();
		if(!array_key_exists('Authorization', $aHeaders)) {
			//$errMsg = 'You must sign in';
			//$errNo = 401;
			return false;
		}

		$authorization = $aHeaders['Authorization'];
		if(strncmp($authorization, "Bearer ", 7)) {
			//$errMsg = 'You must sign in';
			//$errNo = 401;
			return false;
		}
		
		return substr($authorization, 7);
	}

	public static function chkJWTTokenDealer(&$dealer_id, &$dealer_grp_id, &$dealer_grp_name, &$errMsg, &$errNo) {

		$aHeaders = getallheaders();
		if(!array_key_exists('Authorization', $aHeaders)) {
			$errMsg = 'You must sign in';
			$errNo = 401;
			return false;
		}

		$authorization = $aHeaders['Authorization'];
		if(strncmp($authorization, "Bearer ", 7)) {
			$errMsg = 'You must sign in';
			$errNo = 401;
			return false;
		}
		
		$key = Config::get('editorenv.jwtKey');

		try {
			$token = substr($authorization, 7);	
	        $payload = (array) JWT::decode($token, $key);

	        //ErrorDebug::write(json_encode($payload));
	    	if(!isset($payload['sub']) || !isset($payload['group_id']) || !isset($payload['company'])
				|| !isset($payload['usr_level']) || !isset($payload['iss'])) {
				$errMsg = 'user not found';
				$errNo = 404;
				return false;
	        }

	        if($payload['iss'] !== Config::get('editorenv.editor_addr')) {
	        	$errMsg = 'user not found';
				$errNo = 404;
				return false;
	        }

	        $level = (int)$payload['usr_level'];
	        if($level !== URCValues::LOGIN_INSTALLER) {
	        	$errMsg = 'user not found';
				$errNo = 404;
				return false;
			}
			
			$dealer_id = $payload['sub'];
			$dealer_grp_id = $payload['group_id'];
			$dealer_grp_name = $payload['company'];	

	    } catch (Exception $e) {
	    	if ($e->getMessage() === 'Expired Token') {
	    		$errMsg = 'Expired Token';
				$errNo = 401;
				return false;
	    	} else {
	    		$errMsg = 'user not found';
				$errNo = 404;
				return false;
	    	}
	    }

	    return true;
	}
};

