<?php

function EGetData($data,$PayID){
    global $dbo;
    $dataarr = $dbo->DataArray($data,"`",$keyItem = "~");
    if(isset($dataarr[''.$PayID]))return $dataarr[''.$PayID];
    if(isset($dataarr['-1']))return $dataarr['-1'];
    return "";
}

function EInit($param){
    global $dbo;
    $transnums = generateTransInfoOnly();
    return ["Ref"=>$transnums[1]];
}


function EPayNow($param){
    
        //Generate your own unique transId per transaction.
$time = time();
$transId = $param["Ref"];
//10000000000001etz1554379169webhttp://localhost:81/projects/Webconnect/response.phpRXeQfW7pf4PmIi9w
//10000000000001etz1554379169webhttp://localhost:81/projects/Webconnect/response.phpRXeQfW7pf4PmIi9w
//if ($transId==null) $transId="Peter123456787898fff7tt";

$terminalId = EGetData($param["TERMINALID"],$param["PayID"]);
//return ["Markup"=>$terminalId];
//if ($terminalId == null) $terminalId = "0000000001";
//$success = $HTTP_POST_VARS["SUCCESS"];
$amount = $param["Amt"];
$responseurl = explode("?",$param["FinishUrl"]);
$responseurl = $responseurl[0];
//if ($amount == null) $amount = 1000;
//session_register("TOTAL");
//echo "Amount Charged: ".$amount;
$descr = $param["ItemDescr"];
//if ($descr == null) $descr = "Payment";
$secret_key=EGetData($param["SECRETKEY"],$param["PayID"]);
$str=$amount.$terminalId.$transId.$responseurl.$secret_key;
$checksum=md5($str);
$cheksum=md5($amount.$terminalId.$transId.$responseurl.$secret_key);
$posturl = EGetData($param["POSTURL"],$param["PayID"]);
$logo = !isset($param['LOGO'])?EGetData($param["LOGOURL"],$param["PayID"]):$param['LOGO'];

		$form =  "<form method='POST' action='".$posturl."'>
            <input type='hidden' name='TERMINAL_ID' value='".$terminalId."'>
            <input type='hidden' name = 'TRANSACTION_ID' value='".$transId."'>
            <input type='hidden' name = 'AMOUNT' value='".$amount."'>
            <input type='hidden' name = 'DESCRIPTION' value='".$descr."'>
            <input type='hidden' name = 'EMAIL' value='".$param["Email"]."'>
            <input type='hidden' name = 'CURRENCY_CODE' value='NGN'>
            <input type='hidden' name = 'RESPONSE_URL' value='".$responseurl."'>
            <input type='hidden' name = 'CHECKSUM' value='".$cheksum."'> 
            <input type='hidden' name = 'FULL_NAME' value='".$param["Name"]."'> 
            <input type='hidden' name = 'LOGO_URL' value='".$logo."'>
            <input type='hidden' name = 'PHONENO' value='".$param["Phone"]."'>
            
            </form>
            <script language='javascript'>
            //var form = document.forms[0];
            //form.submit()</script>";
	return ["Markup"=>$form];
}

