<?php
class iwomipay
{
	private $error   = true; 
	private $Cle   = 'send';
	private $Production = 0;
	private $CrytageKey = "";
	private $Tocken ='';
	private $BaseUrl = "https://www.pay.iwomitechnologies.com:8443/iwomipay_sandbox";
	private $CallBackUrl = API_URL."callbacks";
	private $ApiUser = "iwomipay2021";
	private $ApiKey = "iwomipay@2020";
	private $Test = false;

	function __construct()
	{
		$this->Mode = 'cash';
		$this->Api['mtn']['credit']['key'] = "5e016fb8-ef10-458c-80c4-442e94708eee";
		$this->Api['mtn']['credit']['secret'] = "6ef3965f-ccb9-4f70-8864-1ca1de8e7c7d";

		$this->Api['mtn']['debit']['key'] = "5e016fb8-ef10-458c-80c4-442e94708eee";
		$this->Api['mtn']['debit']['secret'] = "6ef3965f-ccb9-4f70-8864-1ca1de8e7c7d";
		
		$this->Api['orange']['credit']['key'] = "36f4b65b-bbcf-4ca6-b881-1ba76b95ac39";
		$this->Api['orange']['credit']['secret'] = "0cf40e83-e3eb-4bc1-9504-8d6cd3878343";

		$this->Api['orange']['debit']['key'] = "36f4b65b-bbcf-4ca6-b881-1ba76b95ac39";
		$this->Api['orange']['debit']['secret'] = "0cf40e83-e3eb-4bc1-9504-8d6cd3878343";

	
		$this->BaseUrl = "https://www.pay.iwomitechnologies.com:8443/iwomipay_sandbox";
		$this->ApiUser = "iwomipay2021";
		$this->ApiKey = "iwomipay@2020";
		

		$this->Numeros['disbursement'] = "677777777";
		$this->Names['disbursement']= "IWOMI LTD";

		$this->Numeros['disbursement'] = "677777777";
		$this->Names['disbursement']= "IWOMI LTD";
		$this->setAccountProduction();
	}
	function setProduction()
	{ 
			
	}
	public function setData($data)
	{
		$this->receiveData = 
		$this->Data = $data;
	
	}
    function getBalance()
	{
		$this->setProduction();
		uses_class('curl');
		$this->getToken();
		$this->EndPoint = 'account/balance';
		$curl = new curl;
		$curl->setUrl($this->BaseUrl.$this->EndPoint);
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("Authorization","Bearer ".$this->Token);
		
		$curl->setMethode('POST');
		
		$curl->make();
		$curl->Reponse['result']['maindeposit']=numbertoprix($curl->Reponse['result']['maindeposit']);
		if(!empty($curl->Reponse['data'])) 
		
		$this->Solde = $curl->Reponse['data'];
			
			
	}
	
	function getToken($type="")
	{
		uses_class('curl');
		$curl = new curl;
			
		$data = array(
			'username' => $this->ApiUser,
			'password' => $this->ApiKey
		 );
		$curl->setUrl($this->BaseUrl."/authenticate");
		$curl->addHeader("Content-Type","application/json");
		$curl->setMethode('POST');
		$curl->setData($data);
		
		$curl->make();
	
		
		
		
		$response = $curl->Response;
		if(!empty($response->token))
		{
			$this->Token = $response->token;
			$this->TokenExpire = 3600*24*7;
		}
		else{

			$this->Return['error']=array
			(
				"status"=> "FAILED",
				"reason"=>"Ressource unavaible",
				"code"=> $curl->ErrorNumber
			);
			//local_json($this->Return);
		}
		
		
	}
	   
