<?php

//Init Method - Function to Initialize Payment (Generate the payment referece (RRR))
function Init($params){
	global $dbo;
	//_CURURL_
//return ["Error"=>$params['FinishUrl']];
if(isset($params['MERCHANTID'])){
	//return json_encode($REMITAPARAM);
	$MERCHANTID = $params['MERCHANTID'];
$APIKEY = $params['APIKEY'];
$GATEWAYURL = $params['GATEWAYURL'];
$GATEWAYRRRPAYMENTURL = $params['GATEWAYRRRPAYMENTURL'];
$CHECKSTATUSURL = $params['CHECKSTATUSURL'];
//LE => Using Service Type to detratmine bank/payment details #4
	$SERVICETYPEID = $params['USE'] == 'LIVE'?$params['ItemRef']:'4430731'; //demo service type is static
	$ITEM = $params['ITEM_'.$SERVICETYPEID];
	$BN = $params['BN_'.$SERVICETYPEID];
	$BA = $params['BA_'.$SERVICETYPEID];
	$BC = $params['BC_'.$SERVICETYPEID];
	$DFF = $params['DFF_'.$SERVICETYPEID];
	$SPLIT = $params['SPLIT_'.$SERVICETYPEID];
	
	$timesammp=DATE("dmyHis");		
	$orderID = $params["OrderID"];
	$payerName = $params["Name"];
	$payerEmail = $params["Email"];
	$payerPhone = $params["Phone"];
	$responseurl = $params['FinishUrl'];
	
	$itemtimestamp = $timesammp;
	//return $BC.";".$DFF;
	$ITEMAR = explode("~",$ITEM);
	$BNAR = explode("~",$BN);
	$BAAR = explode("~",$BA);
	$BCAR = explode("~",$BC);
	$DFFAR = explode("~",$DFF);

	$BAMTAR = explode("~",$SPLIT);
	$AMTSARR = [];
	foreach($BAMTAR as $BAMTCUR){
		$CURAMT = 0;
		$subtr = explode("-",$BAMTCUR);
		foreach($subtr as $subamt){
			$subamt = trim($subamt);
			//check if percentage
			$perc = substr($subamt,strlen($subamt) - 1,1);
			if($perc == "%"){ //if percentage
				$subamt = (float)substr($subamt,0,strlen($subamt) - 1);
				$subamt = $subamt > 0?(float)$params["Amt"] * (100/$subamt):0;	
			}
			if($CURAMT > 0){
				$CURAMT = $CURAMT - $subamt;
			}else{
				$CURAMT = (int)$subamt;
			}
		}
		$AMTSARR[] = $CURAMT;
	}
	$totalAmount = $params['USE'] == 'LIVE'?array_sum($AMTSARR):1000;
	$hash_string = $MERCHANTID . $SERVICETYPEID . $orderID . $totalAmount . $responseurl . $APIKEY;
	$hash = hash('sha512', $hash_string);
	//$BAMTAR = $payeeDet["AmtSplit"];
   // return implode(";",$BAMTAR);
	$content = '{"merchantId":"'. $MERCHANTID
	.'"'.',"serviceTypeId":"'.$SERVICETYPEID
	.'"'.",".'"totalAmount":"'.$totalAmount
	.'","hash":"'. $hash
	.'"'.',"orderId":"'.$orderID
	.'"'.",".'"responseurl":"'.$responseurl
	.'","payerName":"'. $payerName
	.'"'.',"payerEmail":"'.$payerEmail
	.'"'.",".'"payerPhone":"'.$payerPhone
	.'","lineItems":[';
	for($s=0; $s < count($ITEMAR); $s++){
		$ITEMCUR = $ITEMAR[$s].$itemtimestamp;
		$BNCUR = $BNAR[$s];
		$BACUR = $BAAR[$s];
		$BCCUR = $BCAR[$s];
		$DFFCUR = $DFFAR[$s];
		$CURAMT = $AMTSARR[$s];
		//check if its a subtract operation
		
$content .='{"lineItemsId":"'.$ITEMCUR.'","beneficiaryName":"'.$BNCUR.'","beneficiaryAccount":"'.$BACUR.'","bankCode":"'.$BCCUR.'","beneficiaryAmount":"'.$CURAMT.'","deductFeeFrom":"'.$DFFCUR.'"},';
	}
	$content = rtrim($content,",").']}';
	//return ["Error"=>$content];
   //return $content;
	/*$itemid1="itemid1".$itemtimestamp;
	$itemid2="34444".$itemtimestamp;
	$itemid3="8694".$itemtimestamp;
	$beneficiaryName="Oshadami Mke";
$beneficiaryName2="Mujib Ishola";
	$beneficiaryName3="Ogunseye Olarewanju";
	$beneficiaryAccount="6020067886";
	$beneficiaryAccount2="0360883515";
	$beneficiaryAccount3="4017904612";
	
	$bankCode="011";
	$bankCode2="050";
	$bankCode3="070";
		$beneficiaryAmount ="900";
	$beneficiaryAmount2 ="50";
	$beneficiaryAmount3 ="50";
	$deductFeeFrom=1;
	$deductFeeFrom2=0;
	$deductFeeFrom3=0;
	
	//The JSON data.
	$content = '{"merchantId":"'. $MERCHANTID
	.'"'.',"serviceTypeId":"'.$SERVICETYPEID
	.'"'.",".'"totalAmount":"'.$totalAmount
	.'","hash":"'. $hash
	.'"'.',"orderId":"'.$orderID
	.'"'.",".'"responseurl":"'.$responseurl
	.'","payerName":"'. $payerName
	.'"'.',"payerEmail":"'.$payerEmail
	.'"'.",".'"payerPhone":"'.$payerPhone
	.'","lineItems":[
	{"lineItemsId":"'.$itemid1.'","beneficiaryName":"'.$beneficiaryName.'","beneficiaryAccount":"'.$beneficiaryAccount.'","bankCode":"'.$bankCode.'","beneficiaryAmount":"'.$beneficiaryAmount.'","deductFeeFrom":"'.$deductFeeFrom.'"},
	{"lineItemsId":"'.$itemid2.'","beneficiaryName":"'.$beneficiaryName2.'","beneficiaryAccount":"'.$beneficiaryAccount2.'","bankCode":"'.$bankCode2.'","beneficiaryAmount":"'.$beneficiaryAmount2.'","deductFeeFrom":"'.$deductFeeFrom2.'"},
	{"lineItemsId":"'.$itemid3.'","beneficiaryName":"'.$beneficiaryName3.'","beneficiaryAccount":"'.$beneficiaryAccount3.'","bankCode":"'.$bankCode3.'","beneficiaryAmount":"'.$beneficiaryAmount3.'","deductFeeFrom":"'.$deductFeeFrom3.'"}
	]}';*/
	//return $content;
	/*,	{"lineItemsId":"'.$itemid2.'","beneficiaryName":"'.$beneficiaryName2.'","beneficiaryAccount":"'.$beneficiaryAccount2.'","bankCode":"'.$bankCode2.'","beneficiaryAmount":"'.$beneficiaryAmount2.'","deductFeeFrom":"'.$deductFeeFrom2.'"},
	{"lineItemsId":"'.$itemid3.'","beneficiaryName":"'.$beneficiaryName3.'","beneficiaryAccount":"'.$beneficiaryAccount3.'","bankCode":"'.$bankCode3.'","beneficiaryAmount":"'.$beneficiaryAmount3.'","deductFeeFrom":"'.$deductFeeFrom3.'"}*/
	//return $GATEWAYURL;
	$curl = curl_init($GATEWAYURL);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_HTTPHEADER,
	array("Content-type: application/json"));
	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
	$json_response = curl_exec($curl);
	$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
	$err = "";
	if(curl_errno($curl)){   
		$err = 'Internal Error: ' . curl_error($curl);
	}
	curl_close($curl);
    if(trim($err) != "")return ["Error"=>$err];
	//return ["Error"=>$json_response];
	$jsonData = substr($json_response, 6, -1);
	$response = json_decode($jsonData, true);
	$statuscode = $response['statuscode'];
	$statusMsg = $response['status'];
	//$rrr = "";
	if($statuscode=='025'){
	  $rrr = trim($response['RRR']);
      return ["Ref"=>$rrr];
	  //return array("RRR"=>$rrr,"Code"=>$statuscode,"Message"=>$statusMsg);
	}else{
		return ["Error"=>"$statuscode: $statusMsg"];
	  //return array("RRR"=>"","Code"=>$statuscode,"Message"=>$statusMsg);	
	}
	
  }
	return ["Error"=>"Wrong Payment Parameter Set"];
}


