<?php

if(session_status() == PHP_SESSION_NONE){
    //session has not started
    session_start();
}

require_once("phplb.php");

date_default_timezone_set("Africa/Lagos");
$phpf = new RphpFunctions;

 /*$queryd = "SELECT SubDomain FROM school_tb Limit 1";
		$subdarr = $dbo->RunQuery($querys);*/
$subdomainName = "";$rootportal=_ROOT_;
//echo _ROOT_."<br />";
foreach(array("rportals.","cportals.","eportals.","portals.","rportal.","cportal.","eportal.","portal.","epconfig.","setup.") as $subd){
	if(strpos(_ROOT_,$subd) !== false){//if the subdomain name is found
		//remove it from the root to get the real site sub
		$rootportal = str_replace($subd,"",_ROOT_);
		$subdomainName = rtrim($subd,".");
		break;
	}else if(strpos(_CURURL_,str_replace(".","/",$subd)) !== false){
		$rtp = strpos(_CURURL_,str_replace(".","/",$subd));
		$rootportal = substr(_CURURL_,0,$rtp);
		$subdomainName = rtrim($subd,".");
		break;
	}
}
//var_dump($_SERVER);
//exit();
define("_SUBDOMAIN_",$subdomainName);

//new way of getting the root directory
//we are sure that this file config.php will always be inside the epconfig dir
//and the epconfig dir will always be in the root directory of the system
$filepth = __FILE__;
$fileptharr = explode("epconfig",$filepth);
define("_PROOT_",$rootportal);
define("_PROOT_SYS_",$fileptharr[0]);//$rootportal

define("_CONFIGDIR_",_PROOT_."epconfig/");//url
define("_CONFIGDIR_SYS_",_PROOT_SYS_."epconfig/");//DOCUMENT_ROOT
//print_r($fileptharr[0]);
//exit;
define("_SUBROOT_",_PROOT_._SUBDOMAIN_."/");
define("_SUBROOT_SYS_",_PROOT_SYS_._SUBDOMAIN_."/");
/* $conf = $phpf->_(file_get_contents(_CONFIGDIR_."conf.txt"));
	if(trim($conf) == ""){ */
		//config file not seen via url addresing, try document root addressing

		 if(!isset($configdir)){
			exit("Eduporta User not Configured");
		 }

		 if(isset($_SESSION['MainCinfig']) && trim($_SESSION['MainCinfig']) != ""){
			$configstr = $_SESSION['MainCinfig'];
		 }else{
			 //confirm the config file
			if(!file_exists($configdir."config.json")){
				
				echo "***************** Configuration File Not Exist  ***************** ".$configdir."config.json";
				exit;
			}

			$configstr = file_get_contents($configdir."config.json");
			if( $configstr === FALSE || trim($configstr) == ""){
				exit("***************** INVALID CONFIGURATION  ***************** ");
			}
		 }
		 

		 $configstr = substr($configstr,strpos($configstr,"{")) ;
			//get the settings as an array
			$config = json_decode($configstr,true);


		$conf = $phpf->_(file_get_contents($configdir."conf.txt"));
		if(trim($conf) == ""){
		echo "***************** APP NOT SETUP  ***************** ";
		exit;
		}
	
	//}
if(isset($_POST['rtconf'])){echo $conf; exit;}
$datastrconfig = str_replace(";","&",$conf);

$datasrr = $phpf->DataArray($datastrconfig);

$dbo = new DbFunctions("127.0.0.1",$datasrr["user"],$datasrr["pw"],$datasrr["db"]);
//echo get_include_path();
/*echo "Normal Root: "._ROOT_."<br />";
echo"Real Root: ". _PROOT_."<br />";
echo "Subdomain: "._SUBDOMAIN_."<br />";*/
//echo dirname($_SERVER['DOCUMENT_ROOT']);
//$dbo = new DbFunctions("localhost","root","","aksuedu_db");
$con = DbFunctions::$con; //get the connection opbject created
$cone = $dbo->Connected?"Connected":"Not Connected";

