<?php
class mytoken
{
	function __construct()
    {
       
        $this->headers = getallheaders();
        global $sgbd;
        $this->db = $sgbd;
        $this->TimeToken = 24*3600*30;
      
    }
  
    function getToken()
    {
        $headers = $this->headers;
		
		## AUTHENTIFICATION 
		$autorisation = $headers['Authorization'];
		
		$method = $_SERVER['REQUEST_METHOD'];
		if($method!='POST')
		{
			header('HTTP/1.0 405 Method not allowed');
			$return['error'] =apiError(405,"Method $method not allowed");
			local_json($return);
		}
		
		$basics = explode(' ',$autorisation);
		$basics[0] = trim(strtolower($basics[0]));
		
		$subscription_base64 = trim($basics[1]);
		$subscription = base64_decode($subscription_base64);
		$subscriptions = explode(':',$subscription);
		
		if( $basics[0]!='basic')
		{
			header('HTTP/1.0 401 Unauthorized');
			$return['error'] =apiError(401,"Invalide authorization Type");
			local_json($return);
		}
		if(count($subscriptions)!=2)
		{
			header('HTTP/1.0 401 Unauthorized');
			$return['error'] =apiError(401,"Unavailables suscriptions parameters");
			local_json($return);
		}
		
		$apiuser = $this->db->query("select * from api_users where api_user='".$subscriptions[0]."' and api_key='".$subscriptions[1]."'")->row_array();
		
		if(empty($apiuser['agent_id']))
		{
			header('HTTP/1.0 401 Unauthorized');
			$return['error'] =apiError(401,"Invalids suscriptions parameters");
			local_json($return);
		}
		
		## CREATION D'UN token
		$expire = datetime();
 
     
		uses_functions('random');
        
		$token = $this->db->query("select * from api_tokens where date_expired>='$expire' and agent_id='".$apiuser['agent_id']."'")->row_array();
       
		$nexpire = date('Y-m-d H:i:s',time()+$this->TimeToken-date('Z')+3600);
		
		if($token['date_expired']>$nexpire) unset($token);
		if($token['date_expired']<=datetime()) unset($token);
		
		if(empty($token))
		{
			$this->db->query("delete from api_tokens where agent_id = '".$apiuser['agent_id']."' or user_id = '".$apiuser['user_id']."'");
			$ka = rand(50,63);
			$tock = random_text($ka);
			$k=0;
            $query = "select * from api_tokens where token!='$tock'";
			
			while($vtock = $this->db->query($query)->row_array())
			{
				$k++;
				if($k>100)break;
			}
		
			$query = "INSERT INTO `api_tokens`(`user_id`, `agent_id`, `token`, `date_expired`, `status`) VALUES ('".$apiuser['user_id']."','".$apiuser['agent_id']."','$tock','$nexpire','1')";
          
			$this->db->query($query);
			$token = $this->db->query("select * from api_tokens where date_expired>='$expire' and agent_id='".$apiuser['agent_id']."'")->row_array();
		}
		if(empty($token))
		{
			header('HTTP/1.0 401 Unauthorized');
			$return['error'] =apiError(401,"Operation to have access token failed.");
			local_json($return);
		}
		
		$reponse['access_token'] = $token['token'];
		$reponse['token_type'] = 'bearer';
		$reponse['expires_in'] = strtotime($token['date_expired'])-strtotime(datetime());
		$result['data']= $reponse;
		local_json($result);
		
    }
   
}
?>