<?php
class mtnsandbox
{
	private $error   = false; 
	private $Type   = 'send';
	private $Simulation = 0;
	private $Production = 0;
	
	private $Momo = 0;	
	private $Url = 'https://proxy.momoapi.mtn.com/';
		
	
	###########################################################
	function __construct()
	{
		/*$this->Payement['ApiKey']='6604972db215419680b7c88c4d4e8333';
		$this->Payement['ApiUser']='c8d8b7f2-c00b-402a-a341-be99a9c099d1';
		*/
		$this->ApiKey = Array
						(
							'collection'=>'842c89beec32499cbfda14b08344413c',
							'disbursement'=>'33f57736fb464f02bf3c1b3ce97ebd28',
							'remittance'=>''
						);
		$this->ApiUser = Array
						(
							'collection'=>'f576ebb8-7f96-44bf-8f32-e74962143f17',
							'disbursement'=>'b683e3c3-7152-44f4-a5f6-90b1e0f71c12',
							'remittance'=>''
						);
		$this->Primary = Array
						(
							'collection'=>'ff37a534b2f04ae78e0bc716d6890ccc',
							'disbursement'=>'5ac1954022f14adda6c59a184a4f2401',
							'remittance'=>'efb8a539f9a14a9d81784cf602db8103'
						);
	 	$this->Secondary  = Array
							(
								'collection'=>'4546c847ca604dbc96c0b17b3fd1c91f',
								'disbursement'=>'ff3fe2ffb1c842059055664e315dfd47',
								'remittance'=>'842e35a8573948d6b69d6e40123e976c'
							);
		$this->PayText  = Array
							(
								'collection'=>'ViralPAY PAY',
								'disbursement'=>'ViralPAY CASH-IN',
								'remittance'=>'ViralPAY REMITTANCE'
							);
		$this->Numeros  = Array
							(
								'collection'=>'678787878',
								'disbursement'=>'687878787',
								'remittance'=>'ViralPAY REMITTANCE'
							);
		$this->Names  = Array
							(
								'collection'=>'ViralPAY',
								'disbursement'=>'ViralPAY DEP.',
								'remittance'=>'ViralPAY REM.'
							);

		$this->Target = 'mtncameroon';
		$this->Currency = 'XAF';
		$this->CallBack = API_URL."callbacks/";
		$this->Key = $this->Primary[$this->Module];

	}
	
	function setProduction()
	{
		$this->Production = 1;
	}
	function setSimulation()
	{
		$this->Production = 0;
	}
	function getUID()
	{
		return getUID();
	}
	function getStatus($current)
	{
		global $sgbd;
		
		

		if(!is_array($current))
		{
			$current = $sgbd->query("select * from transactions where MaviancePTN ='$current'")->row_array();
		}
		$info = json_decode($current['Infos'],true);
		
		if(!empty($info['module'])) $this->Module = $info['module'];

		switch($current['Confirm'])
		{
			case 1:
				$this->Module = 'collection';
				$request = 'requesttopay';
			break;
			case 0:
				$this->Module = 'disbursement';
				$request = 'transfer';
			break;
			default : $request = 'requesttopay';
		}
		
		$infos = json_decode($current['Infos'],true);
		
		$this->ReferenceID = $infos['uid'];
		if(!$this->Production) $this->getSandbox($this->Module);
		$this->getAutorisation();
		
		$this->getToken();
		if(empty($this->Token))
		{
			return 'FAILED';
		}
		
		uses_class('curl');
		$curl = new curl;
		$curl->setUrl($this->Url.$this->Module."/v1_0/".$request."/".$infos['uid']);
		$curl->addHeader("Authorization","Bearer ".$this->Token);
		$curl->addHeader("X-Reference-Id",$current['MaviancePTN']);
		$curl->addHeader("X-Target-Environment",$this->Target);
		//$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("Ocp-Apim-Subscription-Key","".$this->Primary[$this->Module]."");
		$data = "";  
		$curl->setMethode('GET');
		$curl->setData($data);
		
		$curl->make();
		
	
		
		if($curl->ErroNumber==200)
		{
			$statut = strtolower($curl->Reponse['status']);
			if(!empty($curl->Reponse['reason'])) warningError("ViralPAY DEPOSIT ".$curl->Reponse['reason']);
			if($statut=='failed') return "Cancelled";
			elseif($statut=='successful') return "Success";
			//if(empty($statut)) $statut = 'empty';
			//return $statut;
		}
		else
		{
			if($curl->Reponse['statusCode']==404)
			{
					return 'FAILED';
			}
		}
		return "PENDING";

	}
	