if($dbo->ConnectStatus != ""){
	echo "***************** Error on Page: #CON1 *****************";
	exit;
}else{ 
	
	$ServerRoot = isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:$_SERVER['SERVER_NAME'];
//$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';
$protocol = !empty($_SERVER['HTTPS'])?'https://' : 'http://';
//get the current setup details
/* $setupdet = $dbo->SelectFirstRow("setup_tb","","Inuse=1 LIMIT 1");
$Versionstr = "";
if(is_array($setupdet)){
    $Versionstr = $setupdet['Version']."/";
} */

$Versionstr = "";
if(trim($config['Version']) != ""){
  $Versionstr = $config['Version']."/".$config['Core'];
}

//manage back directory(../) withen url
$config["Core2"] = $protocol.$ServerRoot."/".$Versionstr;
$cofigcorarr =  explode("/",$config["Core2"]);
$newarr = [];
foreach($cofigcorarr as $dir){
	
  if($dir == ".."){
	array_pop($newarr);
	continue;
  }
  
  array_push($newarr,$dir);
  //$config["ttt"] = count($newarr);
}
$config["Core2"] = implode("/",$newarr);

$config['SubDir2'] = $protocol.$ServerRoot."/".$config['SubDir'];
	$dbo->Config = $config;
/*$querys = "SELECT * FROM remita_tb Limit 1";
		$rstremita = $dbo->RunQuery($querys);
		if(is_array($rstremita)){
			$rstarr = mysql_fetch_array($rstremita[0]);
			//return $rstarr;
			$demo = $rstarr["USE"] == "LIVE"?"":"_DEMO";
			$MERCHANTID = $rstarr["MERCHANTID".$demo];
			$SERVICETYPEID = $rstarr["SERVICETYPEID".$demo];
			$APIKEY = $rstarr["APIKEY".$demo];
			$GATEWAYURL = $rstarr["GATEWAYURL".$demo];
			$GATEWAYRRRPAYMENTURL = $rstarr["GATEWAYRRRPAYMENTURL".$demo];
			$CHECKSTATUSURL = $rstarr["CHECKSTATUSURL".$demo];*/
			$query = "select * from thirdparty_tb where ID = (select PayThirdPartyID from school_tb limit 1)";
		$rstremita = $dbo->RunQuery($query);
		
		if(is_array($rstremita)){
			$rstarr = $rstremita[0]->fetch_array();
			$demo = $rstarr["USE"] == "LIVE"?"":"DEMO_";
			$param = $rstarr[$demo."PARAM"];
			//echo $param;
			$REMITAPARAM = $phpf->DataArray($param,"&","=","");
			extract($REMITAPARAM);
			if(isset($MERCHANTID)){ //remita
			
			define("MERCHANTID",$MERCHANTID);
			define("SERVICETYPEID",$SERVICETYPEID);
			define("APIKEY",$APIKEY);
			define("GATEWAYURL",$GATEWAYURL);
			define("GATEWAYRRRPAYMENTURL",$GATEWAYRRRPAYMENTURL);
			define("CHECKSTATUSURL",$CHECKSTATUSURL);
			}else{ //etransact
//POSTURL=http://demo.etranzact.com/WebConnectPlus/queryReference.jsp&RESPONSEURL=&TERMINALID=5001102671&REQUESTURL=&OTHERS=&SECRETKEY=DEMO_KEY
			 $POSTURL = trim($POSTURL) != ""?$dbo->DataArray($POSTURL,"`","~"):array("-1"=>"");
			 define("POSTURL",$POSTURL);
			 $RESPONSEURL = trim($RESPONSEURL) != ""?$dbo->DataArray($RESPONSEURL,"`","~"):array("-1"=>"");
			define("RESPONSEURL",$RESPONSEURL);
			 $TERMINALID = trim($TERMINALID) != ""?$dbo->DataArray($TERMINALID,"`","~"):array("-1"=>"");
			define("TERMINALID",$TERMINALID);
			 $REQUESTURL = trim($REQUESTURL) != ""?$dbo->DataArray($REQUESTURL,"`","~"):array("-1"=>"");
			define("REQUESTURL",$REQUESTURL);
			 $OTHERS = trim($OTHERS) != ""?$dbo->DataArray($OTHERS,"`","~"):array("-1"=>"");
			define("OTHERS",$OTHERS);
			 $SECRETKEY = trim($SECRETKEY) != ""?$dbo->DataArray($SECRETKEY,"`","~"):array("-1"=>"");
			define("SECRETKEY",$SECRETKEY);
			$SERVICEURL = trim($SERVICEURL) != ""?$dbo->DataArray($SERVICEURL,"`","~"):array("-1"=>"");
			define("SERVICEURL",$SERVICEURL);
			}
			
		}
		define("DEFAULT_PASSPORT","Resource/Images/userbig.jpg");
}

//Aim object format
$_ = $dbo;
$GLOBALS['dbo'] = $dbo;
$GLOBALS['_'] = $dbo;



