<?php
session_start();
if (!isset($_GET['SubDir'])) {
	exit("Application Owner Directory not Found");
}

//keep SubDir in session
$_SESSION['SubDir'] = $_GET["SubDir"];
$BankPre = isset($_GET["BankPre"]) ? $_GET["BankPre"] : 'a';

//$Config = json_decode(urldecode($_POST['Config']),true);
$configdir = "../../../../" . urldecode($_GET["SubDir"]);
require_once("../config.php");
//require_once("../../TaquaLB/Elements/Elements.php");
require_once("../getinfo.php");
$school = GetSchool();
?>

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<!-- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> -->
	<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
	<link href="<?php echo $configdir . $dbo->Config['Require']; ?>FA4/css/font-awesome.min.css" media="all" type="text/css" rel="stylesheet" />
	<style media="all" type="text/css">
		body {
			margin: 0px;
			font-family: "Segoe UI Light", "Segoe UI Semibold", "Segoe UI Semilight", "Segoe UI", "Segoe UI Black";
			font-weight: lighter;
			padding: 0px;
			background-color: #EBEBEB;
			/* background-image: url(../../images/App/Images/eduportareal.png); 
	  background-position:center bottom;
	  background-repeat:no-repeat;
	  background-attachment:fixed;*/
		}

		.txt {
			width: 100%;
			text-align: center;
			margin-top: 150px;
			font-size: 1.8em;
			color: #26511C
		}

		.txt span {
			display: block;
		}
	</style>
	<title>Card Payment</title>
</head>

<body>
	<div class="txt">Connecting to Payment Platform.<br /><strong>Please Wait ....</strong><span><i class="fa fa-cog fa-spin"></i></span></div>
	<?php
	if (isset($_GET['Ref'])) {
		$Ref = $_GET['Ref'];

		//get the order, item and thirdparty details
		$PayDet = $dbo->RunQuery("SELECT o.*, i.*, t.*,o.ID as OrderID, i.ID as PayID,t.ID as GatewayID FROM order_tb o, item_tb i, thirdparty_tb t WHERE (o.ItemNo='" . $dbo->SqlSafe($Ref) . "' OR o.TransNum='" . $dbo->SqlSafe($Ref) . "') AND o.ItemID = i.ID AND i.PayGatewayID = t.ID");
		if (is_array($PayDet) && $PayDet[1] > 0) {
			$PayDet = $PayDet[0]->fetch_assoc();
			//check the channel and update as required
			
			$RegNo = $PayDet['RegNo'];
			// $_SESSION['Ref'] = $Ref;
			$_SESSION['RegNo'] = $RegNo;
			$_SESSION['GatewayID'] = $GatewayID;
			// $rrr = $_GET['RRR'];
			//$GATEWAYRRRPAYMENTURL = $_GET['URL'];
			//$MERCHANTID = $_GET['MID'];
			/* 	$responseurl = _CURURL_;
$responseurl = str_replace("/post.php","/finish.php",$responseurl); */
			// $responseurl = $dbo->Config['Core2'] . "general/Payment/finish.php?SubDir=" . $_GET['SubDir'];
			$responseurl = $dbo->Config['SubDir2'] . "Payment/finishproxy.php?SubDir=" . $_GET['SubDir'];
			$logourl = $dbo->Config['SubDir2'] . "Files/" . $school['logo'];

			$studDet = GetBasicInfo($RegNo, "", $BankPre, 1, MYSQLI_ASSOC);
			if (!is_array($studDet)) { //try pstudentinfo only
				$studDet = $dbo->SelectFirstRow("{$BankPre}studentinfo_tb", "*, CONCAT(SurName,' ',FirstName,' ',OtherNames) as Name", "RegNo='" . $dbo->SqlSafe($RegNo) . "' OR JambNo='" . $dbo->SqlSafe($RegNo) . "'", MYSQLI_ASSOC);
			}
			//if(!is_array($studDet))exit('{"Error":"Reading Payee Details Failed"}');
			if (is_array($studDet)) {

				$gatewayparam = $PayDet['USE'] == "LIVE" ? $PayDet['PARAM'] : $PayDet['DEMO_PARAM'];
				//remove gateway param
				unset($PayDet['PARAM']);
				unset($PayDet['DEMO_PARAM']);

				if ((int)$PayDet['Currency'] > 0) {
					$cur = $dbo->SelectFirstRow("currency_tb", "", "ID=" . $PayDet['Currency']);
					$PayDet['Currency'] = is_array($cur) ? $cur['Name'] : $PayDet['Currency'];
				}
				$schdet = GetSchool("OrderValidity,email,UniqueTransID");

				//if student Email not set use the school email
				if (!isset($studDet['Email']) || trim($studDet['Email']) == "") $studDet['Email'] = $schdet['email'];
				$params = array_merge($PayDet, $dbo->DataArray($gatewayparam), $studDet, ["ItemRef" => $PayDet['PaymentID'], "FinishUrl" => $responseurl, "Ref" => $PayDet['TransNum'], "LOGO" => $logourl]);
				//access the gateway script and run the Post Script
				//Note the post script should for an html form with required parameter ino an hidden form which will posted to the gateway url
				//include the payment gateway script
				//require_once "../../../".$PayDet['Script'];/*  */
				$scrarr = explode("/", $PayDet['Script']);
				require_once "Gateways/" . $scrarr[count($scrarr) - 1];
				//$dbo->Redirect("finish.php?err=".$PayDet['PostPayMethod']);
				if (function_exists($PayDet['PostPayMethod'])) {

					$rstobj = call_user_func($PayDet['PostPayMethod'], $params);
					//$dbo->Redirect("finish.php?err=sssss");
					//$rstobj = json_decode($rst,true);
					if (isset($rstobj['Error'])) {
						$dbo->Redirect("finish.php?err=" . $rstobj['Error']);
					}

					$updata = ["Channel" => "ONLINE", "PayGatewayID" => $PayDet['PayGatewayID']];
					if(isset($rstobj['CheckSum'])){
						$updata['CheckSum'] = $rstobj['CheckSum'];
					}
					$upd = $dbo->Update("order_tb", $updata , "ID=" . $PayDet['OrderID']);
					if (isset($rstobj['Markup'])) {
						echo $rstobj['Markup'];
						echo json_encode($rstobj['Data']);
						// building array of variables
						/* $content = http_build_query($rstobj['Data']);
// creating the context change POST to GET if that is relevant 
$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'content' => $content, )));

$result = file_get_contents($rstobj['Url'], null, $context);
//dumping the reuslt
exit($result); */
						//echo 'gggggg';
					} else {
						$dbo->Redirect("finish.php?err=Internal Error: Invalid Responce from Gateway Script");
					}
				} else {
					$dbo->Redirect("finish.php?err=Internal Error: Gateway Post Script Not Found");
				}
			} else {
				$dbo->Redirect("finish.php?err=Reading Student Details Failed $RegNo");
			}
		} else {

			//echo '<br />Reading Payment Details Failed';
			$dbo->Redirect("finish.php?err=Reading Payment Details Failed");
		}
	} else {
		// echo 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/sample-receipt-page.php";

		$dbo->Redirect("finish.php?err=Invalid Payment Parameter");
	}
	?>
</body>

</html>