<?php
class Token_model extends CI_Model {

    public function __construct(){
        parent::__construct();
		$this->Headers = getallheaders();
      
        
        if($_SERVER['HTTPS']!='on' && ENVIRONMENT!='development' )
        {
            header('HTTP/1.0 401 Unauthorized');
            $return['error'] =apiError(500,"You must use a secure link.");
            local_json($return);
        }
        
    }
    public function valideToken($login="")
    {
        
        $token = $this->getAutorization('bearer');
        $expire = date('Y-m-d H:i:s',strtotime(datetime())-200);
        $val = $this->db->query("select * from api_tokens where token='$token' and date_expired>'$expire'")->row_array();
     
		if(empty($val))
		{
			header('HTTP/1.0 401 Unauthorized');
			$return['error'] =apiError(304,"The security token is not valid.");
			local_json($return);
        }
        
     

		## CREATION D'UN TOCKEN
        $query = "select api_users.ip_address,api_users.*,api_users.user_id as user_id,agents.status from api_users 
        left join agents on agents.agent_id =  api_users.agent_id   
        where api_users.agent_id='".$val['agent_id']."'";
     
      
		$user = $this->db->query($query)->row_array();
       
       
		if(empty($user))
		{
			header('HTTP/1.0 401 Unauthorized');
			$return['error'] =apiError(304,"This account is not active.");
			local_json($return);
        }
       
		if(empty($user['status']))
		{
			header('HTTP/1.0 401 Unauthorized');
			$return['error'] =apiError(304,"This account is not active.");
			local_json($return);
        }
        global $log_sgdb;
      
      $query = "select * from api_servers_logs where ip_address ='".get_ip()."' and agent_id ='".$user['agent_id']."' ";
      
        $test_ip = $log_sgdb->query($query)->row_array();
       
        if(empty($test_ip))
        {
            $query =  "INSERT INTO `api_servers_logs`( `user_id`, `agent_id`,`ip_address`, `server_name`,`os`, `browser`, `date_begin`, `date_end`, `failed`, `status`, `Autorize`) 
                        VALUES ('".$user['user_id']."','".$user['agent_id']."','".get_ip()."','','".getOS()."','".getBrowser() ."','".datetime()."','".datetime()."','1','None','0')";
  
            $log_sgdb->query($query);
           /* header('HTTP/1.0 401 Unauthorized');
            $return['error'] =apiError(304,"This IP address ".get_ip()." is not authorized");
            local_json($return);*/
        }
        elseif(!$test_ip['Autorise'])
        {
            $query =  "UPDATE `api_servers_logs` SET failed =failed+1, date_end='".datetime()."' where ip_address = '".get_ip()."'";
            $log_sgdb->query($query);
            /*header('HTTP/1.0 401 Unauthorized');
            $return['error'] =apiError(304,"This IP address ".get_ip()." is not authorized by customer");
            local_json($return);*/
        } 
      
        $this->agent_id =
        $this->agent_id =
        $this->user_id = $user['agent_id'];
        $this->MerchantKey = $user['merchant_key'];
       
       
    }
    public function getData($type="")
    {
        $data = file_get_contents('php://input');
        
        $type=strtolower($type);
        if(!empty($data))
        {
            switch($type)
            {
                case 'json':
                    $this->Data = json_decode($data,true);
                    
                    if(empty($this->Data))
                    {
                        header('HTTP/1.0 410 Not Found');
                        $return['error'] =apiError(410,"invalid json data");
                        local_json($return);
                    }
                break;
            }
        }
        return $this->Data;
        
    }
    public function valideMethod($choix)
    {
        $method = $_SERVER['REQUEST_METHOD'];
      
        if($method!=$choix)
		{
			header('HTTP/1.0 405 Method not allowed');
			$return['error'] =apiError(405,"Method $method not allowed");
			local_json($return);
		}
    }
    private function getAutorization($method="")
    {
        $autorisation = $this->Headers['Authorization'];
       
        $pos = strpos($autorisation,' ');
        $key = trim(substr($autorisation,0,$pos));
        if(ucfirst($key)!=ucfirst($method)) return "";
        $val =  trim(substr($autorisation,$pos));
        return $val;
    }
}