	function getStatus($ptn)
	{
		global $sgbd;

		if(!is_array($current))
		{
			//$current = $sgbd->query("select * from transactions where MaviancePTN ='$current'")->row_array();
		}
	    $info = loadTransaction($current);

		if(empty($current['infos'])) $current['infos'] = $current['Infos'];
		$infos = json_decode($current['infos'],true);
		
		
		$this->setProduction();
		

		$this->EndPoint = "/iwomipayStatus/".$infos['provider_id'];
		$this->getToken();
		
    
		uses_class('curl');
		 
		$curl = new curl;
		$curl->setUrl($this->BaseUrl.$this->EndPoint);
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("Authorization","Bearer ".$this->Token);
		$curl->setMethode('GET');
	
		$curl->make();

		
		if(!empty($curl->Reponse['internal_id']) )
		{
			if($curl->Reponse['status']=='01') $statut ='success';
			else $statut = strtolower($curl->Reponse['message']);
			switch($statut)
			{
				case 'successfull':
				case 'success':
				case 'successful':
					return "Success";
				break;
				case 'failed':
					return "FAILED";
				break;
			}
		}
		
		return "PENDING";	
		
		
	}
	function getAutorization()
	{
		
		$this->Autorization =base64_encode($this->ApiUser.':'.$this->ApiKey);
	}
	function Retrait()
	{
		$this->Recharge();
	}
	function getType()
	{
		
		if(strtolower($this->Data['country'])!='cm')
		{
			$this->Return['error']=array
			(
				"status"=> "FAILED",
				"reason"=>"Country unavaible",
				"code"=> $curl->ErrorNumber
			);
			//local_json($this->Return);
		}
		switch($this->Data['operator'])
		{
			case 'orange':
				return 'om';
			break;
			case 'mtn':
				return 'momo';
			break;
			default:
					$this->Return['error']=array
					(
						"status"=> "FAILED",
						"reason"=>"Ressource unavaible",
						"code"=> $curl->ErrorNumber
					);
					//local_json($this->Return);
		}
	}
	function Recharge()
	{
		$this->ReferenceID = getUUID();

		$this->EndPoint = '/iwomipay';
		$this->getToken("credit");
		
		$type = $this->getType();
		uses_class('curl');
		$data = array(
			"op_type" => "credit",
			"type" => $type,
			"amount" => $this->Data['amount_total'],
			"external_id" => date('ymwhsi').random_number(8),
			"motif" => "VIRALPAY",
			"tel" => $this->Numero,
			"email" => "",
			"country" => "cm",
			"currency" => "XAF",
			"callback_url" => $this->CallBackUrl,
			"fist_name" => "",
			"last_name" => "",
			"address" => "",
			"city" => "",
			"success_url" => $this->CallBackUrl,
			"failed_url"=> $this->CallBackUrl
		 );

		$opera = $this->Data['operator'];
		
		$curl = new curl;
		$curl->setUrl($this->BaseUrl.$this->EndPoint);
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("AccountKey"," ".base64_encode($this->Api[$opera]['credit']['key'].':'.$this->Api[$opera]['credit']['secret']));
		$curl->addHeader("Authorization","Bearer ".$this->Token);
		
		$curl->setMethode('POST');
		$curl->setData($data);
		
		$curl->make();
		
		
		
		

		/*****************************************
		 * 
		 **************************************************/

		if(!empty($curl->Reponse['internal_id']) )
		{
			$statut = $this->realStatut($curl->Reponse['data']['status']);
			
			$this->Return['reponse']= array
			(
				"transaction_id"=> $this->IDTransaction,
				"order_id"=> $this->order_id,//->ReferenceID,
				"phone_number"=> $this->Numero,
				"amount"=>$this->Data['amount'],
				"fees"=>$this->Data['fees'],
				"taxes"=>$this->Data['taxes'],
				"status"=>'PENDING',
				"reference_id"=> $this->Data['reference_id'],
				"provider_id"=> $curl->Reponse['internal_id'],
				"provider_code"=>$this->Data['provider_code']	
			);
			$this->Return['error']=0;
			$this->status =	"PENDING";
			$this->Return['ptn'] = $curl->Reponse['internal_id'];
		}
		else
		{
			$this->Return['error']=array
			(
				"status"=> "FAILED",
				"provider_error"=>json_encode($curl->Reponse),
				"reason"=>"Echec de la transaction",
				"code"=> $curl->ErrorNumber
			);
		 	//local_json($this->Return);
			
			
		}
		
	}
	function Depot()
	{
		
		$this->ReferenceID = getUUID();
		$this->EndPoint = '/iwomipay';
		$this->getToken("debit");
	    
		$type = $this->getType();
		
		uses_class('curl');
		$data = array(
			"op_type" => "debit",
			"type" => $type,
			"amount" => $this->Montant,
			"external_id" => date('ymwhsi').random_number(8),
			"motif" => "VIRALPAY",
			"tel" => $this->Numero,
			"email" => "",
			"country" => "cm",
			"currency" => "XAF",
			"callback_url" => $this->CallBackUrl,
			"fist_name" => "",
			"last_name" => "",
			"address" => "",
			"city" => "",
			"success_url" => $this->CallBackUrl,
			"failed_url"=> $this->CallBackUrl
		 );
		$opera = $this->Data['operator'];
		
		$curl = new curl;
		$curl->setUrl($this->BaseUrl.$this->EndPoint);
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("AccountKey"," ".base64_encode($this->Api[$opera]['debit']['key'].':'.$this->Api[$opera]['debit']['secret']));
		$curl->addHeader("Authorization","Bearer ".$this->Token);
		
		$curl->setMethode('POST');
		$curl->setData($data);
		
		$curl->make();
		
		
		
		$curl->ErrorNumber = intval($curl->Reponse['status']);
		if(($curl->ErrorNumber)<400)
		{
			$statut = $this->realStatut($curl->Reponse['data']['status']);
			
			$this->Return['reponse']= array
			(
				"amount"=>$this->Montant,
				"status"=>$statut,
				"transaction_id"=> $this->IDTransaction,
				"reference_id"=> $this->Reference,
				"provider_id"=> $curl->Reponse['internal_id'],
				"provider_code"=>$this->Data['provider_code'],
				"order_id"=> $this->order_id,
				"phone_number"=> $this->Numero
			);
		 
		}
		elseif(($curl->ErrorNumber)==500)
		{
			
			$message = "The server did not respond correctly. ";
			
			
			$this->Return['error']=array
			(
				"status"=> "FAILED",
				"provider_error"=>json_encode($message),
				"reason"=>"Echec de la transaction",
				"code"=> $curl->ErrorNumber
			);
		 	//local_json($this->Return);
			
		}
		else{
			
			$this->Return['error']=array
			(
				"status"=> "FAILED",
				"provider_error"=>json_encode($curl->Reponse),
				"reason"=>"Echec de la transaction",
				"code"=> $curl->ErrorNumber
			);
		 	//local_json($this->Return);
		 
		}
		
		
	
		/*****************************************
		 * 
		 **************************************************/

		if(!empty($curl->Reponse['internal_id']) )
		{
			
			$this->Return['error']=0;
			$this->status =	"PENDING";
			$this->Return['ptn'] = $curl->Reponse['internal_id']; 
		}
		else
		{
			switch($curl->Reponse['status'])
			{
				case 409:
					/*uses_functions('sms');
					adminSMS("Le solde ".strtoupper($opera)." PayOut IWOMI est insuffisant pour effectuer un débit de ".numbertoprix($this->Montant)." vers ".$this->Numero,"674001044,699539792,675955756");*/
					
				break;
				
			}
			$this->Return['error']=0;
			$this->status =	"PENDING";
			$this->Return['ptn']= 'ACF'.random_text(17);	
		}
		
	}
	private function setAccountProduction()
	{
		$this->BaseUrl = "https://www.pay.iwomitechnologies.com/api/iwomipay_prodv1";

		$this->ApiUser = "098IW67MNGO24";
		$this->ApiKey = "PAY04JAQ2024G06";

		$this->Api['mtn']['credit']['key'] = "ff0b4182-deb9-4779-b0d7-142c19d23687";
		$this->Api['mtn']['credit']['secret'] = "ecfcb1de-e37f-4c0f-a637-b606aea90c66";

		$this->Api['mtn']['debit']['key'] = "b34a9980-8d94-472b-8fca-ece5f23a55b8";
		$this->Api['mtn']['debit']['secret'] = "970e53b6-c845-4e2c-838b-0a1f786cfa07";
		
		$this->Api['orange']['credit']['key'] = "7dfa1585-dbb7-4875-970d-02add83da8b6";
		$this->Api['orange']['credit']['secret'] = "b91f47f8-5b81-4421-9061-a00cc5efad48";

		$this->Api['orange']['debit']['key'] = "a5e208ca-f6f0-40a9-8062-9ffd170bf8bf";
		$this->Api['orange']['debit']['secret'] = "416d49cd-24b2-45d8-8087-415e8de73611";
		
		

	}
	private function realStatut($statut)
	{
		$teststatut = strtoupper($statut);
		switch($teststatut)
		{
			case  'SUCCESSFULL':
			case  'SUCCESS':
				$statut = 'SUCCESS';
			break;
			default: $statut = 'PENDING';
		}
		return $statut;
	}
}
?>