<?php
class orange
{
	private $error   = true; 
	private $Cle   = 'send';
	private $Production = 1;
	private $CrytageKey = "";
	private $Tocken ='';
	private $Test = false;

	function __construct()
	{
		
	}
	function setProduction()
	{
		$this->Production = 1;
		$this->Simulation = 0;
		$this->BaseUrl = "https://api-s1.orange.cm/";//https://api-s1.orange.cm/omcoreapis/1.0.2
		$this->Login = "gouaya";
		$this->Password = "Tefossi@1948";
        $this->Key = "vfCuLiCLDPHdupOf7uvD9mC8nA4a";
		$this->Secret = "CV1NRLZmTqjfztZPxXuPDf7sBSQa";

        //PARAMETRES API CASH
        $this->ApiUser['cash']= "VIRALPAYDISTRIPROD";
		$this->ApiKey['cash']= "VIRALPAYDISTRIPROD2021";
		$this->channelUserMsisdn['cash'] = "697822875";
        $this->PinOrange['cash'] = "8394";//Distri sim 697822875 PIN 8394

		//PARAMETRES API marchand
		$this->ApiUser['marchand']= "VIRALPAYWEBPAYMENTPROD";
		$this->ApiKey['marchand']= "VIRALPAYWEBPAYMENTPROD2021";
		$this->channelUserMsisdn['marchand']= "691559032";
        $this->PinOrange['marchand']= "1186";//Web sim 691559032 PIN 5718

        $this->CallBackUrl = API_URL."callbacks";
		$this->Test = true;
	}
	public function setData($data)
	{
		$this->receiveData = 
		$this->Data = $data;
	
	}

    function sandboxProduction()
    {
        $this->Key = "Di73CgfU8VNVuGgPOctC7S31Jtwa";
		$this->Secret = "qljgQ6pqFVnp8IcyRsXhwq48vM8a";
    }
	function getUID($size=14)
	{
		return getUID();
		
	}
	function getToken()
	{
		if($this->Production==1) $this->setProduction();
		else $this->setSimulation();

		uses_class('curl');
        $this->getAutorization();
        $this->EndPoint = 'token';

        $data = array(
                        "grant_type"=>"client_credentials",
                        "username"=>$this->Login,
                        "password"=>$this->Password
                    );
        $curl = new curl;
		$curl->setUrl($this->BaseUrl.$this->EndPoint);
		$curl->addHeader("Authorization","Basic ".$this->Autorization);
		
		$curl->setMethode('POST');
		$curl->setDataUrl($data);
		$curl->make();
		
		
		
       $this->Token = $curl->Reponse['access_token'];
		
	}
	function getAutorization()
	{
		$this->Autorization =base64_encode(($this->Key).':'.($this->Secret));
	}

	function providerRecharge()
	{
		//

		$this->EndPoint = 'transaction/';
		$this->getAutorization();
		$this->getBalance();
		
		uses_class('curl');
		$data = array(
			'destination' => $this->Numero,
			'amount' => $this->Montant
		 );

		$curl = new curl;
		$curl->setUrl($this->BaseUrl.$this->EndPoint);
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("Authorization","Basic ".$this->Autorization);
		
		$curl->setMethode('POST');
		$curl->setData($data);
		
	
		$this->Return['solde']=$this->Solde;
		$curl->make();
		
		
		/*****************************************
		 * 
		 **************************************************/
		

		if(strtolower($curl->Reponse['status'])=='failure')
		{
			$this->Return['error']=1;
			$this->status =	"FAILED";
			$this->Return['message']= $this->customError($curl->Result);
			$this->Return['ptn'] = "";
		}
		elseif(strtolower($curl->Reponse['status'])=='success')
		{
			$this->Return['error']=0;
			$this->status =	"PENDING";
			$this->Return['ptn'] = flottantetostr($curl->Reponse['id']);
		}
		
	}
    
