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

	private $Url = "https://app.paydunya.com/";
	
		
	
	###########################################################
	function __construct()
	{
		$this->AccountPhone = "0713310044";
		$this->AccountPassword = "Azerty@2024";
		$this->AccountEmail = "ivoiredigitek@gmail.com";
		$this->CallBack = API_URL."callbacks/";
        $this->MasterKey = "68b8bzuJ-k2KM-IouK-u5Rr-46MjNALlIuuo";
        //$this->PrivateKey = "test_private_9TkrbJF1SAoHwMFKqTJ6yEE97TN";
		//$this->PublicKey = "test_public_UT3dwQOu5hDCsjZ9A7llmv67VtV";
        //$this->Token = "bmn392sIBqBzxmIWMJdH";
		//$this->Url = 'https://app.paydunya.com/sandbox-api/';
		uses_class('curl');
       $this->setProduction();

	}
	
	function setProduction()
	{
		$this->PrivateKey = "live_private_Zj64PmPy2aGmFaAYhk8mpC5D8qq";
		$this->PublicKey = "live_public_JGbiw2EXM4M6EDl85cM52xFO6Pu";
		$this->Token = "qOLnSLr0ZOz9sK0O5Caz";
		$this->Url = 'https://app.paydunya.com/api/';
	}
	function setSimulation()
	{
		$this->Production = 0;
	}
	public function setData($data)
	{
		$this->receiveData = 
		$this->Data = $data;
	
	}
	function getUID()
	{
		return getUID();
	}
	function getStatus($current)
	{
		global $sgbd;
		
		$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 = "v2/disburse/check-status";
			$data = '{"disburse_invoice": "'.$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/checkout-invoice/confirm/".$info['provider_id'];
			$data = '';
			if(empty($info['provider_id']))
			{
				$sgbd->query("update transactions set compensated = 1 where transaction_id='".$info['transaction_id']."'");
				return "FAILED";
			}
		} 
		
		uses_class('curl');
		
		$curl = new curl;
		$curl->setUrl($this->Url.$EndPoint);
        $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);
		
		if(!empty($data))
		{
			$curl->setMethode('POST');
			$curl->setData($data);
		}
		
		
		$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 getAutorisation()//transfert de credit 
	{
		if($this->Production==1) $this->setProduction();
		else $this->setSimulation();
		$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->Reponse['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->Production = 1;
		//$this->setProduction();
		$this->getOperatorOut($this->Data['operator'],$this->Data['country']);
		
		$this->order_id =$this->Data['order_id'];
        uses_class('curl');
		
		$curl = new curl;
		$curl->setUrl($this->Url."v2/disburse/get-invoice");
        $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 = '{"account_alias" : "'.$this->Data['phone_number'].'", "amount" : '.$this->Montant.', "withdraw_mode" :"'.$this->EndPoint.'", "callback_url": "'.$this->Data['return_url'].'"}';  
		   // $data = '{"disburse_invoice": "hwTHAS0WvTmTaYT2zDoO ", " disburse_id ": "456678900309" }';
		$curl->setMethode('POST');
		$curl->setData($data);
		$curl->make();

		$Reponse = $curl->Reponse;
		
		
		if($Reponse['response_code']=='00')
		{
			
			$this->PayToken = $Reponse['disburse_token'];
			
			
			$curl = curl_init();
			$data = ' {"disburse_invoice": "'.$this->PayToken.'", " disburse_id ": "'.$this->IDTransaction.'" }';
			$curl = new curl;
			$curl->setUrl($this->Url."v2/disburse/submit-invoice");
			$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);
				
			
			$curl->setMethode('POST');
			$curl->setData($data);
		
			$curl->make();
			
	
			$Reponse = $curl->Reponse;
			
			if($Reponse['response_code']=='00')
			{
				$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_transaction_id"=> $Reponse['transaction_id'],
					"provider_message"=> $Response['message'],
					"number"=> $this->Numero
				);
				if($this->Data['operator']=='wave')
				{
					$this->Return['reponse']['provider_link']= $Reponse['provider_link'];
				}
			}
			else
			{
				$this->Return['error']=array
				(
					"status"=> "FAILED",
					"reason"=>"Transaction failed",
					"provider_error"=>json_encode($curl->Reponse),
					"reference_id"=> $this->Reference,
					"order_id"=> $this->order_id,
				);
			}
		}
		else
		{
			$this->Return['error']=array
				(
					"status"=> "FAILED",
					"reason"=>"Transaction failed",
					"provider_error"=>json_encode($curl->Reponse),
					"reference_id"=> $this->Reference,
					"order_id"=> $this->order_id,
				);
		}
		
	}
	function getOperatorIn($opera,$country)
	{
		
		$compo = $opera.'-money-'.$country;
		switch($compo)
		{
			//COTE D'IVOIRE
			case 'orange-money-ci':
				if(empty($this->Data['otp_code']))
				{
					$this->Return['error']=array
					(
						"status"=> "FAILED",
						"reason"=>"cette opération neccessite un code pin",
						"reference_id"=> $this->Reference
					);
					//local_json($this->Return);
				}
				
				$this->EndPoint = 'orange-money-ci';
				$this->Request = '{
									"orange_money_ci_customer_fullname": "Viral PAY",
									"orange_money_ci_email": "'.$this->AccountEmail.'",
									"orange_money_ci_phone_number": "'.$this->Data['phone_number'].'",
									"orange_money_ci_otp": "'.$this->Data['otp_code'].'",
									"payment_token": "'.$this->PayToken.'"
									}';
									
	
			break;
			case 'moov-money-ci':
				$this->EndPoint = 'moov-ci';
				$this->Request = '{
										"moov_ci_customer_fullname": "Viral PAY",
										"moov_ci_email": "'.$this->AccountEmail.'",
										"moov_ci_phone_number": "'.$this->Data['phone_number'].'",
										"payment_token": "'.$this->PayToken.'"
									}';
			break;
			case 'wave-money-ci':
				$this->EndPoint = 'wave-ci';
				$this->Request = '{
										"wave_ci_fullName": "Viral PAY",
										"wave_ci_email": "'.$this->AccountEmail.'",
										"wave_ci_phone": "'.$this->Data['phone_number'].'",
										"wave_ci_payment_token" : "'.$this->PayToken.'"
									}';
			break;

			
			//SENEGAl
			case 'orange-money-sn':
				$this->EndPoint = 'new-orange-money-senegal';
				$this->Request = '{
									"customer_name": "Viral PAY",
									"customer_email": "'.$this->AccountEmail.'",
									"phone_number": "'.$this->Data['phone_number'].'",
									"authorization_code": "'.$this->Data['otp_code'].'",
									"invoice_token": "'.$this->PayToken.'",
									"api_type": "OTPCODE"
									}';
			break;
			case 'free-money-sn':
				$this->EndPoint = 'free-money-senegal';
				$this->Request = '{
									"customer_name": "Viral PAY",
									"customer_email":  "'.$this->AccountEmail.'",
									"phone_number": "'.$this->Data['phone_number'].'",
									"payment_token": "'.$this->PayToken.'"
									}';
			break;
			
			
			case 'wave-money-sn':
				$this->EndPoint = 'wave-senegal';
				$this->Request = '
									{
									"wave_senegal_fullName": "Viral PAY",
									"wave_senegal_email":"'.$this->AccountEmail.'",
									"wave_senegal_phone":"'.$this->Data['phone_number'].'",
									"wave_senegal_payment_token": "'.$this->PayToken.'"
									}';
			break;

			//BURKINA FASO
			case 'orange-money-bf':
				$this->EndPoint = 'orange-money-burkina';
				$this->Request = '{
									"name_bf":  "Viral PAY",
									"email_bf": "'.$this->AccountEmail.'",
									"phone_bf": "'.$this->Data['phone_number'].'",
									"otp_code": "'.$this->Data['otp_code'].'",
									"payment_token": "'.$this->PayToken.'"
									}';
			break;
			case 'moov-money-bf':
				$this->EndPoint = 'moov-burkina';
				$this->Request = '{
									"moov_burkina_faso_fullName":   "Viral PAY",
									"moov_burkina_faso_email": "'.$this->AccountEmail.'",
									"moov_burkina_faso_phone_number":"'.$this->Data['phone_number'].'",
									"moov_burkina_faso_payment_token": "'.$this->PayToken.'"
									}';
			break;
			//BENIN
			case 'moov-money-bj':
				$this->EndPoint = 'moov-benin';
				$this->Request = '{
									"moov_benin_customer_fullname": "Viral PAY",
									"moov_benin_email": "'.$this->AccountEmail.'",
									"moov_benin_phone_number":"'.$this->Data['phone_number'].'",
									"payment_token": "'.$this->PayToken.'"
									}';
			break;
			case 'mtn-money-bj':
				$this->EndPoint = 'mtn-benin';
				$this->Request = '{
									"mtn_benin_customer_fullname": "Viral PAY",
									"mtn_benin_email": "'.$this->AccountEmail.'",
									"mtn_benin_phone_number": "'.$this->Data['phone_number'].'",
									"mtn_benin_wallet_provider": "MTNBENIN",
									"payment_token":  "'.$this->PayToken.'"
									}
									';
			break;
			//TOGO
			case 'tmoney-money-tg':
				$this->EndPoint = 't-money-togo';
				$this->Request = '{
									"name_t_money": "Viral PAY",
									"email_t_money": "'.$this->AccountEmail.'",
									"phone_t_money": "'.$this->Data['phone_number'].'",
									"payment_token":"'.$this->PayToken.'"
									}';
			break;
			case 'moov-money-tg':
				$this->EndPoint = 'moov-togo';
				$this->Request = '{
									"moov_togo_customer_fullname": "Viral PAY",
									"moov_togo_email": "'.$this->AccountEmail.'",
									"moov_togo_customer_address": "Douala",
									"moov_togo_phone_number":"'.$this->Data['phone_number'].'",
									"payment_token": "'.$this->PayToken.'"
									}';
			break;
			//MALI
			case 'orange-money-ml':
				$this->EndPoint = 'orange-money-mali';
				$this->Request = '{
									"orange_money_mali_customer_fullname": "Viral PAY",
									"orange_money_mali_email": "'.$this->AccountEmail.'",
									"orange_money_mali_phone_number": "'.$this->Data['phone_number'].'",
									"orange_money_mali_customer_address" : "Douala",
									"payment_token":  "'.$this->PayToken.'"
									"orange_money_mali_wallet_otp" : "'.$this->Data['otp_code'].'"
								}';
			break;

			case 'orange-money-ml':
				$this->EndPoint = 'orange-money-mali';
				$this->Request = '{
									"orange_money_mali_customer_fullname": "Viral PAY",
									"orange_money_mali_email": "'.$this->AccountEmail.'",
									"orange_money_mali_phone_number": "'.$this->Data['phone_number'].'",
									"orange_money_mali_customer_address" : "Douala",
									"payment_token":  "'.$this->PayToken.'"
									"orange_money_mali_wallet_otp" : "'.$this->Data['otp_code'].'"
								}';
			break;
			
			
			case 'moov-money-ml':
				$this->EndPoint = 'moov-mali';
				$this->Request = '{
									"moov_ml_customer_fullname": "Viral PAY",
									"moov_ml_email": "'.$this->AccountEmail.'",
									"moov_ml_phone_number": "'.$this->Data['phone_number'].'",
									"moov_ml_customer_address" : "Douala",
									"payment_token": "'.$this->PayToken.'"
									}';
			break;
			//
			case 'mtn-money-ci':
				$this->EndPoint = 'mtn-ci';
				$this->Request = '{"mtn_ci_customer_fullname": "Viral PAY", "mtn_ci_email": "'.$this->AccountEmail.'", "mtn_ci_phone_number": "'.$this->Data['phone_number'].'", "mtn_ci_wallet_provider": "MTNCI", "payment_token": "'.$this->PayToken.'"}';
			break;
			
			default : 
			$this->Return['error']=array
			(
				"status"=> "FAILED",
				"reason"=>"operation $compo non pris en charge",
				"reference_id"=> $this->Reference
			);
			//local_json($this->Return);
		}
		$json = json_decode($this->Request,true);
		$this->Request = json_encode($json);
		
	}
	function getOperatorOut($opera,$country)
	{
		
		$compo = $opera.'-money-'.$country;
		
		switch($compo)
		{
			case 'orange-money-ci':
				$this->EndPoint = 'orange-money-ci';
			break;
			case 'moov-money-ci':
				$this->EndPoint = 'moov-ci';
			break;
			case 'wave-money-ci':
				$this->EndPoint = 'wave-ci';

			break;
			case 'mtn-money-ci':
				$this->EndPoint = 'mtn-ci';
			break;
			case 'orange-money-sn':
				$this->EndPoint = 'orange-money-senegal';
			break;
			case 'free-money-sn':
				$this->EndPoint = 'free-money-senegal';
			break;
			case 'expresso-money-sn':
				$this->EndPoint = 'expresso-senegal';
			break;
			case 'wave-money-sn':
				$this->EndPoint = 'wave-senegal';
			break;
			case 'mtn-money-bj':
				$this->EndPoint = 'mtn-benin';
			break;
			case 'moov-money-bj':
				$this->EndPoint = 'moov-benin';
			break;
			case 'tmoney-money-tg':
				$this->EndPoint = 't-money-togo';
			break;
			case 'moov-money-tg':
				$this->EndPoint = 'moov-togo';
			break;
			case 'orange-money-ml':
				$this->EndPoint = 'orange-money-mali';
			break;
			case 'orange-money-bf':
				$this->EndPoint = 'orange-money-burkina';
			break;
			case 'moov-money-bf':
				$this->EndPoint = 'moov-money-burkina';
			break;
			
			default : 
			$this->Return['error']=array
			(
				"status"=> "FAILED",
				"reason"=>"operation $compo non pris en charge",
				"reference_id"=> $this->Reference
			);
			//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->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->Data['amount_total'].', "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);
		
		$this->Return = iso_encode($this->Return);
		echo (json_encode($this->Return,JSON_FORCE_OBJECT|JSON_UNESCAPED_UNICODE));
		exit();
	}
}
?>