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

	private $Url = "https://api.fedapay.com/";
	
		
	
	###########################################################
	function __construct()
	{
		$this->ClientID = 'qPP5cb5sIviTJ4_mPeMON1TbKSga';
		$this->ClientSecret = 'sk_live_41xMG6pigS6jBr_J9r9lqMQk';
		$this->AccountNumber = '6e88b13d-c3a9-44b7-bc2c-ceced60f8e0a'; 
		$this->ClientCode = 'VIRALPAY'; 
		
	}
	public function setData($data)
	{
		$this->receiveData = 
		$this->Data = $data;
	
	}
	function setProduction()
	{
		$this->PublicKey = "pk_live_W_7eBEeWtSVzMnTp096vCvPG";
		$this->PrivateKey = "sk_live_41xMG6pigS6jBr_J9r9lqMQk";
		
		$this->Url = 'https://app.paydunya.com/api/';
	}
	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 = loadTransaction($current);
		
		$type = substr($info['transaction_id'],0,3);
		/*$infos = json_decode($current['infos'],true);
		if(empty($infos['transaction_id'])) $infos['transaction_id']=$infos['transaction'];
		
		if(empty(['provider_id'])) return 'PENDING';*/
		
		if($type=='POM')
		{
			$EndPoint = "v1/payouts/".$info['provider_id'];
			if(empty($info['provider_id']))
			{
				$sgbd->query("update transactions set compensated = 1 where transaction_id='".$info['transaction_id']."'");
				return "FAILED";
			}
		}elseif($type=='PIM')
		{
			$EndPoint = "v1/transactions/".$info['provider_id'];
			
			if(empty($info['provider_id']))
			{
				$sgbd->query("update transactions set compensated = 1 where transaction_id='".$info['transaction_id']."'");
				return "FAILED";
			}
		} 
		
		$curl = new curl;
		$curl->setUrl($this->Url."".$EndPoint);
		
		$curl->addHeader("Authorization","Bearer ".$this->ClientSecret);
		$curl->addHeader("Content-Type","application/json ");		
		$curl->setMethode('GET');
		
		$curl->make();
		
		$status = strtoupper($curl->Reponse['data']['status']);
		
		switch($status)
		{
			case 'COMPLETED':
			case 'SUCCESSFUL':
			case 'SUCCESS':
				$status = 'SUCCESS';
			break;
			case 'FAILED':
				$status = 'FAILED';
			break;
			default: 
				$status = "PENDING";
		}
		
		if(!empty($status)) 
		{
			return $status;
		}
		elseif($curl->ErrorNumber>300)
		{
			return 'FAILED';
		}
		
		return "PENDING";

	}
	
	function getBalance()
	{
		$this->Solde = $this->getBalanceMTN();
	}
	
	
	function getMethode()//transfert de credit 
	{
		if(strtolower($this->Data['country'])!='bj') $this->Data['methode']=$this->Data['operator'].'_'.$this->Data['country'];
		else 
		{
			$this->Data['methode']=$this->Data['operator'];
		}
	}

	function getToken()//transfert de credit 
	{

		uses_class('curl');
		//CREATION ET SAUVEGARDE DU ACCESS_TOCKEN
		$curl = new curl;
		$curl->setUrl($this->Url."v1/".$this->Type);
		
		$curl->addHeader("Authorization","Bearer ".$this->ClientSecret);
		$curl->addHeader("Content-Type","application/json ");
	
        $data = array(
			"description"=>"Transaction for VIRALPAY",
			"amount"=>$this->Data['amount'],
			"currency"=> array("iso"=>$this->Data['currency']),
			"callback_url"=>CALLBACK,
			"customer"=>array
							(
								"firstname"=>"VIRALPAY",
								"lastname"=>"Cameroun",
								"email"=>"it@viralpay.cm",
								"phone_number"=>array(
														"number" =>$this->Data['international_phone'],
														"country" =>$this->Data['country']
													)
							)
		);
		
		$curl->setMethode('POST');

		$curl->setData($data);
		$curl->make();
		
	
		
		if(!empty($curl->Reponse['v1/transaction']))
		{
			$this->PayinID = 
			$transaction_id = $curl->Reponse['v1/transaction']['id'];
			$curl = new curl;
			$curl->setUrl($this->Url."v1/".$this->Type."/$transaction_id/token");
			
			$curl->addHeader("Authorization","Bearer ".$this->ClientSecret);
			$curl->addHeader("Content-Type","application/json ");
		
			$data = array(
				"description"=>"Transaction for VIRALPAY",
				"phone_number"=>$this->Data['international_phone'],
				"amount"=>$this->Data['amount'],
				"currency"=> array("iso"=>$this->Data['currency']),
				"callback_url"=>CALLBACK,
				"customer"=>array("email"=>"it@viralpay.cm")
			);
			
			$curl->setMethode('POST');

			$curl->make();	
			$this->Token = $curl->Reponse['data']['token'];
			
			if(!empty($this->Token))
			{
				$this->getMethode();
				
			}
		}
		else
		{

		}
		
	}
	function getTokenOut()//transfert de credit 
	{

		uses_class('curl');
		//CREATION ET SAUVEGARDE DU ACCESS_TOCKEN
		$curl = new curl;
		$curl->setUrl($this->Url."v1/payouts");
		
		$curl->addHeader("Authorization","Bearer ".$this->ClientSecret);
		$curl->addHeader("Content-Type","application/json ");
	
        $data = array(
			"mode"=>$this->Data['operator'],
			"amount"=>$this->Data['amount'],
			"currency"=> array("iso"=>$this->Data['currency']),
			"callback_url"=>CALLBACK,
			"customer"=>array("email"=>"it@viralpay.cm")
		);

		$data = array(
			"amount"=>$this->Data['amount'],
			"currency"=> array("iso"=>$this->Data['currency']),
			"mode"=>$this->Data['operator'],
			"customer"=>array
							(
								"firstname"=>"VIRALPAY",
								"lastname"=>"Cameroun",
								"email"=>"it@viralpay.cm",
								"phone_number"=>array(
														"number" =>$this->Data['international_phone'],
														"country" =>$this->Data['country']
													)
							)
		);
		
		$curl->setMethode('POST');

		$curl->setData($data);
		$curl->make();
	
		
		if(!empty($curl->Reponse['v1/payout']))
		{
			$this->PayoutID = $curl->Reponse['v1/payout']['id'];
				
			
			
		}

		
	}
	
	function Depot()//transfert de credit 
	{
		$this->Type = 'payouts';
		$this->getTokenOut();
		$curl = new curl;
		$curl->setUrl($this->Url."v1/payouts/start");
		
		$curl->addHeader("Authorization","Bearer ".$this->ClientSecret);
		$curl->addHeader("Content-Type","application/json ");
	
		$data = '{
				"payouts" : [{ "id": '.$this->PayoutID.' }]
				}';
		
		$curl->setMethode('PUT');
		$curl->setData($data);
		$curl->make();

		$provider_id = $this->PayoutID;
		if($curl->ErrorNumber<=203)
		{
			$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"=>$provider_id,
				"provider_code"=>$this->Data['provider_code'],
               
            );
		}
		else
		{
			$this->Return['error']=array
			(
				"status"=> "FAILED",
				"reason"=>$error,
				"provider_error"=>json_encode($curl->Reponse),
				"code"=> $curl->ErrorNumber
			);
		}
	
	}
	
	function Retrait()
	{
		$this->Type = 'transactions';
		$this->getToken();

		$curl = new curl;
		$curl->setUrl($this->Url."v1/".$this->Data['methode']);
		
		$curl->addHeader("Authorization","Bearer ".$this->ClientSecret);
		$curl->addHeader("Content-Type","application/json ");
	
		$data = array(
			"token"=>$this->Token
		);
		
		$curl->setMethode('POST');
		$curl->setData($data);
		$curl->make();	

	
	
		$provider_id = $this->PayinID;
		if(!empty($provider_id))
		{
			$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"=>$provider_id,
				"provider_code"=>$this->Data['provider_code'],
               
            );
		}
		else{
			$error = "transaction failed";
			
			

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

		
			
		
	}
	
	function PaymentInit()
	{
		$this->Recharge();
	}
	
	function Recharge()//transfert de credit 
	{
		//TEST LIVE MTN DIRECT
		if(empty($this->Reference))
		{
			$this->Reference = $this->IDTransaction;
		}
		$this->order_id =$this->Data['order_id'];

		//REALISATION DE LA TRANSACTION
		$curl = new curl;
		$curl->setUrl($this->Url."v1/checkout-invoice/create");
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("PAYDUNYA-MASTER-KEY",$this->MasterKey);
		$curl->addHeader("PAYDUNYA-PRIVATE-KEY",$this->PrivateKey);
		$curl->addHeader("PAYDUNYA-TOKEN",$this->Token);
		$data = '{"invoice": {"total_amount": '.$this->Montant.', "description": "ViralPAY PAYMENT"},"store": {"name": "ViralPAY"}}';  
		$curl->setMethode('POST');
		$curl->setData($data);
		
		
		$curl->make();

		
		$Reponse = $curl->Reponse;
		
		if($Reponse['data']['response_code']=='00')
		{
			$this->PayToken = $Reponse['data']['token'];
			
			
			$this->getOperatorIn($this->Data['operator'],$this->Data['country']);
			$curl = new curl;
			$curl->setUrl($this->Url."v1/softpay/".$this->EndPoint);
			$curl->addHeader("Content-Type","application/json");

			$data = $this->Request;

			$curl->setMethode('POST');
			$curl->setData($data);
			$curl->make();
			
		
			$Response = $curl->Reponse;
			
			if($Response['success']==1)
			{
				$this->Return['reponse']= array
				(
					"amount"=>$this->Montant,
					"status"=>'PENDING',
					"transaction_id"=> $this->IDTransaction,
					"order_id"=> $this->order_id,
					"provider_id"=> $this->PayToken,
					"provider_code"=>$this->Data['provider_code'],
					"provider_message"=> $Response['message'],
					"number"=> $this->Numero
				);
				if($this->Data['operator']=='wave') $this->Return['reponse']['provider_link']= $Response['url'];
			}
			else
			{
				$this->Return['error']=array
				(
					"status"=> "FAILED",
					"provider_error"=>json_encode($curl->Reponse),
					"reason"=>"transaction failed",
					"order_id"=> $this->order_id,
				);
				//local_json($this->Return);
			}

		}
		else
		{
			$this->Return['error']=array
				(
					"status"=> "FAILED",
					"provider_error"=>json_encode($curl->Reponse),
					"reason"=>"transaction failed",
					"order_id"=> $this->order_id,
				);
		}

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