<?php

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;
use Lcobucci\JWT\Parser;

function Unauthorized()
{
	header('HTTP/1.0 401 Unauthorized');
}

function createToken($priv_no, $user_id, $user_name, $roles, $menus, $ExpirationTime, $ClientID)
{
	$priv_no        = isset($priv_no) ? $priv_no : 0;
	$ClientID       = isset($ClientID) ? $ClientID : 0;
	$ExpirationTime = isset($ExpirationTime) ? $ExpirationTime : 30;
	$user_id        = isset($user_id) ? $user_id : '';
	$user_name        = isset($user_name) ? $user_name : '';
	$roles = isset($roles) ? $roles : [];
	$menus = isset($menus) ? $menus : [];
	$signer         = new Sha256();
	//建立token
	$token = (new Builder())->setIssuer('http://sunware.com.tw/') // Configures the issuer (iss claim)
		//->setAudience($_SERVER['REMOTE_ADDR'])  Configures the audience (aud claim)
		->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
		->setNotBefore(time()) // Configures the time that the token can be used (nbf claim)
		->setExpiration((time() + $ExpirationTime)) // Configures the expiration time of the token (nbf claim)
		->setId($ClientID, true) // Configures the id (jti claim), replicating as a header item
		->set('priv_no', $priv_no) // Configures a new claim, called "priv_no"
		->set('user_id', $user_id) // Configures a new claim, called "uid"
		->set('user_name', $user_name) // Configures a new claim, called "uid"
		->set('roles', $roles) // Configures a new claim, called "roles"
		->set('menus', $menus) // Configures a new claim, called "menus"
		->sign($signer, 'sunware') // creates a signature using "testing" as key
		->getToken(); // Retrieves the generated token
	return $token;
}

function parseToken($jwt)
{
	try {
		$token = (new Parser())->parse((string) $jwt);
	} catch (\RunException $e) {
		return false;
	} catch (\OutOfBoundsException $e) {
		return false;
	} catch (\InvalidArgumentException $e) {
		return false;
	} catch (\RuntimeException $e) {
		return false;
	}

	return $token;
}

function validationData($token)
{
	$data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
	$data->setIssuer('http://sunware.com.tw/');
	$data->setId(_Login_Key);
	$signer = new Sha256();

	if ($token->validate($data) && $token->verify($signer, 'sunware')) {
		return createToken($token->getClaim('priv_no'), $token->getClaim('user_id'), $token->getClaim('roles'), 120, _Login_Key);
	} else {
		return false;
	}
}

function headerToken()
{
	$token = '';
	$headers = apache_request_headers();
	if (isset($headers['Authorization'])) {
		$matches = array();
		preg_match('/Bearer\s(\S+)/', $headers['Authorization'], $matches);
		if (isset($matches[1])) {
			$token = $matches[1];
		}
	}

	return $token;
}

/* PHP 7 */
spl_autoload_register(function ($class) {
	if (file_exists(__DIR__ . '\\' . $class . '.php')) {
		require_once($class . '.php');
	} else {
		if (file_exists(__DIR__ . '\\..\\' . $class . '.php')) {
			require_once($class . '.php');
		} else {
			throw new Exception("connt find " . __DIR__ . $class . " class, load failuer");
		}
	}
});