//Post Method - Function to Post Payment Details to Remita platform
function PayNow($params){
	//return ["Error"=>$params['FinishUrl']];
	$new_hash_string = $params['MERCHANTID'] . $params['Ref'] . $params['APIKEY'];	
		$new_hash = hash('sha512', $new_hash_string);
		$form = '<form action="'.$params['GATEWAYRRRPAYMENTURL'].'" method="POST" id="payfrm" name="payform">
<input id="merchantId" name="merchantId" value="'.$params['MERCHANTID'].'" type="hidden"/>
<input id="rrr" name="rrr" value="'.$params['Ref'].'" type="hidden"/>
<input id="responseurl" name="responseurl" value="'.$params['FinishUrl'].'" type="hidden"/>
<input id="hash" name="hash" value="'.$new_hash.'" type="hidden"/>
<input id="paymenttype" name="paymenttype" value="Interswitch" type="hidden"/>
<input type="submit" class="" style=" visibility:hidden; opacity:0"  name="submits" id="submits" value="Submit" />
</form>';
$form .= '<script type="text/javascript" >
document.getElementById("payfrm").submit();
</script>';
	return ["Markup"=>$form];
}




//Function to check payment status
function CheckPayNow($params){
	//$orderId,$rrr=false
	global $dbo;
	//global $phpf;
	//$REMITAPARAM = $dbo->DataArray($param,"&","=","");
		//	extract($REMITAPARAM);
			
	if(isset($params['MERCHANTID'])){
		
			   $concatString = $params['Ref'] . $params['APIKEY'] . $params['MERCHANTID']; //RRR+api_key+merchantId
				$hash = hash('sha512', $concatString);
				$url 	= $params['CHECKSTATUSURL'] . '/' . $params['MERCHANTID']  . '/' . $params['Ref'] . '/' . $hash . '/' . 'status.reg';
				//return [$params['Ref']];
		   
			//  Initiate curl
			$ch = curl_init();
			// Disable SSL verification
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			// 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
			$result=curl_exec($ch);
			// Closing
			curl_close($ch);
			$response = json_decode($result, true);
			/* {"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"} */
if(isset($response['status'] )){
	 if($response['status'] == "01" || $response['status'] == "00"){
				  return ["Status"=>1,"DateTime"=>$response['paymentDate'],"Ref"=>$response['RRR'],"Amt"=>$response['amount'],"Message"=>"Paid"];
			  }else{
				$Mes = $response['status'] == "021"?"Pending: Payment Not Made":$response['message'];
				return ["Status"=>0,"DateTime"=>$params['RegDate'],"Ref"=>$response['RRR'],"Amt"=>$response['amount'],"Message"=>$Mes];
			  }
}else{
	return ["Status"=>0,"DateTime"=>$params['RegDate'],"Ref"=>$params['Ref'],"Amt"=>$param['Amt'],"Message"=>"Invalid Gateway Responce"];
}
			 
			  //return $response;
			}
			return ["Status"=>0,"DateTime"=>$params['RegDate'],"Ref"=>$params['Ref'],"Amt"=>$param['Amt'],"Message"=>"Invalid Gateway Setup"];
		
}
?>