<?php
class bizao
{
	private $error   = false; 
	private $Type   = 'send';
	private $Simulation = 0;
	private $Production = 1;
	
	private $Momo = 0;	
	//private $Url = 'https://proxy.momoapi.mtn.com/';
	private $Url_live = 'https://api.bizao.com/';
	private $Url_test = 'https://preproduction-gateway.bizao.com/';
	
	
		
	
	###########################################################
	function __construct()
	{
		

	}
	function getPayin()
	{
		$this->Production =0;
		$this->Url = $this->Url_live;
		$this->ClientID = "6XByapdzPXliCoyxmLU_UneoCZka";
		$this->ClientSecret = "GE9bmrrNTMh7M96xfSTbdG5_7Qwa";
		
		$this->getToken();

	}
	public function setData($data)
	{
		$this->receiveData = 
		$this->Data = $data;
	
	}
	function getPayout()
	{
		$this->Production =1;
		$this->Url = $this->Url_live;
		$this->ClientID = "MVr0DkxuFhC3tTMNZNbLm6rP8nwa";
		$this->ClientSecret = "TkkmP2Uw0GQhfNeXrBh3JGQYt9oa";
		$this->getToken();
	}
	
	function setProduction()
	{
		$this->Production = 1;
	}
	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();
		}
		
		
	    $info = loadTransaction($current);

		
		
		$debut = substr($info['transaction_id'],0,3);
		
		switch($debut)
		{
			case 'PIM':
				if(empty($info['provider_id']))
				{
					$sgbd->query("update transactions set compensated = 1 where transaction_id='".$info['transaction_id']."'");
					return "FAILED";
				}
				$this->getPayin();
				uses_class('curl');

			
				
				
				$curl = new curl;
				$curl->setUrl($this->Url."mobilemoney/v2/getStatus/".$info['provider_id']);
				$curl->addHeader("Authorization","Bearer ".$this->Token);
				$curl->addHeader("Accept","application/json");
				$curl->addHeader("Content-Type","application/json");
				$curl->addHeader("country-code",strtolower($info['country']));
				$curl->addHeader("mno-name",$info['operator']);
				$curl->addHeader("cookie","route=1720773444.124.2192.908566|81ae3a9a04c06b83bdb4bb4311fcd72d");
				$curl->setMethode('GET');
				$curl->make();
				
				if(!empty($curl->Reponse['data']['status']))
				
				$status = strtoupper($curl->Reponse['data']['status']);
				
				if(empty($status) and !empty($curl->Reponse['data']['fault'])) $status = "FAILED";
				elseif(empty($status) and !empty($curl->Reponse['error']['fault'])) $status = "FAILED";
				switch($status)
				{
					case 'SUCCESSFUL':
						if(!empty($curl->Reponse['extTransaction-id']))
						{
							$info['operator_id']=$curl->Reponse['extTransaction-id'];
							$json = json_encode($info);
							$query = "update transactions set infos = '".addslashes($json)."' where transaction_id = '".$info['transaction_id']."'";
							$sgbd->query($query);
						}
						
						$status = "SUCCESS";
					break;
					case 'FAILED':
						$status = "FAILED";
					break;
					case 'INPROGRESS':
						if(!empty($curl->Reponse['extTransaction-id']))
						{
							$info['operator_id']=$curl->Reponse['extTransaction-id'];
							$json = json_encode($info);
							$query = "update transactions set infos = '".addslashes($json)."' where transaction_id = '".$info['transaction_id']."'";
						}
						
						$sgbd->query($query);	
					case 'INITIATED':
					default: 
						$status = "PENDING";
				}
				
			break;
			case'POM':
				if(empty($info['provider_id']))
				{
					$sgbd->query("update transactions set compensated = 1 where transaction_id='".$info['transaction_id']."'");
					return "FAILED";
				} 
				$this->getPayout();
				
			
				uses_class('curl');
				$curl = new curl;
				$curl->setUrl($this->Url."bulk/v1/getStatus/".$info['provider_id']);
				$curl->addHeader("Authorization","Bearer ".$this->Token);
				$curl->addHeader("Accept","application/json");
				$curl->addHeader("Content-Type","application/json");
				$curl->addHeader("country-code",strtolower($info['country']));
				$curl->addHeader("channel","web");
				$curl->addHeader("mno-name",$info['operator']);
				$curl->addHeader("type","bulk");
				$curl->addHeader("cookie","route=1720773444.124.2192.908566|81ae3a9a04c06b83bdb4bb4311fcd72d");
				$curl->setMethode('GET');
				$curl->make();
				
				$Reponse = $curl->Reponse['data'][0];
				$status = strtoupper($Reponse['status']);
				
				switch($status)
				{
					case 'SUCCESSFUL':
						if(!empty($Reponse['extTransaction-Id']))
						{
							$info['operator_id']=$Reponse['extTransaction-Id'];
							$json = json_encode($info);
							$query = "update transactions set infos = '".addslashes($json)."' where transaction_id = '".$info['transaction_id']."'";
							$sgbd->query($query);
						} 

						$status = "SUCCESS";
					break;
					case 'FAILED':
						$status = "FAILED";
					break;
					case 'INPROGRESS':
						if(!empty($Reponse['extTransaction-id']))
						{
							$info['operator_id']=$Reponse['extTransaction-id'];
							$json = json_encode($info);
							$query = "update transactions set infos = '".addslashes($json)."' where transaction_id = '".$info['transaction_id']."'";
	
							$sgbd->query($query);
						}
							
					case 'INITIATED':
					default: 
						$status = "PENDING";
				}
			break;
			default : $request = 'requesttopay';
		}
		
		return $status;
	
	}
	
	function getBalance()
	{
		$this->Solde = $this->getBalanceMTN();
	}
	
	function getAutorisation()//transfert de credit 
	{
		
		$this->Autorization = base64_encode($this->ClientID.":".$this->ClientSecret);
	}

	function getToken()//transfert de credit 
	{
		uses_class('curl');
		$this->getAutorisation();

		$data['grant_type']='client_credentials';
		//CREATION ET SAUVEGARDE DU ACCESS_TOCKEN
		$curl = new curl;
		$curl->setUrl($this->Url."token/");
		$curl->addHeader("Authorization","Basic ".$this->Autorization);
		
		$curl->setMethode('POST');
		$curl->setDataUrl($data);
		
		$curl->make();	
		
		
		
		$this->Token = $curl->Reponse['data']['access_token'];
		$this->Scope = $curl->Reponse['data']['scope'];
		$this->TokenType = $curl->Reponse['data']['token_type'];
		
		//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();
		
	
		//if(!$this->Production) $this->getSandbox($this->Module);

		$this->getPayout();

		
		$curl = new curl;
		$curl->setUrl($this->Url."bulk/v1");
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("Authorization","Bearer ".$this->Token);
		$curl->addHeader("country-code",$this->Data['country']);
		$curl->addHeader("mno-name",$this->Data['operator']);
		$curl->addHeader("lang","fr");
		$curl->addHeader("channel","web");
		$curl->addHeader("type","bulk");
		
		$states[]= "param1%3Dvalue1%26param2%3Dvalue2";
		
		$state = rawurlencode(implode('&',$states));
			
		$curl->setMethode('POST');
		
		$data  ='{
					"currency":"'.$this->Data['currency'].'",
					"reference":"ViralPAY",
					"batchNumber":"'.$this->IDTransaction.'",
					"state":"'.$state.'",
					"data":
							[
							{"id":"'.$this->IDTransaction.'",
							"beneficiaryFirstName":"ViralPAY",
							"beneficiaryLastName":"Pay",
							"beneficiaryAddress":"Bonamoussadi Cameroun",
							"beneficiaryMobileNumber":"'.$this->Numero.'",
							"amount":"'.$this->Data['amount'].'",
							"feesApplicable":"",
							"mno":"'.$this->Data['operator'].'"
							}]
							}';

							/*
							
							 */
	
		$curl->setData($data);
		
		
		$curl->make();

		$provider_id = $this->IDTransaction;
		if(($curl->ErrorNumber)<400 and !empty($provider_id))
		{
			
			$this->Return['reponse']= array
			(
				"amount"=>$this->Montant,
				"status"=>'PENDING',
				"reference"=> $this->Reference,
				"transaction_id"=> $this->IDTransaction,
                "order_id"=> $this->Data['order_id'],
                "provider_id"=>$provider_id,
				"provider_code"=>$this->Data['provider_code'],
				"uid"=> $this->ReferenceID,
				"phone"=> $this->Numero
			);
		 
		}
		else{
			switch($curl->ErrorNumber)
			{
				case 403: 
					$reason = ' Resource forbidden';
				break;
			}
			if(!empty($curl->Reponse['requestError'])) $reason = $curl->Reponse['requestError']['serviceException']['text'].' & '.$curl->Reponse['requestError']['serviceException']['variables'];
			$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 Retrait()//transfert de credit 
	{
		$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();

		//EMULATION DE LA SANDBOX
		
		$this->getPayin();

		
		$curl = new curl;
		
		$curl->setUrl($this->Url."mobilemoney/v2");
		$curl->addHeader("Authorization","Bearer ".$this->Token);
		$curl->addHeader("mno-name",$this->Data['operator']);
		$curl->addHeader("country-code",($this->Data['country']));
		if($this->Data['operator']=='wave')
		{
			$curl->addHeader("channel","web");
		}
		else $curl->addHeader("channel","tpe");
		
		$curl->addHeader("lang","fr");
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("cookie","route=1720773444.124.2192.908566|81ae3a9a04c06b83bdb4bb4311fcd72d");
		
		
		$states[]= "param1%3Dvalue1%26otp%3Dvalue2";
		
		$state = rawurlencode(implode('&',$states));
		$BIZAO_ID = substr($this->IDTransaction,3);
		if(empty($this->Data['return_url'])) $this->Data['return_url'] = API_URL."callbacks";
		if(empty($this->Data['cancel_url'])) $this->Data['cancel_url'] = API_URL."callbacks"; 

		$info = array(
			
			
			"currency"  => $this->Data['currency'] ,
			"order_id"  =>$BIZAO_ID ,
			"otp_code"  =>$this->Data['otp_code'] ,
			"reference"  => "ViralPAY",
			"amount" =>  $this->Data['amount_total'] ,
			"return_url"  => $this->Data['return_url'],
			"cancel_url"  => $this->Data['cancel_url'],
			"user_msisdn"  => $this->Data['international_phone'],
			"state" => $state
		);

		

		
		$data = json_encode($info); 
			
		$curl->setMethode('POST');
		
		$curl->setData($data);
		
		
		$curl->make();
		
		
		
		
		
		/*"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"=> "SANDBOX-".random_number(8),
			"provider_code"=>"SANDBOX"*/
    
		if($curl->ErrorNumber<=201)
		{
			$this->Return['reponse']= array
            (
                "transaction_id"=> $this->IDTransaction,
				"order_id"=> $this->Data['order_id'],
				"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"=>$BIZAO_ID,
				"provider_code"=>$this->Data['provider_code'],
               
            );
			
			
			if($this->Data['operator']=='wave') $this->Return['reponse']['provider_link']= $curl->Reponse['payment_url'];
		}
		else{
				$error = "transaction failed";
				
				if(substr_count($curl->Reponse['requestError']['serviceException']['variables'],'otp')>0)
				{
					$error = "Missing the request body parameter: otp";
				}

		 $this->Return['error']=array
		 (
			 "status"=> "FAILED",
			 "reason"=>$error,
			 "provider_error"=>json_encode($curl->Reponse),
			 "code"=> $curl->ErrorNumber
		 );
		 //local_json($this->Return);
		}

	}
	
	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();
	}
}
?>