<?php
class hub2
{
	private $error   = false; 
	private $Type   = 'send';
	private $Simulation = 0;
	private $Production = 0;
	
	private $Momo = 0;	

	private $Url = "https://api.hub2.io/";
	
		
	
	###########################################################
	function __construct()
	{
		$this->MerchantID = "UkoJwtlbK2D6BUI3hnsTu";
		$this->ApiKey = "sk_VOZIkxecCXwzdElw4Hctq4ooXN9qtHWn";
		$this->IntentID = "";
		$this->IntentToken = "";
	}
	public function setData($data)
	{
		$this->receiveData = 
		$this->Data = $data;
	
	}
	function setProduction()
	{
		$this->PrivateKey = "live_private_Zj64PmPy2aGmFaAYhk8mpC5D8qq";
		$this->PublicKey = "live_public_JGbiw2EXM4M6EDl85cM52xFO6Pu";
		$this->Token = "qOLnSLr0ZOz9sK0O5Caz";
		$this->Url = 'https://app.paydunya.com/api/';
	}
	function setSimulation()
	{
		$this->Production = 0;
	}
	
	function getUID()
	{
		return getUID();
	}
	function getStatus($current)
	{
		global $sgbd;
		
		$status = 'PENDING';
		if(!is_array($current))
		{
			//$current = $sgbd->query("select * from transactions where MaviancePTN ='$current'")->row_array();
		}
		if(!empty($current['Infos'])) $info = json_decode($current['Infos'],true);
		else $info = json_decode($current['infos'],true);

		$debut = substr($info['transaction_id'],0,3);
		
		switch($debut)
		{
			case 'PIM':
				
				uses_class('curl');
				
				
				$curl = new curl;
				$curl->setUrl($this->Url."payment-intents/".$info['provider_id']);
				$curl->addHeader("merchantId",$this->MerchantID);
				$curl->addHeader("environment","sandbox");
				$curl->addHeader("ApiKey",$this->ApiKey);
				$curl->addHeader("Content-Type","application/json");
				$curl->setMethode('GET');
				
				$curl->make();
				
				$status = strtoupper($curl->Reponse['data']['status']);
				$code_error = strtoupper($curl->Reponse['data']['lastPaymentFailure']['code']);
				
				switch($status)
				{
					case 'SUCCESSFUL':


						$status = "SUCCESS";
					break;
					case 'PAYMENT_REQUIRED':
					case 'INPROGRESS':
					case 'INITIATED':
						$status = "PENDING";
					break;
					default: 
						$status = "PENDING";
				}
				
			break;
			case'POM':
	
				
				
				uses_class('curl');
				$curl = new curl;
				$curl->setUrl($this->Url."transfers/".$info['provider_id']);
				$curl->addHeader("merchantId",$this->MerchantID);
				$curl->addHeader("environment","sandbox");
				$curl->addHeader("ApiKey",$this->ApiKey);
				$curl->addHeader("Content-Type","application/json");
				$curl->setMethode('GET');
				
				$curl->make();
				$status = strtoupper($curl->Reponse['data']['status']);
				$code_error = strtoupper($curl->Reponse['data']['failureCause']['code']);
				
				switch($status)
				{
					case 'SUCCESSFUL':


						$status = "SUCCESS";
					break;
					case 'INPROGRESS':
					case 'INITIATED':
					default: 
						$status = "PENDING";
				}
				
			break;
			default : $status = 'FAILED';
		}
		if(!empty($code_error))
		{
	
			switch($code_error)
			{
				case 'FORBIDDEN_BY_PROVIDER':
	
	
					$status = "FAILED";
				break;
				case 'TOO_MANY_REQUEST':
	
	
					$status = "FAILED";
				break;
				case 'UNKNOWN_REASON':
	
	
					$status = "FAILED";
				case 'INVALID_MSISDN':


					$status = "FAILED";
				break;
				case 'INTERNAL_ERROR':


					$status = "FAILED";
				break;
				case 'INTERNAL_ERROR':


					$status = "FAILED";
				break;
				
				default:
				if(!empty($code_error)) $status = "FAILED";
					
			}
		}
		if($curl->Reponse['error']['statusCode']==400) $status = "FAILED";
		return strtoupper($status);
		
		

	}
	