	function getBalance()
	{
		$this->Solde = $this->getBalanceMTN();
	}
	function getBalanceMTN()
	{
		$modules = array('collection','disbursement');
		$return['Total'] = 0;
		foreach($modules as $k)
		{
			$this->Module = $k;
			$this->getAutorisation();
			$this->getToken();
			$curl = new curl;
			$curl->setUrl($this->Url.$this->Module."/v1_0/account/balance");
			$curl->addHeader("Authorization","Bearer ".$this->Token);
			$curl->addHeader("X-Target-Environment",$this->Target);
			//$curl->addHeader("Content-Type","application/json");
			$curl->addHeader("Ocp-Apim-Subscription-Key","".$this->Primary[$this->Module]."");
			$data = "";  
			$curl->setMethode('GET');

			$curl->make();
			
			
			
			if(isset($curl->Response->availableBalance)) 
			{
				$return['Total']+= doubleval($curl->Response->availableBalance); 
				$return[$k]= doubleval($curl->Response->availableBalance).' '.$curl->Response->currency; 		
			}
			else $return[$k]=null;
			
		}
		
		return $return;
	}
	
	function getAutorisation()//transfert de credit 
	{
		$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->Response->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 
	{
		//TEST LIVE MTN DIRECT
		$this->ReferenceID = getUUID();
		$this->Module = 'disbursement';
		$phone = strtophone($this->Numero);
		$this->Numero = $phone['phone'];
		
		//EMULATION DE LA SANDBOX
		
		if(!$this->Production) $this->getSandbox($this->Module);

		$this->getAutorisation();
		
		$this->getToken();

		$curl = new curl;
		$curl->setUrl($this->Url.$this->Module."/v1_0/transfer");
		$curl->addHeader("Authorization","Bearer ".$this->Token);
		$curl->addHeader("X-Reference-Id",$this->ReferenceID);
		$curl->addHeader("X-Target-Environment",$this->Target);
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("Ocp-Apim-Subscription-Key","".$this->Primary[$this->Module]."");
 
		$data = json_encode(array(
							"amount"  => $this->Montant,
							"currency"  => $this->Currency,
							"externalId"  => $this->ReferenceID,
							"payee"  => array("partyIdType"=>"MSISDN","partyId"=>$this->Numero),
							"payerMessage" => $this->PayText[$this->Module],
							"payeeNote" =>$this->IDTransaction
							));   
		$curl->setMethode('POST');
		$curl->setData($data);
		$curl->make();
		
		
		
		if(($curl->ErrorNumber)<400)
		{
			$statut = $this->realStatut($curl->Reponse['data']['status']);
			
			$this->Return['reponse']= array
			(
				"amount"=>$this->Montant,
				"status"=>$statut,
				"transaction"=> $this->IDTransaction,
				"reference"=> $this->Reference,
				"provider_number"=> $this->Numeros['disbursement'],
				"provider_name"=> $this->Names['disbursement'],
				"uid"=> $this->ReferenceID,
				"phone"=> $this->Numero
			);
		 
		}
		elseif(($curl->ErrorNumber)==500)
		{
			if(!empty($curl->Reponse['message'])) $message = $curl->Reponse['message'];
			else $message = "The server did not respond correctly. ";
			$this->Return['error']=array
			(
				"status"=> "FAILED",
				"reason"=>$message,
				"code"=> $curl->ErrorNumber
			);
			local_json($this->Return);
		}
		else{
		 $this->Return['error']=array
		 (
			 "status"=> "FAILED",
			 "reason"=>$curl->Reponse['errorMessage'],
			 "code"=> $curl->ErrorNumber
		 );
		 local_json($this->Return);
		}
	}
	function Retrait()//transfert de credit 
	{
		$this->Recharge();
	}
	
	function PaymentInit()
	{
		$this->Recharge();
	}
	
	function Recharge()//transfert de credit 
	{
		//TEST LIVE MTN DIRECT
		if(empty($this->Reference))
		{
			$this->Reference = $this->IDTransaction;
		}
		$this->Confirm = 1;
		$this->ReferenceID = getUUID();
		$this->Module = 'collection';
		$phone = strtophone($this->Numero);
		$this->Numero = $phone['phone'];
		
		//EMULATION DE LA SANDBOX
		if(!$this->Production) $this->getSandbox($this->Module);

		$this->getAutorisation();
		
		$this->getToken();

		
		//REALISATION DE LA TRANSACTION
		$curl = new curl;
		$curl->setUrl($this->Url.$this->Module."/v1_0/requesttopay");
		$curl->addHeader("Authorization","Bearer ".$this->Token);
		$curl->addHeader("X-Callback-Url",$this->CallBack);
		$curl->addHeader("X-Reference-Id",$this->ReferenceID);
		$curl->addHeader("X-Target-Environment",$this->Target);
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("Ocp-Apim-Subscription-Key","".$this->Primary[$this->Module]."");
		$data = json_encode(array(
							"amount"  => $this->Montant,
							"currency"  => $this->Currency,
							"externalId"  => $this->IDTransaction,
							"payer"  => array("partyIdType"=>"MSISDN","partyId"=>$this->Numero),
							"payerMessage" => $this->PayText[$this->Module],
							"payeeNote" => $this->Reference
							));  
		$curl->setMethode('POST');
		$curl->setData($data);
		
		$curl->make();
		
		if(($curl->ErrorNumber)<400)
		{
			$statut = $this->realStatut($curl->Reponse['data']['status']);
			
			$this->Return['reponse']= array
			(
				"amount"=>$this->Montant,
				"status"=>$statut,
				"transaction"=> $this->IDTransaction,
				"reference"=> $this->Reference,
				"provider_number"=> $this->Numeros['collection'],
				"provider_name"=> $this->Names['collection'],
				"uid"=> $this->ReferenceID,
				"phone"=> $this->Numero
			);
		 
		}
		
		elseif(($curl->ErrorNumber)==500)
		{
			if(!empty($curl->Reponse['message'])) $message = $curl->Reponse['message'];
			else $message = "The server did not respond correctly. ";
			$this->Return['error']=array
			(
				"status"=> "FAILED",
				"reason"=>$message,
				"code"=> $curl->ErrorNumber
			);
			local_json($this->Return);
		}
		else{
		 $this->Return['error']=array
		 (
			 "status"=> "FAILED",
			 "reason"=>$curl->Reponse['errorMessage'],
			 "code"=> $curl->ErrorNumber
		 );
		 local_json($this->Return);
		}
		

	}
	function getSandbox($code)
	{
		//CREATION ET SAUVEGARDE DE LA REFERENCE 
		$this->Primary = Array
						(
							'collection'=>'ff37a534b2f04ae78e0bc716d6890ccc',
							'disbursement'=>'5ac1954022f14adda6c59a184a4f2401',
							'remittance'=>'95d3e95e48554740b0b181d8c6285b28'
						);
	 	$this->Secondary  = Array
							(
								'collection'=>'4546c847ca604dbc96c0b17b3fd1c91f',
								'disbursement'=>'ff3fe2ffb1c842059055664e315dfd47',
								'remittance'=>'6a2ec294e8da4d22806db009138d4c58'
							);
	
		
		$this->Url = "https://sandbox.momodeveloper.mtn.com/";
		$this->Target = "sandbox";
		$this->Key = $this->Primary[$this->Module];
		
		$rand = rand(0,4);
		//$this->Numero = '46733123451'.$rand;
		$this->Montant = min($this->Montant,100);
		$this->Module = $code;
		$this->Currency = 'EUR';

		uses_class('curl');
		$curl = new curl;
		$curl->setUrl("https://sandbox.momodeveloper.mtn.com/v1_0/apiuser");
		$curl->addHeader("X-Reference-Id",$this->ReferenceID);
		$curl->addHeader("X-Target-Environment",$this->Target);
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("Ocp-Apim-Subscription-Key","".$this->Key."");
		$data = json_encode(array("providerCallbackHost"  => $this->CallBackHost)); 
		$curl->setMethode('POST');
		$curl->setData($data);
		$curl->make();
		
		
		
		
		//CREATION ET SAUVEGARDE DE LA CLE 
		$curl = new curl;
		$curl->setUrl("https://sandbox.momodeveloper.mtn.com/v1_0/apiuser/".$this->ReferenceID."/apikey");
		$curl->addHeader("X-Reference-Id",$this->ReferenceID);
		$curl->addHeader("Ocp-Apim-Subscription-Key","".$this->Key."");
		$data = ""; 
		$curl->setMethode('POST');
		$curl->setData($data);
		$curl->make();
		$this->ApiKey[$code] = $curl->Response->apiKey;
		$this->ApiUser[$code] = $this->ReferenceID;
		
		
	}
	function simule()
	{
		$this->Return['error']=0;
		$this->Return['message']=
		$this->Return['statut'] =	"PENDING";
		$a = rand(6,10);
		$b = rand(6,10);
		$c = rand(6,10);
		$this->Return['ptn'] = random_text($a).'-'.random_text($b).'-'.random_text($c);
		return true;
	}
	function setError($err)
	{
		$this->Return['error']   = 1;
		$this->Return['message'] = mb_encode($err);
		traceError($err,$this->Service);
		$this->Return = iso_encode($this->Return);
		echo (json_encode($this->Return,JSON_FORCE_OBJECT|JSON_UNESCAPED_UNICODE));
		exit();
	}
	private function realStatut($statut)
	{
		$teststatut = strtoupper($statut);
		switch($teststatut)
		{
			case  'SUCCESSFULL':
			case  'SUCCESS':
				$statut = 'SUCCESS';
			break;
			default: $statut = 'PENDING';
		}
		return $statut;
	}
}
?>