<?php
class pakhpay
{
	private $error   = false; 
	private $Url = 'https://api.pakhpay.com/';//
	

	###########################################################
	function __construct()
	{


	}
	public function setData($data)
	{
		$this->receiveData = 
		$this->Data = $data;
	
	}
	
	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);
		

		$debut = substr($info['transaction_id'],0,3);

		$this->getToken();
	
		
    
		if($info['operator']=='tmoney') $info['operator'] = 'togocom';
		$type = $debut;
		
		if($type=='POM')
		{
			if(empty($info['provider_id']))
				{
					$sgbd->query("update transactions set compensated = 1 where transaction_id='".$info['transaction_id']."'");
					return "FAILED";
				}
			$EndPoint = "v1/bulk/transfers/status";
			$data = '{"batch_number": "'.$info['provider_id'].'"}';
		}elseif($type=='PIM')
		{
			if(empty($info['provider_id']))
			{
				$sgbd->query("update transactions set compensated = 1 where transaction_id='".$info['transaction_id']."'");
				return "FAILED";
			}
			$EndPoint = "v1/payment/status";
			$data = '{"order_id": "'.$info['provider_id'].'"}';
		} 
		
		$data = json_decode($data,true);
		
	
		uses_class('curl');
		
		$curl = new curl;
		$curl->setUrl($this->Url.$EndPoint);
        $curl->addHeader("Content-Type","application/json");

		$curl->addHeader("Authorization","Bearer ".$this->Token);

		
		if(!empty($data))
		{
			$curl->setMethode('GET');
			$curl->setDataUrl($data);
		}
		
		
		$curl->make();	


		return "PENDING";

	}

	function getToken()//transfert de credit 
	{
		uses_class('curl');
		

		
		//CREATION ET SAUVEGARDE DU ACCESS_TOCKEN
        $data = array("grant_type"=>"client_credentials","client_id"=>"7","client_secret"=>"TIgpPBHeqkmCDXmKEYT6mv8pV1xfTVLE7naCZzze");
		$curl = new curl;
		$curl->setUrl($this->Url."oauth/token/");//'https://api.pakhpay.com//token
		$curl->addHeader("Accept","application/json");

		$curl->setMethode('POST');
        $curl->setDataUrl($data);
       
		$curl->make();	
		$this->Token = $curl->Response->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 
	{
		
		if(empty($this->Reference))
		{
			$this->Reference = $this->IDTransaction;
		}
		$this->Confirm = 1;
		$this->ReferenceID = getUUID();
		$this->Module = 'collection';
		$phone = strtophone($this->Numero);
		$this->Numero = $phone['phone'];
		

		
		$this->getToken();
		$this->Token;
		
    
		if($this->Data['operator']=='tmoney') $this->Data['operator'] = 'togocom';
		//REALISATION DE LA TRANSACTION
		$curl = new curl;
		$curl->setUrl($this->Url."api/v1/bulk/transfers");
		$curl->addHeader("Authorization","Bearer ".$this->Token);
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("Accept","application/json");
       
		$data = json_encode(array(
            "country_iso_code"  => $this->Data['country'],
            "operator"  => $this->Data['operator'],
            "msisdn"  => $this->Data['national_phone'],
            "amount"  =>$this->Montant,
            "otp_code" => $this->Data['otp_code'],
            "customer_ref" =>"VIRAL"
            ));    
		$data = '{ 
					"country_iso_code": "'.$this->Data['country'].'",
					"customer_ref": "VIRAL",
					 "data":
					 	[
							{
								"beneficiaryFirstName":"VIRAL",
								"beneficiaryLastName":"Pay",
								"beneficiaryAddress":"Bonamousadi", 
								"beneficiaryMobileNumber":"'.$this->Data['national_phone'].'",
								"amount": '.$this->Montant.',
								"mno":"'.$this->Data['operator'].'"
							}
						]
				}';
		
				
		$curl->setMethode('POST');
		$curl->setData($data);
        $curl->make();

        $Response = $curl->Reponse;
 
		//$curl->make();
        if($curl->ErrorNumber<300)
        {
            $this->Return['reponse']= array
            (
                "amount"=>$this->Montant,
                "status"=>'PENDING',
                "transaction_id"=> $this->IDTransaction,
                "order_id"=> $this->order_id,
                "provider_id"=>$Response['order-id'],
				"provider_code"=>$this->Data['provider_code'],
                "provider_message"=> $Response['message'],
                "number"=> $this->Numero
            );
        }
		elseif($curl->ErrorNumber==403)
		{
			$error = "Acces forbidden";
			if(!empty($curl->Reponse['message'])) $error = $curl->Reponse['message'];
			$this->Return['error']=array
            (
                "status"=> "FAILED",
               "provider_error"=>json_encode($curl->Reponse),
				"reason"=>$error,
                "order_id"=> $this->Data['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,
            );
            //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->Confirm = 1;
		$this->ReferenceID = getUUID();
		$this->Module = 'collection';
		$phone = strtophone($this->Numero);
		$this->Numero = $phone['phone'];
		

		
		$this->getToken();
		$this->Token;
    
		if($this->Data['operator']=='tmoney') $this->Data['operator'] = 'togocom';
		//REALISATION DE LA TRANSACTION
		$curl = new curl;
		$curl->setUrl($this->Url."api/v1/payment");
		$curl->addHeader("Authorization","Bearer ".$this->Token);
		$curl->addHeader("Content-Type","application/json");
		$curl->addHeader("Accept","application/json");
        
		
		$data = array(
            "country_iso_code"  => $this->Data['country'],
            "operator"  => $this->Data['operator'],
            "msisdn"  => $this->Data['national_phone'],
            "amount"  =>$this->Data['amount_total'],
            "customer_ref" =>"VIRAL"
            );    
			if($this->Data['operator']=='orange') $data['otp_code']=$this->Data['otp_code'];
		$curl->setMethode('POST');
		$curl->setData($data);
        $curl->make();
		

        $Response = $curl->Reponse;
 
		
		if($curl->ErrorNumber<300)
        {
            $this->Return['reponse']= array
            (
                "amount"=>$this->Montant,
                "status"=>'PENDING',
                "transaction_id"=> $this->IDTransaction,
                "order_id"=> $this->Data['order_id'],
                "provider_id"=>$Response['order-id'],
				"provider_code"=>$this->Data['provider_code'],
                "provider_message"=> $Response['message'],
                "number"=> $this->Numero
            );
            if($this->Data['operator']=='wave') $this->Return['reponse']['provider_link']= $this->PayLink;
			
        }
		elseif($curl->ErrorNumber==403)
		{
			$error = "Acces forbidden";
			if(!empty($curl->Reponse['message'])) $error = $curl->Reponse['message'];
			$this->Return['error']=array
            (
                "status"=> "FAILED",
               "provider_error"=>json_encode($curl->Reponse),
                "reason"=>$error,
                "order_id"=> $this->Data['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->Data['order_id'],
            );
            //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();
	}
}
?>