<?php
include_once $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'config.php';

class help2PayAPI extends System {
	private $callback_url		= H2P_CALLBACKURL;
	
	private $payoutUrl          = NO_STRING;
	private $ip   				= NO_STRING;
	private $merchant_code		= NO_STRING;
	private $security_code		= NO_STRING;


	public function __construct(){
	    parent::__construct();
	    $this -> fillCredentials();
	}
	
	private function fillCredentials(){
	    $h2pSettings = $this -> getRowData($this -> accessSelect("SELECT_DEV_SETTING", ["help2pay_conf"]));
	    
	    if($this -> isLoopData($h2pSettings)){
	        $h2pSettings = json_decode($this -> getColumnData($h2pSettings, "dev_setting_value"));
	        
	        $this -> payoutUrl         = $h2pSettings -> payout_url;
	        $this -> ip                = $h2pSettings -> ip_address;
	        $this -> merchant_code     = $h2pSettings -> merchant_code;
	        $this -> security_code     = $h2pSettings -> security_code;
	        
	        $this -> payoutUrl         = str_replace("{merchantcode}", $this -> merchant_code, $this -> payoutUrl);
	    }
	}
	
    /*-------------------------------------------------------------------------
     * @function_name: generateRequestData
     * "@description : generates the request data
     * @parameter    : data and key
     * @return       : array
    -------------------------------------------------------------------------*/
    public function generateRequestData($data,$key){
		$requestData = array(
			'Key'					=> $key,
			'ClientIP'				=> $this -> ip,
			'ReturnURI'				=> $this -> callback_url,
			'MerchantCode'			=> $this -> merchant_code,
			'TransactionID'			=> $data['TransactionID'],
			'CurrencyCode'			=> $data['CurrencyCode'],
			'MemberCode'			=> $data['MemberCode'],
			'Amount'				=> $data['Amount'],
			'TransactionDateTime'	=> $data['TransactionDateTime2'],
			'BankCode'				=> $data['BankCode'],
			'toBankAccountName'		=> $data['toBankAccountName'],
			'toBankAccountNumber'	=> $data['toBankAccountNumber'],
		);

        return $requestData;
    }

	/*-------------------------------------------------------------------------
	 * @function_name: generateKey
	 * "@description : Generates key for the request data
	 * @parameter    : $data array
	 * @return       : key string
	-------------------------------------------------------------------------*/

	public function generateKey($data, &$rawKeyForm){
    	$strKey = NO_STRING;
    
    	$transaction_id			= $data['TransactionID'];
    	$member_code			= $data['MemberCode'];
    	$amount					= $data['Amount'];
    	$currency				= $data['CurrencyCode'];
    	$transaction_date_time	= $data['TransactionDateTime'];
    	$bank_account_number	= $data['toBankAccountNumber'];
    
    	$strKey = $this -> merchant_code
    	   .$transaction_id
    	   .$member_code
    	   .$amount
    	   .$currency
    	   .$transaction_date_time
    	   .$bank_account_number
    	   .$this -> security_code;
    	
    	$rawKeyForm = $strKey;   
    
    	$key = md5($strKey);

		return $key;
	}
    /*-------------------------------------------------------------------------
     * @function_name: submitPayoutRequest
     * "@description : Submits the request to Help2Pay
     * @parameter    : generated data array from generateRequestData function
     * @return       : array response data ; bool - false (if creation is successful, returns response data else returns false)
    -------------------------------------------------------------------------*/
    public function submitPayoutRequest($data){
        //set curl parameters
        $ch = curl_init($this -> payoutUrl); //请求的URL地址
        
		curl_setopt_array($ch, [
		    CURLOPT_URL => $this -> payoutUrl,
		    CURLOPT_RETURNTRANSFER => true,
		    CURLOPT_FOLLOWLOCATION => true,
		    CURLOPT_ENCODING => "utf8",
		    CURLOPT_POSTFIELDS => http_build_query($data),
		    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		    CURLOPT_CUSTOMREQUEST => "POST",
		    CURLOPT_HTTPHEADER => [
		        "Content-type: application/x-www-form-urlencoded"
		    ]
		]);
		
        $responseData = curl_exec($ch);

        //check if curl failed
        if(curl_errno($ch)) {
            return false;
	    }
        curl_close($ch);
        
        if(count($responseData) > 0) {
            return $responseData;
        } else {
            return false;
        }
    }
}