//check if version change exist
/* $version = $dbo->SelectFirstRow("setup_tb","","Inuse=1");
if(is_array($version)){
  $versionstr = trim($version['Version']) != ""?str_replace(".","_",$version['Version']):"";
  $sroot = $_SERVER['DOCUMENT_ROOT'];
   //check if current script is the current version
    if(trim($versionstr) != "" && count(explode("/".$versionstr."/",$_SERVER['PHP_SELF'])) < 2 && is_dir($sroot."/".$versionstr)){ //meaning not in the current version
      exit('<h1 style="text-align:center">Invalid Version! '.$version['Version'].' <a href="javascript:location.reload(true)">Load Current Version</a></h1>');
	}
} */
/*
require_once("../../../epconfig/TaquaLB/Elements/Elements.php");
require("../../../epconfig/GenScript/PHP/getinfo.php");
include("../../../epconfig/TaquaLB/Ajax/CGI/PHP/PDF/mpdf60/mpdf.php");
require("../../../epconfig/TaquaLB/Elements/Script/pdf.php");
*/
$pagesingludes = array(
  "pdfprint" =>array("general/TaquaLB/Elements/Elements.php","general/getinfo.php","genera/TaquaLB/Ajax/CGI/PHP/PDF/mpdf60/mpdf.php","epconfig/TaquaLB/Elements/Script/pdf.php"),
  "pdfprintredirect"=>array("epconfig/GenScript/PHP/getinfo.php","epconfig/TaquaLB/Elements/Elements.php"),
  "basic"=>array("general/getinfo.php","general/TaquaLB/Elements/Elements.php"),
  "objectbasic"=>array("portal/AppTemp/objects.php",
  "epconfig/GenScript/PHP/getinfo.php","epconfig/TaquaLB/Elements/Elements.php")
);
//function to load all required script
function LoadFile($page,$basedir = ""){
  global $pagesingludes;
	if(isset($pagesingludes[$page])){
      $pagesarr = $pagesingludes[$page];
	  //print_r($pagesarr);
	  if(is_array($pagesarr)){
		  foreach($pagesarr as $scrip){
			  //echo $basedir.$scrip."<br />";
			  require_once($basedir.$scrip);
		  }
	  }else{
		 require_once($basedir.$pagesarr); 
	  }
	}
   
}

// function to check privilege - for cportal
function AllowUser($priv){
	if(isset($_REQUEST['EP_FORCE_PRIV']) && $_REQUEST['EP_FORCE_PRIV'] == "taquatech")return 1;
	$UID = isset($_SESSION['UID'])?$_SESSION['UID']:"";
 if(!isset($UID) || trim($UID) == "" || !isset($priv) || trim($priv) == ""){
	exit("^##AD_eduporta##^");
	 //return false;
 }
 global $dbo;
 $check = $dbo->Select("user_tb","","UserID = $UID AND (Privs LIKE '{$priv}:%' OR Privs LIKE '%:{$priv}:%' OR Privs LIKE '%:{$priv}')");
 if($check[1] < 1){
   //return false;
   exit("^##AD_eduporta##^");
 }
 return $check;
 //$privstr = implode(":",$priv);
}

if(isset($EpModuleName)){
	AllowUser($EpModuleName);
}

$EPTPID = "eduporta@user";

function CallScript($url,$fields = []){
   global $dbo;

	$fields_string = "";
	if(is_array($fields)){
	//url-ify the data for the POST
	foreach($fields as $key=>$value) { $fields_string .= $key.'='.urlencode($value).'&'; }
	$fields_string=rtrim($fields_string, '&');
	}

	/* curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); */
	
	//return json_encode($fields);
	//open connection
	$curl = curl_init($url);
	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, $dbo->DataString($fields));
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
	$json_response = curl_exec($curl);
	$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
	$err = "";
	 if(curl_errno($curl)){   
		return ["Error"=>curl_error($curl)];
	} 
	curl_close($curl);
	//if(trim($err) != "")return ["Error"=>curl_error($curl)];
	return $json_response;
	}

	//Function to resolve filename url for new structured version
	function ResolveFilePath($url){
		//check if contain epconfig
		$urlbr = explode("epconfig/",$url);
		if(count($urlbr) == 2){ //if 
          $url = "Files/".$urlbr[1];
		}
		return $url;
	}

//function to 
//$tt = array("-1"=>"yommy","1"=>"ade","2"=>"ssss");
//print_r($tt["2"]);

?>