	function getBalance()
	{
		$this->Solde = $this->getBalanceMTN();
	}

	function getAutorisation()//transfert de credit 
	{
		if($this->Production==1) $this->setProduction();
		else $this->setSimulation();
		$this->Autorization = base64_encode($this->ApiUser[$this->Module].":".$this->ApiKey[$this->Module]);//$curl->Response->apiKey;
	}

	function getToken()//transfert de credit 
	{
		uses_class('curl');
		

		
		//CREATION ET SAUVEGARDE DU ACCESS_TOCKEN
		$curl = new curl;
		$curl->setUrl($this->Url.$this->Module."/token/");
		$curl->addHeader("Authorization","Basic ".$this->Autorization);
		$curl->addHeader("Ocp-Apim-Subscription-Key","".$this->Primary[$this->Module]."");

		$curl->setMethode('POST');
		$curl->make();	
		
		
		
		$this->Token = $curl->Reponse['access_token'];
		//if(empty($this->Token)) setError("Service momentanément indisponible !","Le jéton de sécurité ".$this->Module." mtnpay n'est plus/pas valide");
	}
	
	function Depot()//transfert de credit 
	{
		$number = 
		$n1     = '00000001'; // Successful
		$n2     = '00000200'; // Failure : Unknown Reason
		$n3     = '00000202'; // Failure : Fraud Suspicion
		$n4     = '00000203'; // Failure : Forbidden by provider 
		$n5     = '00000400'; // Failure : Invalid destination

		$t = rand(1,5);
		$t = "n$t";
		$this->Data['reference_id']=
		$this->Data['international_phone']=
		$this->Data['national_phone'] = $$t;
        uses_class('curl');
		$curl = new curl;
		$curl->setUrl($this->Url."transfers");
        $curl->addHeader("merchantId",$this->MerchantID);
		$curl->addHeader("environment","sandbox");
		$curl->addHeader("ApiKey",$this->ApiKey);
		$curl->addHeader("Content-Type","application/json");
		
		$data = '{
				"reference": "'.$this->IDTransaction.'",
				"amount":'.$this->Data['amount'].',
				"currency": "'.$this->Data['currency'].'",
				"description": "Viral Pay",
				"destination": {
					"type": "mobile_money",
					"country": "'.$this->Data['country'].'",
					"provider": "'.$this->Data['operator'].'",
					"msisdn": "'.$this->Data['national_phone'].'"
				}
			}';  
		
		$curl->setMethode('POST');
		$curl->setData($data);
		
		$curl->make();

		$Reponse = $curl->Reponse;
		
