<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Callback extends CI_Controller {

	public function __construct(){
        parent::__construct();
		$this->load->model('token_model');
		
    }


	public function index()
    {
	
		## METHODE ACCEPTE
		$this->token_model->valideMethod('GET');
		
		## AUTHENTIFICATION 
		$this->token_model->valideToken();

		## RECUPERATION DES DONNEES 
		
		if(!empty($_GET['transaction_id'])) $cond = "transaction_id = '".$_GET['transaction_id']."'";
		elseif(!empty($_GET['order_id'])) $cond = "order_id = '".$_GET['order_id']."'";
		
		

		//REQUETE DE RECUPERATION
		success:
		$query = "select customers_accounts.*,transactions.infos from transactions left join customers_accounts on customers_accounts.agent_id = transactions.agent_id and customers_accounts.account_number = transactions.account_number where transactions.agent_id = '".$this->token_model->user_id."' and $cond limit 2";// and   transaction_id='".$this->token_model->Data['transactionid']."'";
		
		$trans = $this->db->query($query)->result_array();

	
		if(count($trans)>1 or empty($trans))
		{
			header('HTTP/1.0 404 Resource not found');
			$return['error'] =apiError(400,"resource not available");
			local_json($return);
		}
		$trans = $trans[0];
		if(strtolower($trans['status'])=='pending')
		{
			$reponse['message']= "La transaction est en cours";
			
		}
        else
        {
            uses_class('finance');
            $finance = new finance();
            $infos = json_decode($trans['Infos'],true);
			
           if(!empty($infos['notify_url'])) 
           {
            try {

				if($finance->callback($infos['notify_url'],$infos))	$reponse['message']= "Callback envoyé à ".$infos['notify_url'];
				else 	$reponse['message']= "Le dernier callbacks est recents ou il y a un soucis ".$infos['notify_url'];

			  } catch(Exception $e) {
				
				$reponse['message']= $e;

			  }
			
           } 
           else $reponse['message']= "Pas de callback disponible";
        }
		
		
		
		$result['data']=$reponse;
		local_json($result);

		## METHODE ACCEPTE
		$this->token_model->valideMethod('POST');

		## AUTHENTIFICATION 
		$this->token_model->valideToken();

		## RECUPERATION DES DONNEES 
		$this->token_model->getData('JSON');
       
        $json = $this->token_model->Data;
        
    }
	

}