<?php

class Jwt
{

	public $secret = 'that is my secret key' ;
	public function encode(array $arr=[])
	{
		$header['alg']='HS256';
		$header['typ']='JWT';
		$header['craet_timestamp']=time();
		$header['craet_date']=date('Y-m-d H:i:s');
		$header['valid_date']=date('Y-m-d H:i:s',time()+86400*365);
		$arr['iss']="http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
		$header= str_replace("=","",strtr(base64_encode(json_encode($header)),'+/','-_'));
		$payload= str_replace("=","",strtr(base64_encode(json_encode($arr)),'+/','-_'));
		$token=$header.'.'.$payload;
		$signature=hash_hmac('sha256',$token,$this->secret);
		$sign= str_replace("=","",strtr(base64_encode(json_encode($signature)),'+/','-_'));
		return $token=$token.".".$sign;
	}


	public  function verify($token)
	{
		$arr=explode('.',$token);
		if(count($arr)===3)
		{
			$len= strlen($arr[0])%4;
			if($len)
			{
				$pad=4-$len;
				$arr[0].=str_repeat('=',$pad);
			}
			$arr[0]=strtr($arr[0],'-_','+/');
			$arr[0]=base64_decode($arr[0]);
			$header=json_decode($arr[0],true);
			
			
			$len= strlen($arr[1])%4;
			if($len)
			{
				$pad=4-$len;
				$arr[1].=str_repeat('=',$pad);
			}
			$arr[1]=strtr($arr[1],'-_','+/');
			$arr[1]=base64_decode($arr[1]);
			$payload=json_decode($arr[1],true);
				
			$header= str_replace("=","",strtr(base64_encode(json_encode($header)),'+/','-_'));
			$payload= str_replace("=","",strtr(base64_encode(json_encode($payload)),'+/','-_'));
			$token=$header.'.'.$payload;
			$signature=hash_hmac('sha256',$token,'secret');
			$sign= str_replace("=","",strtr(base64_encode(json_encode($signature)),'+/','-_'));
			
			if($sign==$arr[2])
			{
				return true;
			}
			else
			{
				return false;
			}
			
		}
		else
		{
			return false;
		}


	}


	public function decode($token)
	{
		$arr=explode('.',$token);
		if(count($arr)===3)
		{
			$len= strlen($arr[0])%4;
			if($len)
			{
				$pad=4-$len;
				$arr[0].=str_repeat('=',$pad);
			}
			$arr[0]=strtr($arr[0],'-_','+/');
			$arr[0]=base64_decode($arr[0]);
			$header_orig=$header=json_decode($arr[0],true);
			
			
			$len= strlen($arr[1])%4;
			if($len)
			{
				$pad=4-$len;
				$arr[1].=str_repeat('=',$pad);
			}
			$arr[1]=strtr($arr[1],'-_','+/');
			$arr[1]=base64_decode($arr[1]);
			$payload_orig=$payload=json_decode($arr[1],true);
				
			$header= str_replace("=","",strtr(base64_encode(json_encode($header)),'+/','-_'));
			$payload= str_replace("=","",strtr(base64_encode(json_encode($payload)),'+/','-_'));
			$token=$header.'.'.$payload;
			$signature=hash_hmac('sha256',$token,'secret');
			$sign= str_replace("=","",strtr(base64_encode(json_encode($signature)),'+/','-_'));
			
			if($sign==$arr[2])
			{
					$return_arr['header']=($header_orig);
					$return_arr['payload']=($payload_orig);
					return ($return_arr);
			}
			else
			{
				return false;
			}
			
		}
		else
		{
			return false;
		}


	}

}