function EQueryPay($params){
    global $dbo;
	//global $phpf;
	//$REMITAPARAM = $dbo->DataArray($param,"&","=","");
        //	extract($REMITAPARAM);
        
    //return ["Status"=>0,"DateTime"=>$params['RegDate'],"Ref"=>$params['RRR'],"Amt"=>$params['Amt'],"Message"=>json_encode($params)];
	if(isset($params['TERMINALIDBANK'])){
		$TERMINALID = EGetData($params['TERMINALIDBANK'],$params['PayID']);
			   //$concatString = $params['Ref'] . $params['APIKEY'] . $params['MERCHANTID']; //RRR+api_key+merchantId
				//$hash = hash('sha512', $concatString);
                
               // return ["Status"=>0,"DateTime"=>$params['RegDate'],"Ref"=>$params['Ref'],"Amt"=>$params['Amt'],"Message"=>$params['Ref']];
               $url 	= EGetData($params['QUERYURL'],$params['PayID']);
               $data = "TERMINAL_ID=".$TERMINALID."&PAYEE_ID=".$params['Ref']."&RESPONSE_URL=";


               //$url = "https://demo.etranzact.com/webconnect/v3/query.jsp";
               //$data = "TRANSACTION_ID=".$params['Ref'];

                /* <form method = ‘POST’ action= ‘http://demo.etranzact.com/WebConnectPlus/query.jsp’ > 
<input type=hidden name = ‘TERMINAL_ID’ value=’0000000001’> 
<input type=hidden name = ‘TRANSACTION_ID’ value=’1234325435435345345435454’> 
<input type=hidden name= ‘RESPONSE_URL’ value=’http://www.mywebsite.com/processQuery.jsp’> 
</form> */
				//return [$params['Ref']];
		   //$TERMINALID = '0440000045';
		   //$url = 'https://www.etranzact.net/WebConnectPlus/queryReference.jsp';
			//  Initiate curl
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_POST, 3);
            curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
			// Disable SSL verification
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
			// Will return the response, if false it print the response
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			// Set the url
			curl_setopt($ch, CURLOPT_URL,$url);
			// Execute
			$rst = curl_exec($ch);
//return ["Status"=>0,"DateTime"=>$params['RegDate'],"Ref"=>$params['Ref'],"Amt"=>$params['Amt'],"Message"=>$rst];			
$rst = rtrim($rst,"</html>");
$rst = trim($rst);
curl_close($ch);

$etr = urldecode($rst);

$data = UrlToArray($etr); //$etr = implode("~",$data);
$data['BANK'] = 1;
if((isset($data['SUCCESS']) && $data['SUCCESS'] == -1) || count($data) == 0){
    //check if it is a bank payment or card payment
    if(isset($data['BANK']) && $data['BANK'] == 1 ){
        return ["Status"=>0,"DateTime"=>$params['RegDate'],"Ref"=>$params['Ref'],"Amt"=>$params['Amt'],"Message"=>"Payment Not Made"];
    }else if(count($data) == 0){
        return ["Status"=>0,"DateTime"=>$params['RegDate'],"Ref"=>$params['Ref'],"Amt"=>$params['Amt'],"Message"=>"Invalid Parameter or Bad Network"];
     //  return "6#{$msg}"; //Invalid Parameter or Bad Network 
    }else{
        return ["Status"=>0,"DateTime"=>$params['RegDate'],"Ref"=>$params['Ref'],"Amt"=>$params['Amt'],"Message"=>"Transaction Failed"];
       
    }
    
}else{
  if(isset($data['TRANS_AMOUNT']) || isset($data['AMOUNT'])){
      $amtPaid = isset($data['TRANS_AMOUNT'])?(float)$data['TRANS_AMOUNT']:(float)$data['AMOUNT'];
      $amtOrder = (float)$params['Amt'];
      if($amtPaid < $amtOrder){
        return ["Status"=>0,"DateTime"=>$params['RegDate'],"Ref"=>$params['Ref'],"Amt"=>$params['Amt'],"Message"=>"Invalid Amount Paid"];
      }else{
        return ["Status"=>1,"DateTime"=>$data["TRANS_DATE"],"Ref"=>$params['Ref'],"Amt"=>$params['Amt'],"Message"=>"Paid","Bank"=>$data["BANK_NAME"],"Branch"=>$data["BRANCH_NAME"]];
      }
    }else{
        return ["Status"=>0,"DateTime"=>$params['RegDate'],"Ref"=>$params['Ref'],"Amt"=>$params['Amt'],"Message"=>$params['Ref']." - ($etr) "]; 
    }

}
//return $data;
            //return ["Status"=>0,"DateTime"=>$params['RegDate'],"Ref"=>$params['Ref'],"Amt"=>$params['Amt'],"Message"=>$response. " - "."TERMINAL_ID=".$TERMINALID."&TRANSACTION_ID=".$params['Ref']."&RESPONSE_URL="];
			/* {"amount":29685,"RRR":"140279641557","orderId":"666887812140219105251","message":"Approved","paymentDate":"2019-02-14 01:02:05 PM","transactiontime":"2019-02-14 12:00:00 AM","status":"01"}

{"amount":81685,"RRR":"300280279075","orderId":"32385958615504855061142","message":"Transaction Pending","transactiontime":"2019-02-18 12:00:00 AM","status":"021"} */

			 
			  //return $response;
			}
		
}


//Card Payment Finish script
function EFinishPay($param){
//Calcualte Finalchecksum from response returned.
$secret_key = "DEMO_KEY";
$amount = $param['AMOUNT'];
$desc = $param['DESCRIPTION'];
$email = $param['EMAIL'];
$status_code = $param['SUCCESS'];
$terminal_id = $param['TERMINAL_ID'];
$transid = $param['TRANSACTION_ID']; //Note, status_code and response_code are the same.
$final_checksum = $param['FINAL_CHECKSUM'];
$response_code = $param['RESPONSE_CODE'];
$msg = $param['STATUS_REASON'];
$msg2 = $param['MESSAGE']; //Note, STATUS_REASON and MESSAGE are the same.
//$msg3 = $param['msg'];
//$rmsg = isset($param['STATUS_REASON'])?$param['STATUS_REASON']:isset($param['MESSAGE'])?$param['MESSAGE']:isset($param['msg'])?$param['msg']:"Unknown Error";
$etzRef = $param['TRANS_NUM'];
$myFinalcheck = md5($param['SUCCESS'].$param['AMOUNT'].$param['TERMINAL_ID'].$param['TRANSACTION_ID'].$secret_key);
//$err = "";
if(isset($param['FINAL_CHECKSUM']) != $myFinalcheck){
        $msg .= ", WRONG CHECKSUM";
        $status_code = -2;
}
if($status_code == '0'){
    return [1,$param['TransNum'],$msg,$status_code,["Amt"=>$amount,"Bank"=>$param['CARD_TYPE'],"Branch"=>$param['CARD_NO'],"DateTime"=>date("Y-m-d")]];
}else{
    //@@@try requery incase it is network issue

    return [0,$param['TransNum'],$msg,$status_code,["Amt"=>$amount,"Bank"=>"UNKNOWN","Branch"=>"UNKNOWN","DateTime"=>date("Y-m-d")]];
}
}

?>