	function Recharge()
	{
		
	
		$this->getToken();
        $this->Action = 'mp';
		$this->Type = 'marchand';
		
        $this->getPayTocken();
		
        $phone  = strtophone($this->Numero);
       $this->Numero = $phone['local'];
      
       
       
   
	   if($this->Simulation==1) $this->Montant = max(1,$this->Montant);
       uses_class('curl');
       $curl = new curl;
   
       $data = '{
        "subscriberMsisdn": "'.$this->Numero.'",
        "channelUserMsisdn": "'.$this->channelUserMsisdn[$this->Type].'",
        "amount":  "'.$this->Data['amount_total'].'",
        "description": "ViralPAY PAYMENT",
		"orderId": "'.$this->IDTransaction.'",
        "pin": "'.$this->PinOrange[$this->Type].'",
        "payToken": "'.$this->PayTocken.'",
        "notifUrl": "'.$this->CallBackUrl.'"
      }';
        $data = json_decode($data,true);
		
		
        //$this->Push();
        /**/
       $this->EndPoint = 'omcoreapis/1.0.2/'.$this->Action.'/pay';
       $curl->setUrl($this->BaseUrl.$this->EndPoint);
       $curl->addHeader("X-AUTH-TOKEN",base64_encode($this->ApiUser[$this->Type].':'.$this->ApiKey[$this->Type]));
       $curl->addHeader("Authorization","Bearer ".$this->Token);
       $curl->addHeader("Content-Type","application/json");
       $curl->setMethode('POST');
       $curl->setData($data);
       
       $curl->make();
       
	  
       
       
       if(!empty($curl->Reponse['data']['status'])) $statut = strtolower($curl->Reponse['data']['status']);
	   
       if($statut!='success')
	   {
			$return['error']['code']= $curl->ErrorNumber;
			$return['error']['reason']= trim($curl->Reponse['data']['txnmessage']);
			$return['error']['status']= "Failed";
			
			local_json($return);
	   }
       
       $reponse = $curl->Reponse;
	  