		if(empty($curl->Reponse['error']) and !empty($curl->Reponse['data']['id']))
		{
			$this->Return['reponse']= array
				(
					"transaction_id"=> $this->IDTransaction,
					"order_id"=> $this->Data['order_id'],
					"phone_number"=> $this->Data['international_phone'],
					"amount"=>$this->Data['amount'],
					"fees"=>$this->Data['fees'],
					"taxes"=>$this->Data['taxes'],
					"status"=>'PENDING',
					"reference_id"=> $this->Data['reference_id'],
					"provider_id"=> $curl->Reponse['data']['id'],
					"provider_code"=>"hubto"
				);
				if($this->Data['operator']=='wave')
				{
					$this->Return['reponse']['provider_link']= $Reponse['provider_link'];
				}
		}
		else
		{

			$this->Return['error']=array
				(
					"transaction_id"=> $this->IDTransaction,
					"amount"=> $this->Data['amount'],
					"status"=> strtoupper("Failed"),
					"reason"=>"Transaction failed",
					"provider_error"=>$curl->Reponse['error']['message'][0],
					"order_id"=> $this->Data['order_id'],

				);
				//local_json($this->Return);
		}
		
	}
	
	function Retrait()//transfert de credit 
	{
		$number = 
		$n1     = '00000001'; // Successful
		$n2     = '00000101'; // Failure : Unknown Reason
		$n3     = '00000200'; // Failure : Fraud Suspicion
		$n4     = '00000201'; // Failure : Forbidden by provider 
		$n5     = '00000202'; // Failure : Invalid destination
		$n6     = '00000203'; // Failure : Invalid destination
		$n7     = '00000300'; // Failure : Invalid destination
		$n8     = '00000301'; // Failure : Invalid destination
		$n9     = '00000400'; // Failure : Invalid destination

		

		$t = rand(1,9);
		$t = "n$t";

		$this->Data['reference_id']=
		$this->Data['international_phone']=
		$this->Data['national_phone'] = $$t;
        uses_class('curl');
		$curl = new curl;
		$curl->setUrl($this->Url."payment-intents");
        $curl->addHeader("merchantId",$this->MerchantID);
		$curl->addHeader("environment","sandbox");
		$curl->addHeader("ApiKey",$this->ApiKey);
		$curl->addHeader("Content-Type","application/json");
	
		$data = '{
				"customerReference": "'.$this->IDTransaction.'",
				"purchaseReference": "'.$this->IDTransaction.'",
				"amount": '.$this->Data['amount_total'].',
				"currency": "'.$this->Data['currency'].'"
			}';  
		
		$curl->setMethode('POST');
		$curl->setData($data);
		
		$curl->make();
		
		$Reponse = $curl->Reponse;
		$id_itent = $Reponse['data']['id'];

		if(empty($curl->Reponse['error']) and !empty($id_itent))
		{
		
			$curl = new curl;
			$curl->setUrl($this->Url."payment-intents/".$id_itent."/payments");
			$curl->addHeader("merchantId",$this->MerchantID);
			$curl->addHeader("environment","sandbox");
			$curl->addHeader("ApiKey",$this->ApiKey);
			$curl->addHeader("Content-Type","application/json");
		
			$data = '{
				"token": "'.$Reponse['data']['token'].'",
				"paymentMethod": "mobile_money",
				"country": "'.$this->Data['country'].'",
				"provider": "'.$this->Data['operator'].'",
				"mobileMoney": {
					"msisdn": "'.$this->Data['national_phone'].'"
				}
			}';
		
		$curl->setMethode('POST');
		$curl->setData($data);
		
		$curl->make();
       
		$hubto_id = $curl->Reponse['data']['id'];
		if(empty($curl->Reponse['error']) and !empty($hubto_id))
		{

			$this->Return['reponse']= array
			(
				"transaction_id"=> $this->IDTransaction,
				"order_id"=> $this->Data['order_id'],
				"phone_number"=> $this->Data['international_phone'],
				"amount"=>$this->Data['amount'],
				"fees"=>$this->Data['fees'],
				"taxes"=>$this->Data['taxes'],
				"status"=>'PENDING',
				"reference_id"=> $this->Data['reference_id'],
				"provider_id"=> $hubto_id,
				"provider_code"=>"hubto"
			);
			
			if($this->Data['operator']=='wave')
			{
				$this->Return['reponse']['provider_link']= $Reponse['provider_link'];
			}
			
		}
		else
		{
			$this->Return['error']=array
			(
				"transaction_id"=> $this->IDTransaction,
				"amount"=> $this->Data['amount'],
				"status"=> strtoupper("Failed"),
				"reason"=>"Transaction failed",
				"provider_error"=>$curl->Reponse['error']['message'],
				"order_id"=> $this->Data['order_id'],

			);
			//local_json($this->Return);
		}
			
		}
		else
		{
			$this->Return['error']=array
				(
					"transaction_id"=> $this->IDTransaction,
					"amount"=> $this->Data['amount'],
					"status"=> strtoupper("Failed"),
					"reason"=>"Transaction failed",
					"provider_error"=>$curl->Reponse['error']['message'][0],
					"order_id"=> $this->Data['order_id'],

				);
				//local_json($this->Return);
		}
		
	}
	
	function PaymentInit()
	{
		$this->Recharge();
	}

	function setError($err)
	{
		$this->Return['error']   = 1;
		$this->Return['message'] = mb_encode($err);
		
		$this->Return = iso_encode($this->Return);
		echo (json_encode($this->Return,JSON_FORCE_OBJECT|JSON_UNESCAPED_UNICODE));
		exit();
	}
}
?>