	   if(!empty($reponse['data']))
	   {
			$this->Return['error']=0;
			$this->status =	"PENDING";
			$this->Infos =	$reponse['data'];
			$this->Return['ptn'] = $this->PayTocken;   
			$this->PayTocken = $reponse['data']['payToken'];
			$this->Return['reponse']= array
			(
				"amount"=>$this->Montant,
				"status"=>'PENDING',
				"transaction"=> $this->IDTransaction,
				"reference"=> $this->Reference,
				"provider_number"=> $this->channelUserMsisdn[$this->Type],
				"provider_name"=> "ViralPAY",
				"uid"=> $this->PayTocken,
				"phone"=> $this->Numero
			);
	   }
	   else
	   {
			traceError($curl->Reponse['message']);
			$this->Return['error']=array
			(
				"status"=> "FAILED",
				"reason"=>"transaction error",
				"code"=> $curl->ErrorNumber
			);
	   }
       
		
	}
	function PaymentInit()
	{
		$this->Recharge();
	}
    function Retrait()
	{
		
		$this->setSimulation();
		$this->getToken();
        $this->Action = 'cashout';
		$this->Type = 'cash';
		
        $this->getPayTocken();
        $phone  = strtophone($this->Numero);
		
       $this->Numero = $phone['local'];
		
   
	   if($this->Simulation==1) $this->Montant = max(1,$this->Montant);
       
       

       uses_class('curl');
       $curl = new curl;
   
       $data = '{
        "subscriberMsisdn": "'.$this->Numero.'",
        "channelUserMsisdn": "'.$this->channelUserMsisdn[$this->Type].'",
        "amount":  "'.$this->Montant.'",
        "description": "ViralPAY PAYMENT",
        "orderId": "'.$this->IDTransaction.'",
        "pin": "'.$this->PinOrange[$this->Type].'",
        "payToken": "'.$this->PayTocken.'",
        "notifUrl": "'.$this->CallBackUrl.'"
      }';
        $data = json_decode($data,true);

		
        //$this->Push();
        /**/
       $this->EndPoint = 'omcoreapis/1.0.2/'.$this->Action.'/pay';
       $curl->setUrl($this->BaseUrl.$this->EndPoint);
       $curl->addHeader("X-AUTH-TOKEN",base64_encode($this->ApiUser[$this->Type].':'.$this->ApiKey[$this->Type]));
       $curl->addHeader("Authorization","Bearer ".$this->Token);
       $curl->addHeader("Content-Type","application/json");
       $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->channelUserMsisdn['cash'],
				"provider_name"=> "ViralPAY DEPOSIT",
				"uid"=> $this->Reference,
				"phone"=> $this->Numero
			);
		 
		}
		elseif(($curl->ErrorNumber)==500)
		{
			$this->Return['error']=array
			(
				"status"=> "FAILED",
				"reason"=>"The server did not respond correctly. ",
				"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 Depot()
	{
		
		$this->setSimulation();
		$this->getToken();
        $this->Action = 'cashin';
		$this->Type = 'cash';

        $this->getPayTocken();
        $phone  = strtophone($this->Numero);
       $this->Numero = $phone['local'];
		
       
	   if($this->Simulation==1) $this->Montant = max(1,$this->Montant);
       
       
      
       uses_class('curl');
       $curl = new curl;
   
       $data = '{
        "subscriberMsisdn": "'.$this->Numero.'",
        "channelUserMsisdn": "'.$this->channelUserMsisdn[$this->Type].'",
        "amount":  "'.$this->Montant.'",
        "description": "ViralPAY DEPOSIT",
		"orderId": "'.$this->IDTransaction.'",
        "pin": "'.$this->PinOrange[$this->Type].'",
        "payToken": "'.$this->PayTocken.'",
        "notifUrl": "'.$this->CallBackUrl.'"
      }';
        $data = json_decode($data,true);
      
        //$this->Push();
        /**/
       $this->EndPoint = 'omcoreapis/1.0.2/'.$this->Action.'/pay';
       $curl->setUrl($this->BaseUrl.$this->EndPoint);
       $curl->addHeader("X-AUTH-TOKEN",base64_encode($this->ApiUser[$this->Type].':'.$this->ApiKey[$this->Type]));
       $curl->addHeader("Authorization","Bearer ".$this->Token);
       $curl->addHeader("Content-Type","application/json");
       $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->channelUserMsisdn['cash'],
				"provider_name"=> "ViralPAY DEPOSIT",
				"uid"=> $this->Reference,
				"phone"=> $this->Numero
			);
		 
		}
		else{
		 $this->Return['error']=array
		 (
			 "status"=> "FAILED",
			 "reason"=>$curl->Reponse['errorMessage'],
			 "code"=> $curl->ErrorNumber
		 );
		 local_json($this->Return);
		}
		
	}
    function getPayTocken()
	{
        
        $this->EndPoint = 'omcoreapis/1.0.2/'.$this->Action.'/init';
       
        uses_class('curl');
		$curl = new curl;
		$data = 
			array
			(
				'grant_type' => 'password',
				'username' =>  $this->Login,
				'password'=>  $this->Password
			);
		
		

		
		$curl->setUrl($this->BaseUrl.$this->EndPoint);
		$curl->addHeader("X-AUTH-TOKEN",base64_encode($this->ApiUser[$this->Type].':'.$this->ApiKey[$this->Type]));
		$curl->addHeader("Authorization","Bearer ".$this->Token);
		$curl->addHeader("Content-Type","application/json");
		$curl->setMethode('POST');
		$curl->make();
		
		$reponse = $curl->Reponse;
		if(!empty($reponse['data']))
		{
			$this->PayTocken = $reponse['data']['payToken'];
			

		}
		else setError("Echec de l'opération : ");
	}
    function push()
    {
        $this->EndPoint = 'omcoreapis/1.0.2/'.$this->Action.'/pay';
        $curl->setUrl($this->BaseUrl.$this->EndPoint);
        $curl->addHeader("X-AUTH-TOKEN",base64_encode($this->ApiUser[$this->Type].':'.$this->ApiKey[$this->Type]));
        $curl->addHeader("Authorization","Bearer ".$this->Token);
        $curl->addHeader("Content-Type","application/json");
        $curl->setMethode('GET');
        $curl->setData($data);
        
        $curl->make();
        
		exit();
    }
	function getBalance()
	{
		//
		$this->EndPoint = 'user/balance';
		$this->getAutorization();
		uses_class('curl');
		
		$curl = new curl;
		$curl->setUrl($this->BaseUrl.$this->EndPoint);
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("Authorization","Basic ".$this->Autorization);
		
		$curl->setMethode('GET');
		$curl->setData($data);
		$curl->make();
		$this->Solde = doubleval($curl->Reponse['balance']);
		if($this->Solde <100000 ) traceError("Le solde CAMTEL est inférieur 100 000 XAF !");
		
	}
	private function realStatut($statut)
	{
		$teststatut = strtoupper($statut);
		switch($teststatut)
		{
			case  'SUCCESSFULL':
			case  'SUCCESS':
				$statut = 'SUCCESS';
			break;
			default: $statut = 'PENDING';
		}
		return $statut;
	}
	function getTransaction()
	{
		//
		$this->EndPoint = 'transaction/history';
		$this->getAutorization();
		uses_class('curl');
		
		$curl = new curl;
		$curl->setUrl($this->BaseUrl.$this->EndPoint);
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("Authorization","Basic ".$this->Autorization);
		
		$curl->setMethode('GET');
		$curl->setData($data);
		$curl->make();
		
		foreach($curl->Reponse['transactions'] as $trans)
		{
			
		}
		
	}
	function getStatus($current)
	{
		if(!is_array($current))
		{
			//$current = $sgbd->query("select * from transactions where MaviancePTN ='$current'")->row_array();
		}
	    $info = loadTransaction($current);
		global $sgbd;
		if(!is_array($current))	$current = $sgbd->query("select * from transactions where MaviancePTN ='$current' or transaction_id ='$current'")->row_array();
		$ptn = $current['transaction_id']; 
		
		$info = json_decode($current['Infos'],true);
		//if(strtolower($info['status'])=='failed') return 'failed';
		
		$deb = substr($ptn,0,2);
		
		switch($deb)
		{
			case 'MP':
				$this->Action = 'mp';
				$this->Type = 'marchand';
			break;
			case 'PO':
				$this->Action = 'cashout';
				$this->Type = 'cash';
			break;
			case 'PI':
				$this->Action = 'cashin';
				$this->Type = 'cash';
			break;
			default : return "PENDING";
		}
		
		$this->getToken();
		
		uses_class('curl');
		$this->EndPoint = 'omcoreapis/1.0.2/'.$this->Action;
		$curl = new curl;///acashout/paymentstatus/{payToken}
		$curl->setUrl($this->BaseUrl.$this->EndPoint."/paymentstatus/".$current['MaviancePTN']);
		$curl->addHeader("X-AUTH-TOKEN",base64_encode($this->ApiUser[$this->Type].':'.$this->ApiKey[$this->Type]));
		$curl->addHeader("Authorization","Bearer ".$this->Token);
       	$curl->addHeader("Content-Type","application/json");
		//$curl->addHeader("Authorization","Bearer ".$this->Token);		
		$curl->setMethode('GET');
		
		
		$curl->make();
		
		if($curl->ErrorNumber<=204)
		{
			
		}
		else
		{
			return "Failed";
			
		}
	}
	function simule()
	{
		if(!$this->Simulation) return false;
		uses_functions('random');
		$this->Return['error']=0;
		$this->Return['status'] =	"PENDING";
		$this->Return['ptn'] = 'SIM'.random_number(15,'8888');
		return true;
	}
	
	function customError($result)
	{
		switch($result['error'])
		{
			default : 
				traceError($result['error']);
				return "Service indisponible !";
		}
	}	
	function setMessage($number)
	{
		switch($number)
		{
			case 400:
				return "Invalid data was sent ";
			break;
			case 409:
				return "Conflict, duplicated reference id";
			break;
			case 401:
				return "This module may only work in production";
			break;
			
			default : return "Unknow error";
		}
	}
}



?>