<?php
// exit('aaaaa');
//Last Edited - 22-6-17 #4
function IsFreshStud($regNo)
{
	global $dbo;
	$currSes = CurrentSes();
	$currSesID = $currSes['SesID'];
	$startses = StudStartSes($regNo);
	$startses = ($startses === false) ? $currSesID : $startses;
	if ($startses == $currSesID) {
		return true;
	} else {
		return false;
	}
}

//function to form breakdown condition
function FormBrkDwnCond($attr, $oprator, $value, $studrec)
{
}

//function to get faculty based on progID
function Fac($progID)
{
	global $dbo;
	global $phpf;
	$progID = (int)$progID;
	$query = "select fc.* from fac_tb fc, programme_tb pr, dept_tb dt where pr.DeptID = dt.DeptID and dt.FacID = fc.FacID and pr.ProgID = {$progID} limit 1";
	$rw = "";
	$rst = $dbo->RunQuery($query);
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$rw = $rst[0]->fetch_array();
		}
	}
	return $rw;
}

function PaymentBreakDown($PayBrkDn, $lvl, $sem, $studrec = array(), $sempart = 3, $dt = NULL,$ItemID=NULL)
{
	
	global $dbo;
	//get the heigest Semester
	$higestsem = HighestSemester();
	//$higestsem = $dbo->SelectFirstRow("semester_tb","ID,IF(Num=0,ID,Num) as Num","Enable = 1 ORDER BY Num DESC, ID DESC LIMIT 1");
	$fullpolicy = is_array($higestsem) ? (int)$higestsem['Num'] + 1 : 3; //get the full semester policy id
	if (is_null($dt)) {
		$dt = date("Y-m-d");
	}
	
	if (is_string($studrec)) {
		//get student details
		$studDet = GetBasicInfo($studrec, "", "a", 1, MYSQLI_ASSOC);
		//if(!is_array($studDet))exit('{"Error":"Reading Payee Details Failed"}');
		if (!is_array($studDet)) {
			//get details from payee tb
			$studDet = $dbo->SelectFirstRow("payee_tb", "PayeeID as RegNo", "PayeeID=" . $studrec);
			if (!is_array($studDet)) {
				$studrec = [];
			} else {
				if (trim($studDet['OtherDet']) != "") {
					$otherdet = json_decode($studDet['OtherDet'], true);
					$studDet = array_merge($studDet, $otherdet);
				}
				$studrec = $studDet;
			}
		} else {
			$studrec = [];
		}
	}
	
	//return $studrec;
	/* {"Name":"Kejemilobi Abayomi ","ProgID":"23","ProgName":"Botany ","DeptID":"22","DeptName":"Biological Science","FacID":"1","FacName":"Sciences","StartSes":"10","ModeOfEntry":"1","StudyID":"5","RegID":"1","PayName":"AKSCOE SCHOOL FEE"} */
	//check if facID is set and FacGrpID not set, get and set it
	if (isset($studrec['FacID']) && (int)$studrec['FacID'] > 0 && !isset($studrec['FacGrpID'])) {
		
		//get the fac group details by the fac id
		$facgrpdet = $dbo->SelectFirstRow("facgroup_tb fg, fac_tb f", "fg.FacGrpID, fg.FacGrpName", "f.GroupID = fg.FacGrpID AND f.FacID =" . $studrec['FacID']);
		if (is_array($facgrpdet)) { //if found
			$studrec['FacGrpID'] = $facgrpdet['FacGrpID'];
			$studrec['FacGrpName'] = $facgrpdet['FacGrpName'];
		}

		//get the 
	}
	//return ["aaaaa"];
	//check if admision session is zero, use the student start session
	if (!isset($studrec['AdmSes']) || (int)$studrec['AdmSes'] == 0) {
		//use the Start session if exist
		if (isset($studrec['StartSes'])) {
			$studrec['AdmSes'] = $studrec['StartSes'];
		}
	}

	

	//get the school current session
	$CurSes = CurrentSes();
	$CurSes = $CurSes['SesID'];
	//return json_encode($studrec);
	//$dtobj = new DateTime($dt);
	$brkDnArr = explode("***", $PayBrkDn); //break all payment items string as array
	$cnt = 1;
	$trs = "";
	$totamt = 0.0;
	$totamtArr = [];
	$printBrkDwn = "";
	$printBrkDwnArr = [];
	if (count($brkDnArr) > 0) { //if items found
		for ($d = 0; $d < count($brkDnArr); $d++) { //loop through individual items
			$include = false; //determine if the current payment item is to be included
			$brkItem = $brkDnArr[$d]; //get current payment item string
			$brkItemCondArr = explode("?", $brkItem); //break item string into array by the "?" condition character; to know if there exist a condition for the display of item
			$cond = (1 == 1);
			if (count($brkItemCondArr) > 1) { //if condition exist, i.e split exist meaning "?" condition exist
				$fcondstr =  $brkItemCondArr[0]; //get the condition part
				$brkItem = $brkItemCondArr[1]; //get the item real string
				//loop throuhg all the operators to determin the condition operator
				$condopers = ["==", "!=", "<=", ">=", "<", ">"];
				$multconds = explode("&&", $fcondstr);
				foreach ($multconds as $condstr) { //loop through individual multiple condition
					foreach ($condopers as $opr) {
						$condArr = explode($opr, $condstr); //break condition down by spliting the attribute and value
						if (count($condArr) <= 1) continue; //if not the operator used or the attribute not set
						$atr = $condArr[0]; //get atribute
						$val = $condArr[1]; //get value
						//work on special attr val (AdmSes) - Added on 1/12/20
						if ($atr == "AdmSes") {
							//check if the current session is selected
							if (trim($val) == "0") {
								//get the current sesion id
								$val = $CurSes;
							}
						}
						if (!isset($studrec[$atr])) {
							$cond = false;
						} else {
							//general operator
							switch ($opr) {
								case "==":
									$cond = ($studrec[$atr] == $val);
									break;
								case "!=":
									$cond = ($studrec[$atr] != $val);
									break;
								case "<=":
									$cond = is_numeric($val) ? ((int)$studrec[$atr] <= (int)$val) : (1 == 1);
									break;
								case ">=":
									$cond = is_numeric($val) ? ((int)$studrec[$atr] >= (int)$val) : (1 == 1);
									break;
								case "<":
									$cond = is_numeric($val) ? ((int)$studrec[$atr] < (int)$val) : ($studrec[$atr] != $val);
									break;
								case ">":
									$cond = is_numeric($val) ? ((int)$studrec[$atr] > (int)$val) : ($studrec[$atr] != $val);
									break;

								default:
									$cond = ($studrec[$atr] == $val);
							}
						}

						break;
					}
					if ($cond == false) break; //if atleast one false condition exist, makes the whole condition false (AND)
				}
			}
			if ($cond == false) { //if condition not satisfied break
				//i.e skip the item for the student
				continue;
			}
			$itemcontArr = explode("|", $brkItem); //break down the real payment item string
			if (count($itemcontArr) >= 5) { //if total payment item element is 5 i.e a valid payment item string
				//check if enabled
				$status = $itemcontArr[3];
				if ((int)$status < 1) continue; //if the item is disabled, skip it;

				$optional = isset($itemcontArr[5]) ? $itemcontArr[5] : "0";

				//check the date interval
				if (trim($itemcontArr[4]) != "") { //if date set
					$dateintarr = MysqlDateEncode($itemcontArr[4]);
					if ($dateintarr != "") { //if valid date set
						if (is_array($dateintarr)) { //if interval
							$mindate = strtotime($dateintarr[0]);
							$maxdate = strtotime($dateintarr[1]);
							$nowdate = strtotime($dt);
							if ($nowdate < $mindate || $nowdate > $maxdate) continue; //if the payemnt type date is withen the item date
						} else { //if a single date
							if (strtotime($dt) != strtotime($dateintarr)) continue; //for single date item skip the item if date not the item date
						}
					}
				}


				$name = $itemcontArr[0]; //get the payment item name (json) {ID:3,Name:---}
				//proccess the name
				$nameobj = json_decode($name, true);
				$nameid = $nameobj["ID"];
				$name = $nameobj["Name"];

				//Proccess Level - Amount
				$amtList = explode("~", $itemcontArr[1]); //breakdown the amount structure, to get varous amount for deferent levels

				if (count($amtList) > 0) { // if multiple amount found
					// $alllev = "";
					foreach ($amtList as $amtstr) { //loop through all the amounts
						$amtArr = explode("=", $amtstr); //breakdown individual amount
						if (count($amtArr) == 2) { //if a valid individual amount structure
							if ((int)$amtArr[0] == $lvl || $amtArr[0] == "-1") { //if payment item amount level is student level or is for all level(-1)
								//get the amount condition for that level

								if ($sem < $fullpolicy && trim($itemcontArr[2]) != "$fullpolicy") { //if part payment policy for the current payment item exit
									$partpaymentlist = explode("~", $itemcontArr[2]); //breakdown the part payment policy string

									if (count($partpaymentlist) > 0) {
										for ($as = 0; $as < count($partpaymentlist); $as++) { //loop through all the policies
											$partp = explode("=", $partpaymentlist[$as]); //breakdown the current policy to get the semester and percentage amount of the main amount
											$brdwnSem = trim($partp[0]); //the current break down semester
											//comfirm if it has a SemPart
											$SemPrtStr = explode("_", $brdwnSem);
											$SemPrtcond = count($SemPrtStr) > 1 ? true : false; //if more than one sem id found: It is a SemPart Structure
											//return $amtArr[0]."=".$amtArr[1];
											//return $SemPrtcond . " ; " . $brdwnSem;
											//return "Level: ".$amtArr[0]." ; Sem: ".$sem." ; ItemSem: ".$brdwnSem." ; SemPart: ".$sempart." ; ContainSemPart: ".$SemPrtcond;
											if (($SemPrtcond == false && (int)$brdwnSem == $sem) || ($SemPrtcond == true && $brdwnSem == $sem . "_" . $sempart)) { //if the part id = 1 or 2 for half share and 1_1, 1_2, 1_3, 2_1, 2_2, 2_3 for quater sharing exit, get the percentage part and calculate amount

												//calculate amount based on percentage part
												$amtArr[1] = round((float)$partp[1] * (float)$amtArr[1]);
												$include = true;
												break;
											}
										}
									}
								} elseif ($sem == $fullpolicy) { //if full payment selected
									$amtArr[1] = (float)$amtArr[1];
									$include = true;
								} elseif ($sem == 1 && ($sempart == 1 || $sempart == 3) && (int)$itemcontArr[2] == $fullpolicy) {
									//if user selected sem is first and aempart is first part or first full and the item is to be paid full allow it 
									$amtArr[1] = (float)$amtArr[1];
									$include = true;
								}

								if ($amtArr[1] < 1) $include = false; //ignore if the total amount is zero


								//if student sem is 2 or student is completing first sem payment i.e sem is 1 and sempart is 2 and the polycy of item is 3; i.e the item is for full payment or first payment only
								// if($include == false || (($sem == 2 || ($sem == 1 && $sempart == 2)) && (int)$itemcontArr[2] == 3)){
								//do nothing
								//}else{
								if ($include) {
									$amt = number_format($amtArr[1], 2, '.', ','); //format the amount
									// $amt = floatval($amt);
									if ((int)$optional == 0) {
										$totamt += floatval($amtArr[1]); //calculate the total amount
										$totamtArr[$nameid] = floatval($amtArr[1]);
									}
									// $id = str_replace(" ","_",$name);
									/* $trs .= "<tr class=\"phtrTp\" style=\"text-align:left\">
                                     	<td width=\"10%\">{$cnt}</td><td width=\"60%\">{$name}</td><td width=\"30%\">{$amt}</td>
                                     </tr >";*/
									//$printBrkDwn .= $brkDnArr[$d]."***";
									$disabled = 0; //disabled at default is false(0)
									if ((int)$optional > 0) $disabled = 1; //if it is optional disable it at default
									$printBrkDwn .= $name . "~" . $amtArr[1] . "~$nameid~$optional~$disabled" . "***"; //form break down for printing slip
									$printBrkDwnArr[$nameid] = $name . "~" . $amtArr[1] . "~$nameid~$optional~$disabled";
									$cnt++;
								}
							}
						}
					}
				}
			}
		}
	} else {
		return "No Payment Break-Down Found";
	}
	/* if($cnt > 1){ //if breakdown found
	      if((int)$stateID != 3 && (int)$payItemID == 2){ //if not indigene and payment is school fee, add developmental fee = 20,000
			  $trs .= "<tr class=\"phtrTp\" style=\"text-align:left\">
                                     	<td width=\"10%\">{$cnt}</td><td width=\"60%\">Development Fees</td><td width=\"30%\">20000.00</td>
                                     </tr >";
										  $cnt++;
										  $totamt += 20000.00;
										  $printBrkDwn .= "Development Fees|-1=20000.00|3"."***";
		  }
		  
		  //add the transaction charge
		  $trs .= "<tr class=\"phtrTp\" style=\"text-align:left\">
                                     	<td width=\"10%\">{$cnt}</td><td width=\"60%\">Transaction Charges</td><td width=\"30%\">300.00</td>
                                     </tr >";
										  $pricepay = $totamt;
									 $totamt += 300.00; //transaction charge
										  $printBrkDwn .= "Transaction Charges|-1=300.00|3";
	  }*/
	//AKSCOE LATE WORKAROUND
	//WORK AROUND 1
	/*if(isset($studrec['LateAmt']) && $studrec['LateAmt'] > 0.00 && $lvl == $studrec['LateLvl'] && $sem == $studrec['LateSem'] ){
		$totamt += $studrec['LateAmt'];
		$printBrkDwn .= "Late Charge~".$studrec['LateAmt']."***"; 

	   }*/
	//AKSCOE LATE WORKARROUND
	//$rtot = number_format($totamt, 2, '.', ',');
	$totamt = array_sum(array_values($totamtArr));
	$rtot = number_format($totamt, 2, '.', ',');
	/*$trs .= "<tr class=\"phtrTp\" style=\"text-align:left; font-weight:bold\">
                                     	<td colspan=\"2\" style=\"text-align:right; padding-right:4px; \">Total:</td><td width=\"30%\">{$rtot}</td>
                                     </tr >";*/


	$printBrkDwn = rtrim($printBrkDwn, "***");
	 if(!is_null($ItemID)){
		if(!isset($printBrkDwnArr[$ItemID]))return "Item Not Exist in Breakdown";
		$itemtot = isset($totamtArr[$ItemID])?$totamtArr[$ItemID]:0;
		return [$itemtot,number_format($itemtot,2),$printBrkDwnArr[$ItemID]];
	} 
	$printBrkDwnStr = implode("***", array_values($printBrkDwnArr));
	return array($totamt, $rtot, $printBrkDwnStr);
}


//function to get payment item breakdown
function PaymentBreakDownOld($PayBrkDn, $lvl, $sem, $studrec = array(), $sempart = 3)
{
	//AKSCOE LATE WORKAROUND
	//WORK AROUND 2
	if (count($studrec) > 0) {

		global $dbo;
		//Get the student payment level
		$studpaylvl = $lvl;
		$studregNo = (trim($studrec['RegNo']) == "") ? $studrec['JambNo'] : $studrec['RegNo'];
		$studexplvl = StudLevel($studregNo);
		$studclass = "CURR";
		$studStartSes = !isset($studrec['StartSes']) ? StudStartSes($studregNo) : $studrec['StartSes'];
		if ((int)$studpaylvl < (int)$studexplvl) {
			$studclass = "PREV";
		}

		//Get all extra payment
		$extrpay = $dbo->Select("extrapay_tb", "", "(StudClass = '$studclass' OR StudClass = 'BOTH') AND (MaxStudStartSes <= $studStartSes OR MaxStudStartSes = -1) AND Status = 1");
		//echo $studStartSes;
		// $PayBrkDn .= "***".$extrpay."|-1=1000|3";
		if (is_array($extrpay) && $extrpay[1] > 0) {

			while ($extrapayitem = $extrpay[0]->fetch_array()) {
				//$PayBrkDn .= "***StudClass - {$extrapayitem['item']} |-1=10000|3";
				$PayBrkDn .= "***" . $extrapayitem['Item'];
			}
		}
		// echo $PayBrkDn;
	}
	//AKSCOE LATE WORKAROUND
	$brkDnArr = explode("***", $PayBrkDn); //break all payment items string as array
	$cnt = 1;
	$trs = "";
	$totamt = 0.0;
	$printBrkDwn = "";
	if (count($brkDnArr) > 0) { //if items found
		for ($d = 0; $d < count($brkDnArr); $d++) { //loop through individual items
			$include = false; //determine if the current payment item is to be included
			$brkItem = $brkDnArr[$d]; //get current payment item string
			$brkItemCondArr = explode("?", $brkItem); //break item string into array by the "?" condition character; to know if there exist a condition for the display of item
			$cond = (1 == 1);
			if (count($brkItemCondArr) > 1) { //if condition exist, i.e split exist meaning "?" condition exist
				$condstr =  $brkItemCondArr[0]; //get the condition part
				$brkItem = $brkItemCondArr[1]; //get the item real string
				$condArr = explode("==", $condstr); //break condition down by spliting the attribute and value
				if (count($condArr) > 1) { //if conndition is checking "=="
					$atr = $condArr[0]; //get atribute
					$val = $condArr[1]; //get value
					$opr = "==";
					//Note - attribute must be one of studentinfo_tb field
					$cond = ($studrec[$atr] == $val); //form the condition by checking if student atrribute value is same as supplied value
				} else { //if conndition is checking "!="
					$condArr = explode("!=", $condstr);
					if (count($condArr) > 1) {
						$atr = $condArr[0]; //get the attribute
						$val = $condArr[1]; //get the value
						// $opr = "==";
						$cond = ($studrec[$atr] != $val); //form the condition by checking if student atrribute value is not same as supplied value
					}
				}
			}
			if ($cond == false) { //if condition not satisfied break
				//i.e skip the item for the student
				continue;
			}
			$itemcontArr = explode("|", $brkItem); //break down the real payment item string
			if (count($itemcontArr) == 3) { //if total payment item element is 3 i.e a valid payment item string
				$name = $itemcontArr[0]; //get the payment item name
				$amtList = explode("~", $itemcontArr[1]); //breakdown the amount structure, to get varous amount for deferent levels

				if (count($amtList) > 0) { // if multiple amount found
					// $alllev = "";
					foreach ($amtList as $amtstr) { //loop through all the amounts
						$amtArr = explode("=", $amtstr); //breakdown individual amount
						if (count($amtArr) == 2) { //if a valid individual amount structure
							if ((int)$amtArr[0] == $lvl || $amtArr[0] == "-1") { //if payment item amount level is student level or is for all level(-1)
								//get the amount condition for that level

								$amtRealarr = explode("#", $amtArr[1]);
								if (count($amtRealarr) > 1) { //if multiple amount found
									$identifier = $amtRealarr[0]; //get the name of the operation or field to confirm form, e.g Fac - get amount base on faculty
									if (count($studrec) > 0) { //if student details send
										//Fac($progID)
										//based on faculty 
										if (trim($identifier) == "Fac") {
											$studProgId =  $studrec['ProgID']; //the students programme Id
											$facD = Fac($studProgId); // get the faculty details of the programme using the progID
											if (is_array($facD)) {
												$facID = $facD['FacID'] . ""; //get the students facID
												//loop through all amounts
												for ($s = 1; $s < count($amtRealarr); $s++) {
													$fisrtAmtArrm = explode("@", $amtRealarr[$s]);
													$firstAmtm = $fisrtAmtArrm[1]; //get the amount
													$facmID = $fisrtAmtArrm[0]; //get the facID
													if (trim($facmID) == trim($facID)) { //if student facID is the curremt amount facID
														$amtArr[1] = $firstAmtm; //set the real amount
														break;
													}
												}
												//$name = $amtArr[1];
												//$amtArr[1] = $identifier;
											}
										}
									} else { //if no student info send pick the first amount
										//break down the first amount
										$fisrtAmtArr = explode("~", $amtRealarr[1]);
										$firstAmt = $fisrtAmtArr[1]; //get the amount
										$amtArr[1] = $firstAmt;
									}
								}
								//calculate Tution for part payment
								/* if(trim($name)=="Tuition" && $sem == 1){
									   $percent = 50; //percent deduction
									 $amtArr[1] = ($percent/100) * (float)$amtArr[1];
								 }*/
								if ($sem < 3 && trim($itemcontArr[2]) != 3) { //if part payment policy for the current payment item exit
									$partpaymentlist = explode("~", $itemcontArr[2]); //breakdown the part payment policy string

									if (count($partpaymentlist) > 0) {
										for ($as = 0; $as < count($partpaymentlist); $as++) { //loop through all the policies
											$partp = explode("=", $partpaymentlist[$as]); //breakdown the current policy to get the semester and percentage amount of the main amount
											$brdwnSem = trim($partp[0]); //the current break down semester
											//comfirm if it has a SemPart
											$SemPrtStr = explode("_", $brdwnSem);
											$SemPrtcond = count($SemPrtStr) > 1 ? true : false; //if more than one sem id found: It is a SemPart Structure
											//return $amtArr[0]."=".$amtArr[1];
											//return $SemPrtcond . " ; " . $brdwnSem;
											//return "Level: ".$amtArr[0]." ; Sem: ".$sem." ; ItemSem: ".$brdwnSem." ; SemPart: ".$sempart." ; ContainSemPart: ".$SemPrtcond;
											if (($SemPrtcond == false && (int)$brdwnSem == $sem) || ($SemPrtcond == true && $brdwnSem == $sem . "_" . $sempart)) { //if the part id = 1 or 2 for half share and 1_1, 1_2, 1_3, 2_1, 2_2, 2_3 for quater sharing exit, get the percentage part and calculate amount

												//calculate amount based on percentage part
												$amtArr[1] = round((float)$partp[1] * (float)$amtArr[1]);
												$include = true;
												break;
											}
										}
									}
								} elseif ($sem == 3) { //if full payment selected
									$amtArr[1] = (float)$amtArr[1];
									$include = true;
								} elseif ($sem == 1 && ($sempart == 1 || $sempart == 3) && (int)$itemcontArr[2] == 3) {
									//if user selected sem is first and aempart is first part or first full and the item is to be paid full allow it 
									$amtArr[1] = (float)$amtArr[1];
									$include = true;
								}

								//if student sem is 2 or student is completing first sem payment i.e sem is 1 and sempart is 2 and the polycy of item is 3; i.e the item is for full payment or first payment only
								// if($include == false || (($sem == 2 || ($sem == 1 && $sempart == 2)) && (int)$itemcontArr[2] == 3)){
								//do nothing
								//}else{
								if ($include) {
									$amt = number_format($amtArr[1], 2, '.', ','); //format the amount
									// $amt = floatval($amt);
									$totamt += floatval($amtArr[1]); //calculate the total amount
									// $id = str_replace(" ","_",$name);
									/* $trs .= "<tr class=\"phtrTp\" style=\"text-align:left\">
                                     	<td width=\"10%\">{$cnt}</td><td width=\"60%\">{$name}</td><td width=\"30%\">{$amt}</td>
                                     </tr >";*/
									//$printBrkDwn .= $brkDnArr[$d]."***";
									$printBrkDwn .= $name . "~" . $amtArr[1] . "***"; //form break down for printing slip
									$cnt++;
								}
							}
						}
					}
				}
			}
		}
	} else {
		return "No Payment Break-Down Found";
	}
	/* if($cnt > 1){ //if breakdown found
	      if((int)$stateID != 3 && (int)$payItemID == 2){ //if not indigene and payment is school fee, add developmental fee = 20,000
			  $trs .= "<tr class=\"phtrTp\" style=\"text-align:left\">
                                     	<td width=\"10%\">{$cnt}</td><td width=\"60%\">Development Fees</td><td width=\"30%\">20000.00</td>
                                     </tr >";
										  $cnt++;
										  $totamt += 20000.00;
										  $printBrkDwn .= "Development Fees|-1=20000.00|3"."***";
		  }
		  
		  //add the transaction charge
		  $trs .= "<tr class=\"phtrTp\" style=\"text-align:left\">
                                     	<td width=\"10%\">{$cnt}</td><td width=\"60%\">Transaction Charges</td><td width=\"30%\">300.00</td>
                                     </tr >";
										  $pricepay = $totamt;
									 $totamt += 300.00; //transaction charge
										  $printBrkDwn .= "Transaction Charges|-1=300.00|3";
	  }*/
	//AKSCOE LATE WORKAROUND
	//WORK AROUND 1
	/*if(isset($studrec['LateAmt']) && $studrec['LateAmt'] > 0.00 && $lvl == $studrec['LateLvl'] && $sem == $studrec['LateSem'] ){
		$totamt += $studrec['LateAmt'];
		$printBrkDwn .= "Late Charge~".$studrec['LateAmt']."***"; 

	   }*/
	//AKSCOE LATE WORKARROUND
	$rtot = number_format($totamt, 2, '.', ',');
	/*$trs .= "<tr class=\"phtrTp\" style=\"text-align:left; font-weight:bold\">
                                     	<td colspan=\"2\" style=\"text-align:right; padding-right:4px; \">Total:</td><td width=\"30%\">{$rtot}</td>
                                     </tr >";*/


	$printBrkDwn = rtrim($printBrkDwn, "***");
	return array($totamt, $rtot, $printBrkDwn);
}

function GetPaymentItem($payID)
{
	global $dbo;
	$payID = (int)$payID;
	$query = "SELECT * FROM item_tb  WHERE ID = {$payID} LIMIT 1";
	$rst = $dbo->RunQuery($query);
	$err = NULL;
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$err = $rst[0]->fetch_array();
		}/*else{
					$err = NULL;
				}*/
	}/*else{
				$err = true;
			}*/
	return $err;
}
//************Modified******************
//$paymentItems = array('1'=>array("Acceptance Fees","Pay for Acceptance Fee.","acceptpay"), '2'=>array("School Fees","The School fees payment and other school related payment.","schpay"), '3'=>array("putme Form","Buy Post-UTME form","putmepay"));

//function to load courses 
/*function LoadCourseReg($regno, $Lower = false, $rp = 0){
<tr class=\"phtrsel\" title=\"Click to Select/Deselect\">
                                     	<td width=\"10%\">1
                                      </td><td width=\"25%\">COM 123</td><td width=\"55%\">Computer Fundermental</td><td width=\"10%\" class=\"ch\">20</td>
                                     </tr >	
	$studinfo = GetBasicInfo($regno,"stud");
	global $dbo;
	$ProgID = (int)$studinfo['ProgID'];
	$lvlar =  StudLevelSpill($regno);
	$lvl = (int)$lvlar[0];
	$sem = GetCourseRegSem($regno,0,$rp);
	$sem = (int)$sem[0];
	$cont = "";
	$op = ($Lower)?"<":"=";
	
	$rst = $dbo->RunQuery("SELECT * FROM course_tb WHERE  Lvl {$op} {$lvl} AND DeptID = {$ProgID} AND Sem = {$sem} order by Lvl desc");
	if(is_array($rst)){
		if($rst[1] > 0){
			$cnt = 0;
			while($rstt = $rst[0]->fetch_array()){
				$cnt++;
				$code = $rstt['CourseCode'];
				$title = $rstt['Title'];
				$CH = $rstt['CH'];
				$CID = $rstt['CourseID'];
				$clss = ((int)$rstt['Elective'] == 1)?"phtre":"phtr"; //outstanding => phtrsel
				$cont .= "<tr class=\"{$clss}\" id=\"{$CID}course\"  onclick=\"CourseReg.Select(this)\" title=\"Click to Select/Deselect\">
                                     	<td width=\"10%\">{$cnt}</td><td width=\"25%\" class=\"CCode\" style=\"text-transform:uppercase\">{$code}</td><td width=\"55%\" class=\"TTit\" style=\"text-transform:uppercase\">{$title}</td><td  width=\"10%\" class=\"ch\">{$CH}</td>
                                     </tr>
						
									 ";
		
			}
			
			    if($op == "="){
					$cont .= "<tr  title=\"Load Lower Level Courses\" id=\"loadlC\">
                                     	<td colspan=\"4\" style=\"font-size:1.1em; color:#E9E9E9\"><a href=\"javascript:CourseReg.LoadLowerCourse('{$regno}')\" title=\"Load Lower Level Courses\" style=\"float:left;font-style:\">Load Lower Level Courses</a></td>
                                     </tr>
									 
									 ";
				}
			
			//$cont .= "SELECT * FROM course_tb WHERE  Lvl {$op} {$lvl} AND DeptID = {$ProgID} AND Sem = {$sem} order by Lvl desc";
		}else{
			$cont = "#";
		}
	}else{
		$cont = "##";
	}
	return $cont;
}*/
//************Modified******************

//functon to get all courses from database for a particular student, given the level and semester
function GetStudCourses($regno, $lvl, $sem, $lower = false, $ProgID = 0, $enableonly = true)
{
	global $dbo;
	$studinfo = GetBasicInfo($regno, "stud");
	$StudyID = $studinfo['StudyID'];
	//return $studinfo['RegNo'];
	if ($ProgID == 0) {
		$ProgID = (int)$studinfo['ProgID'];
	}
	$op = ($lower) ? "<" : "=";
	$lvl = (int)$lvl;
	$sem = (int)$sem;
	//************Modified******************
	$lvlses = StudSes($regno, $lvl, (int)$studinfo['StartSes'], GetMOEID($studinfo['ModeOfEntry']));

	//if only enabeled course or both
	$enableonly = $enableonly ? "AND CourseStatus = 0" : "";

	$rst = $dbo->RunQuery("SELECT * FROM course_tb WHERE  Lvl {$op} {$lvl} AND DeptID = {$ProgID} AND Sem = {$sem} AND StudyID = {$StudyID} $enableonly AND StartSesID <= $lvlses AND (EndSesID >= $lvlses OR EndSesID = 0) order by Lvl desc, CourseCode ASC"); //************Modified******************
	//if(is_array($rst)){
	return  $rst;
	//}
}

//function to get the semester name
function SemesterName($Sem)
{
	global $dbo;
	if ((int)$Sem < 1) return '';
	$semn = $dbo->SelectFirstRow("semester_tb", "Sem", "Num = " . $Sem);
	if (!is_array($semn)) return 'ALL';
	return $semn['Sem'];
}

//function to get the semester name
function SemesterDescription($Sem)
{
	global $dbo;
	if ((int)$Sem < 1) return '';
	$semn = $dbo->SelectFirstRow("semester_tb", "IF(Descr='',Sem,Descr) as Descr", "Num = " . $Sem);
	if (!is_array($semn)) return 'UNKNOWN';
	return $semn['Descr'];
}

//function to get the current activated semester
function GetCurrentSem()
{
	global $dbo;
	$rst = $dbo->RunQuery("SELECT Num,Sem,IF(Descr='',Sem,Descr) as Descr from semester_tb where Enable = 1 ORDER BY Current DESC LIMIT 1");
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$rstrw = $rst[0]->fetch_array();
			return $rstrw;
		} else {
			return false;
		}
	} else {
		return false;
	}
}
//function to get the next semester to register courses
/*function GetCourseRegSem($RegNo, $lvl = 0, $rp = "0"){
	$regCourse = GetRegCourses($RegNo,$lvl);
	 if(is_array($regCourse)){ //if the top registration semester is not 2
	    if($regCourse[0] < 2){
					  if($regCourse[0] == 0){ //if not registered at all sem is First
						  $semester = "First";
						  $semCode = 1;
					  }else{ //if first semester already registered sem is Second
						 $semester = "Second";
						   $semCode = 2;
					  }
			$regCourse = array($semCode,$semester);
		}else{
			$regCourse = array(0,"Registered");
		}
	 }else{
		 $regCourse = array(-1,"Error");
	 }
	 if($rp == "1"){
					  if($regCourse[0] == 0){
						 $regCourse = array(2,"Second"); 
					  }else if($regCourse[0] == 2){
						  $regCourse = array(1,"First"); 
					  }else{
						  $regCourse = array(-1,"Error"); 
					  }
				  }
	return $regCourse;
}*/

//function to get the student top semester id and name
function GetCourseRegSem($RegNo, $lvl = 0, $rp = "0")
{
	$regCourse = GetRegCourses($RegNo, $lvl); //Get Student Corses Registered in a particular Level, returns array of the top sem and the courses
	$currSem = GetCurrentSem(); //get the currently activated semester [0] => id, [1] => Semester name
	if (is_array($regCourse)) { //if the top registration semester is not 2

		if ($regCourse[0] != $currSem[0]) { //if last reg sem is not current sem
			/*if($regCourse[0] == 0){ //if not registered at all sem is First
						  $semester = "First";
						  $semCode = 1;
					  }else{ //if first semester already registered sem is Second
						 $semester = "Second";
						   $semCode = 2;
					  }*/
			//use current semester
			$regCourse = array($currSem[0], $currSem[1]);
		} else { //else already register
			$regCourse = array(0, "Registered");
		}
	} else { //error
		$regCourse = array(-1, "Error");
	}
	if ($rp == "1") {
		if ($regCourse[0] == 0) {
			$regCourse = array($currSem[0], $currSem[1]);
		} else {
			$regCourse = array(-1, "Error");
		}
	}
	return $regCourse;
}

//function to Get Student Corses Registered in a particular Level - Return the top semester and the courses
function GetRegCourses($RegNo, $lvl = 0)
{
	global $dbo;
	if ($lvl == 0) { //if no level suplied get the current student
		$lvl = StudLevel($RegNo);
	}
	$lvl = $dbo->SqlSave($lvl);
	$sqlRegNo = $dbo->SqlSave($RegNo);
	$query = "SELECT * FROM coursereg_tb WHERE RegNo = '{$sqlRegNo}' AND Lvl = {$lvl} order by Sem desc";
	$rst = $dbo->RunQuery($query);
	$courses = array();
	$topSem = 0;
	if (is_array($rst)) {
		if ($rst[1] > 0) {

			while ($rstrw = $rst[0]->fetch_array()) {
				$courses[] = $rstrw;
				if ($topSem == 0) {
					$topSem = $rstrw['Sem'];
				}
			}
			//$paypol = rtrim($paypol,":");
			return array($topSem, $courses);
		} else {
			return array($topSem, $courses);
		}
	} else {
		return $rst;
	}
}

//check if the supplied student has paid for the supplied item for a specific level
//added sesID 12/7/16
function HasPaid($regNo, $payID, $lvl = 0, $sem = 0, $sempart = 3, $RegID = 1, $SesID = 0)
{
	global $dbo;

	$payID = (int)$payID;

	$msg = ""; //holds the message from third party
	if ($lvl == 0) { //if no level suplied get the current student
		$pre = StudPreByPayID($payID, $RegID);
		$lvl = StudLevel($regNo, $pre);
	}

	//if ses not sent use the current ses
	if ($SesID == 0) {
		$Ses = CurrentSes();
		$SesID = $Ses['SesID'];
	}

	$sempartquery = (int)$sempart != 0 ? (int)$sempart > 1 ? "(SemPart = 2 OR SemPart = 3)" : "(SemPart = {$sempart} OR SemPart = 3)" : "1 = 1"; //if sempart is 3 or 2 are financially thesame, because the two represent completion of payment,i.e are to be considered as such in payment verification
	$semquery = ($sem == 0) ? " AND Sem = 3" : " AND (Sem = 3 OR (Sem = {$sem} AND {$sempartquery}))";
	$sqlregNo = $dbo->SqlSave($regNo);
	$lvl = (int)$lvl;
	//Handling Session for Prev Payment Checking
	//****************************************
	$SesQ = "AND Ses = $SesID";
	if ($SesID < 0) { //if session is negative force checking not to consider ses
		$SesQ = "";
	}

	//get the student current programme
	$ProgID = GetStudentProgIDForPay($regNo);

	//exit($sem);
	//***************************************
	//get if student place other
	$query = "SELECT * FROM order_tb WHERE RegNo = '{$sqlregNo}' AND Lvl = {$lvl} AND ItemID = {$payID} AND ProgID={$ProgID} {$semquery} {$SesQ} order by Paid desc, RegDate desc, Sem desc, SemPart desc";
	//exit($query);
	$rst = $dbo->RunQuery($query);
	//note - the system currently is not checking order on simester bases which will pose issue on school fee part payment - RESOLVED
	if (is_array($rst)) {

		if ($rst[1] > 0) { //st
			$det = $rst[0]->fetch_array();
			return HasPaidRef($det['TransNum'], $det);
		} else {
			return array(0, $sem, $payID, $lvl, $sem, "Order Details not Found", 3);	//no order placed 
		}
	} else {
		return array(0, $sem, $payID, $lvl, $sem, "Internal Error", 7);	//no order placed 
		//return array("4",$rst); //error
	}

	//if payment ses not sent use the current session
	/* if($SesID == 0){
			$Ses = CurrentSes();
			$SesID = $Ses['SesID'];
		}
		
		   //check if hasPaid locally
		    $paid = CheckPayLocal($regNo,$payID,$lvl,$sem,$sempart,$RegID,$SesID);
			
			//if has paid return payment status array
		   if($paid[0] == 1)return $paid;
		   
		   //if not paid check etransact, if paid in bank, update local database
			$cp = CheckPay($regNo,$payID,$lvl,$sem,$sempart,$RegID,$SesID);
			//return $cp;
			
			if(is_array($cp)){
				return $cp;
			}
			$cpbf = $cp;
			$cparr = explode("#",$cp);
			$cp = $cparr[0];
			if($cp == "0"){
				return array(0,0,$payID,$lvl,0,"Go to Bank with the generated Payment Analysis Slip to make payment",1,$cpbf);
			}elseif($cp == "1"){
				return array(0,0,$payID,$lvl,0,"Invalid Amount Paid",2,$cparr[1]);
			}elseif($cp == "2"){
				return array(0,0,$payID,$lvl,0,"Internal Error: Invalid Parameter received from Third-Party",3,$cparr[1]);
			}elseif($cp == "3"){
				return array(0,0,$payID,$lvl,0,"Make Payment",4,$cparr[1]);
			}elseif($cp == "4"){
				return array(0,0,$payID,$lvl,0,"Server Error",5,$cparr[1]);
			}elseif($cp == "5"){
				return array(0,0,$payID,$lvl,0,"Transaction Failed",6,$cparr[1]);
			}elseif($cp == "6"){
				return array(0,0,$payID,$lvl,0,"Invalid Parameter or Bad Network",7,$cparr[1]);
			}elseif($cp == "#"){
				   return CheckPayLocal($regNo,$payID,$lvl,0,$sempart,$RegID,$SesID);
			}else{
			//return array(0,0,2,1,$cp);
			//check if paid local again and return payment status array
		 return array(0,0,$payID,$lvl,0,"UnKnown Error");
			} */



	/*}else{
		return $rst;
	}*/

	//}
}

//function HasPaid by Ref
function HasPaidRef($Ref, $orderdet = NULL)
{

	global $dbo;
	if (!isset($orderdet) || is_null($orderdet)) {
		//get the order details
		$orderdet = $dbo->SelectFirstRow("order_tb", "", "TransNum='" . $dbo->SqlSafe($Ref) . "'");
		if (!is_array($orderdet)) return [0, 0, 0, 0, 0, "Invalid Payment Reference", 7];
	}

	// return $orderdet;
	//check Has Paid Local
	$paid = CheckPayLocalRef($Ref, $orderdet);

	//return json_encode($paid);
	if ($paid[0] == 1) return $paid;

	$sch = GetSchool('PayVerifyType');
	if ($sch['PayVerifyType'] == "DEEP") {
		//check gateway
		return VerifyPayFromGateway($Ref, $orderdet);
	} else {
		return $paid;
	}
}

function HasPaidRef2($Ref, $orderdet)
{

	global $dbo;
	if (!isset($orderdet)) {
		//get the order details
		$orderdet = $dbo->SelectFirstRow("order_tb", "", "TransNum='" . $dbo->SqlSafe($Ref) . "'");

		if (!is_array($orderdet)) return [0, 0, 0, 0, 0, "Invalid Payment Reference", 7];
	}


	// return $orderdet;
	//check Has Paid Local
	$paid = CheckPayLocalRef($Ref, $orderdet);

	//return json_encode($paid);
	if ($paid[0] == 1) return $paid;
	//return [implode("<br />",get_included_files())];

	//check gateway
	return VerifyPayFromGateway($Ref, $orderdet, "dddd");
}

//update wallet payment - credit the wallet
function WalletUpdate($orderdet)
{
	global $dbo;
	if (!isset($orderdet['PayScope']) || $orderdet['PayScope'] != "w") return -1;
	if ($orderdet['PayScope'] == "w") {
		$bal = 0;
		$lasttrans = $dbo->SelectFirstRow("wallet_tb", "", "RegNo='" . $dbo->SqlSafe($orderdet['RegNo']) . "' ORDER BY ID DESC LIMIT 1");
		if (is_array($lasttrans)) { //if transaction exist
			$bal = (float)$lasttrans['Balance'];
		}
		//update the student wallet balance
		$studwall = $dbo->RunQuery("INSERT INTO wallet_tb(Flow, RegNo, Amt, RefNo,Balance,TransDate,Status,TransDetails) VALUES (0,'" . $dbo->SqlSafe($orderdet['RegNo']) . "'," . $orderdet['Amt'] . ",'" . $orderdet['TransNum'] . "',($bal + " . $orderdet['Amt'] . "),'" . date('Y-m-d H:i:s') . "',1,'Deposit into Account(" . $orderdet['RegNo'] . ")')", "hshh");
		if (!is_array($studwall)) {
			return $studwall;
		}
		return $dbo->Connection->insert_id;
	}
	return -1;
}

//debit wallet account
function WalletDowndate($orderdet)
{
	global $dbo;
	//if(!isset($orderdet['PayScope']) || $orderdet['PayScope'] != "w")return -1;
	// if($orderdet['PayScope'] == "w"){
	$bal = 0;
	$lasttrans = $dbo->SelectFirstRow("wallet_tb", "", "RegNo='" . $dbo->SqlSafe($orderdet['RegNo']) . "' ORDER BY ID DESC LIMIT 1");
	if (is_array($lasttrans)) { //if transaction exist
		$bal = (float)$lasttrans['Balance'];
	}
	//update the student wallet balance
	$studwall = $dbo->RunQuery("INSERT INTO wallet_tb(Flow, RegNo, Amt, RefNo,Balance,TransDate,Status,TransDetails) VALUES (1,'" . $dbo->SqlSafe($orderdet['RegNo']) . "'," . $orderdet['Amt'] . ",'" . $orderdet['TransNum'] . "',($bal - " . $orderdet['Amt'] . "),'" . date('Y-m-d H:i:s') . "',1,'Paid Fee From Wallet(" . $orderdet['ItemName'] . ")')", "hshh");
	if (!is_array($studwall)) {
		return $studwall;
	}
	return $dbo->Connection->insert_id;

	//  }
	// return -1;
}

//create order details
function CreateOrder($Reg, $orderinfo = [])
{
	global $dbo;
	if (!isset($Reg)) {
		return '{"Error":"Invalid Student"}';
	}
	if (!isset($orderinfo['TransNum'])) {
		$RefDet = generateTransInfoOnly();
		$orderinfo['TransNum'] = $RefDet[1];
		$orderinfo['ItemNo'] = $RefDet[0];
	}

	//get the current session
	$CurSes = CurrentSes();
	$CurSes = $CurSes['SesID'];
	//check if reference already exist
	/* $orderdet = $dbo->SelectFirstRow("order_tb","TransNum,Amt","TransNum='".$dbo->SqlSafe($Ref)."'");
        if(is_array($orderdet)){
			return '{"Ref":"'.$orderdet['TransNum'].'","Amt":'.$orderdet['Amt'].'}';
		} */

	if (count($orderinfo) < 1) {
		return '{"Error":"Invalid Order Details"}';
	}

	if (isset($orderinfo['PayID'])) { //if payID isset
		$orderinfo['ItemID'] = $orderinfo['PayID'];
	}

	if (!isset($orderinfo['ItemID'])) {
		return '{"Error":"Invalid Payment Type"}';
	}

	/* if (!isset($orderinfo['ItemName'])) {
		//get the Payment Details
		$paydet = $dbo->SelectFirstRow("item_tb", "ItemName,ItemDescr,Currency,PayGatewayID,studType", "ID=" . $orderinfo['ItemID']);
		if (!is_array($paydet)) {
			return '{"Error":"Fetching payment type information failed"}';
		}

		$orderinfo = array_merge($orderinfo, $paydet);
	} */
	if (!isset($orderinfo['ItemName']) || !isset($orderinfo['PayGatewayID'])  || !isset($orderinfo['PayBrkDn'])) {
		//get the Payment Details
		$paydet = $dbo->SelectFirstRow("item_tb", "ItemName,ItemDescr,Currency,PayGatewayID,studType,PayBrkDn", "ID=" . $orderinfo['ItemID']);
		if (!is_array($paydet)) {
			return '{"Error":"Fetching payment type information failed"}';
		}

		$orderinfo = array_merge($orderinfo, $paydet);
	}



	$BrkDwn = "";
	if (!isset($orderinfo['Amt']) || (float)$orderinfo['Amt'] < 1) {
		$anal = PaymentBreakDown($orderinfo['PayBrkDn'], $orderinfo['Lvl'], $orderinfo['Sem'], $Reg, $orderinfo['SemPart']);
		$BrkDwn = is_array($anal) ? $anal[2] : "";
		$orderinfo['Amt'] = $anal[0];
		return '{"Error":"Invalid Amount"}';
	}

	if (!isset($orderinfo['BrkDwn']) || trim($orderinfo['BrkDwn']) == "") {
		$orderinfo['BrkDwn'] = $BrkDwn;
	}

	$Sem = isset($orderinfo['Sem']) ? (int)$orderinfo['Sem'] : 1;
	$HeihestSemNum = HighestSemester();
	$PaySem = (int)$Sem > (int)$HeihestSemNum['Num'] ? (int)$HeihestSemNum['Num'] : $Sem;
	$default = [
		"ItemNo" => isset($orderinfo['ItemNo']) ? $orderinfo['ItemNo'] : (mt_rand(1000, 999999999) . date("dmyHis")),
		"TransNum" => $orderinfo['TransNum'],
		"ItemName" => $orderinfo['ItemName'],
		"ItemDescr" => isset($orderinfo['ItemDescr']) ? $orderinfo['ItemDescr'] : "",
		"Amt" => $orderinfo['Amt'],
		"Currency" => isset($orderinfo['Currency']) ? $orderinfo['Currency'] : 1,
		"RegNo" => $Reg,
		"SemPart" => isset($orderinfo['SemPart']) ? $orderinfo['SemPart'] : 3,
		"Sem" => $Sem,
		"Lvl" => isset($orderinfo['Lvl']) ? $orderinfo['Lvl'] : 1,
		"ItemID" => $orderinfo['ItemID'],
		"Paid" => 0,
		"Ses" => $CurSes,
		"RegDate" => date('Y-m-d'),
		"BrkDwn" => $orderinfo['BrkDwn'],
		"PayGatewayID" => $orderinfo['PayGatewayID'],
		"Info" => StudPatchDet($Reg, $orderinfo['ItemID'], isset($orderinfo['Lvl']) ? $orderinfo['Lvl'] : 1),
		"PayScope" => isset($orderinfo['studType']) ? $orderinfo['studType'] : "r",
		"SchSem" => $PaySem,
		"ProgID" => isset($orderinfo['ProgID']) ? $orderinfo['ProgID'] : GetStudentProgIDForPay($Reg),
	];

	$insorder = $dbo->InsertID2("order_tb", $default);
	if (!is_numeric($insorder) || $insorder < 1) return '{"Error":"Storing order details Failed - ' . $insorder . '"}';
	return '{"Ref":"' . $orderinfo['TransNum']. '","Amt":' . $orderinfo['Amt'] . '}';
}

function MakePaidByRef($Ref, $orderdet = [], $param = [], $fromWallet = 0)
{
	global $dbo;
	//return ["aaa"=>"ddddd"];
	if (!isset($orderdet) || count($orderdet) == 0) {
		//get the order details
		$orderdet = $dbo->SelectFirstRow("order_tb", "", "TransNum='" . $dbo->SqlSafe($Ref) . "'", MYSQLI_ASSOC);
		if (!is_array($orderdet)) return [0, $Ref, "Invalid Payment Reference", -3];
	}
	if (isset($orderdet['Paid']) && (int)$orderdet['Paid'] == 1) { //if already paid
		return array(1, $orderdet['Sem'], $orderdet['ItemID'], $orderdet['Lvl'], $orderdet['Sem'], "Already Paid", 0, "", $orderdet['SemPart']);
	}
	// return $orderdet;
	if (count($param) < 1) {
		$param = ["Amt" => $orderdet['Amt'], "Bank" => "UNKNOWN", "Branch" => "UNKNOWN", "DateTime" => date('Y-m-d')];
	} else {
		$param['Amt'] = !isset($param['Amt']) ? $orderdet['Amt'] : $param['Amt'];
		$param['Bank'] = !isset($param['Bank']) ? "UNKNOWN" : $param['Bank'];
		$param['Branch'] = !isset($param['Branch']) ? "UNKNOWN" : $param['Branch'];
		$param['DateTime'] = !isset($param['DateTime']) ? date('Y-m-d') : $param['DateTime'];
	}
	$RegNo = $orderdet['RegNo'];
	$sem = $orderdet['Sem'];
	$sempart = $orderdet['SemPart'];
	$Lvl = $orderdet['Lvl'];
	$dt = new DateTime($param['DateTime']);
	$date = $dt->format("Y-m-d");
	$paytype = $orderdet['ItemID'];
	$transaction_number = $Ref;
	$item = $orderdet['ItemNo'];
	$Ses = $orderdet['Ses'];
	$bank_name = $param['Bank'];
	$amtPaid = $orderdet['Amt'];
	$GatewayAmt = isset($orderdet['GWAmt'])?$orderdet['GWAmt']:$orderdet['Amt'];
	$bank_branch = $param['Branch'];
	$val_number = $transaction_number . $item;
	$brkdwn = $dbo->SqlSave($orderdet['BrkDwn']);
	//$ses = CurrentSes();
	$sqlregNo = $dbo->SqlSave($RegNo);
	$progID = $orderdet['ProgID'];

	//insert into pay history
	$rstins = $dbo->RunQuery("INSERT INTO payhistory_tb(TransID, Amt, Bank, BnkBranch,itemNum,PayDate,Sem,Ses,Lvl,RegNo,PayID,validationNo,SemPart,PayBrkDn,Info,TransAmt,CollectBank,PayScope,SchSem,ProgID,FromWallet) VALUES ('" . $dbo->SqlSave($transaction_number) . "', " . $amtPaid . ", '" . $dbo->SqlSave($bank_name) . "','" . $dbo->SqlSave($bank_branch) . "','" . $dbo->SqlSave($item) . "','" . $dbo->SqlSave($date) . "'," . $sem . "," . $Ses . "," . $Lvl . ",'" . $sqlregNo . "'," . $dbo->SqlSave($paytype) . ",'" . $val_number . "',$sempart,'" . $brkdwn . "','" . $dbo->SqlSafe(StudPatchDet($RegNo, $paytype, $Lvl)) . "',$GatewayAmt,'" . $dbo->SqlSafe(GetCollectBank($paytype)) . "','" . $dbo->SqlSafe($orderdet['PayScope']) . "','" . $orderdet['SchSem'] . "'," . $progID . "," . $fromWallet . ")", "hgdsgh");
	if (is_array($rstins)) {
		//update the order tb (Paid field)
		$item = $dbo->SqlSave($item);
		$transaction_number = $dbo->SqlSave($transaction_number);
		$rstord = $dbo->RunQuery("UPDATE order_tb SET Paid = 1 WHERE TransNum = '" . trim($transaction_number) . "'", "jadvskj");
		$erro = "Internal Error: Updating Payment Order Details Failed";
		if (is_array($rstord)) {
			$autoreg = AutoRegCourses($sqlregNo, $Lvl, $sem, $Ses, $paytype);
			if ($autoreg !== TRUE) { //if auto course registration failed
				$dbo->RunQuery("UPDATE order_tb SET Paid = 0 WHERE TransNum = '" . trim($transaction_number) . "'", "jadvskj");
				$erro = $autoreg;
			} else {
				//perform wallet updaute (Credit Student wallet if it is to be paid to wallet)
				$orderdet["DateTime"] = $date;
				$walup = WalletUpdate($orderdet);
				if (!is_numeric($walup)) {
					$dbo->RunQuery("UPDATE order_tb SET Paid = 0 WHERE TransNum = '" . trim($transaction_number) . "'", "jadvskj");
					$erro = $walup;
				} else {
					$waldownerr = false;
					//debit student wallet if payment made via wallet
					if ($fromWallet == 1) {
						$waldown = WalletDowndate($orderdet);
						if (!is_numeric($waldown)) {
							$dbo->RunQuery("UPDATE order_tb SET Paid = 0 WHERE TransNum = '" . trim($transaction_number) . "'", "jadvskj");
							$erro = $waldown;
							$waldownerr = true;
						}
					}
					if ($waldownerr == false) { //if no error occur while debiting wallet
						return array(1, $sem, $paytype, $Lvl, $sem, "Payment Updated", 0, "", $sempart);
					}
				}
			}
		}
		//delete the inserted payment record
		$del = $dbo->Delete("payhistory_tb", "TransID = '" . $dbo->SqlSave($transaction_number) . "'");
		return [0, $orderdet["SemPart"], $orderdet["ItemID"], $orderdet["Lvl"], $orderdet["Sem"], $erro, 7];
	} else { // payhistory insertion failed
		return [0, $orderdet["SemPart"], $orderdet["ItemID"], $orderdet["Lvl"], $orderdet["Sem"], "Internal Error: Adding Payment Details Failed - $rstins", 7];
	}
}

//AutoRegister Courses
function AutoRegCourses($sqlregNo, $Lvl, $sem, $Ses, $paytype)
{
	global $dbo;
	//perform auto registration if enabled
	//get course control details
	$courseControl = COURSE();
	$sch = GetSchool("Abbr,OpUName,OpUPassw,OpSMSLive");
	if (isset($courseControl['AutoRegStatus']) && $courseControl['AutoRegStatus'] == "TRUE" && $paytype == $courseControl['PayID']) {

		//if auto course reg is enablPaymentBreakDowned
		//check if course already registered
		$CourseReg = $dbo->SelectFirstRow("coursereg_tb", "", "Lvl=" . $Lvl . " AND SesID=" . $Ses . " AND Sem=" . $sem . " AND RegNo='$sqlregNo'");
		if (!is_array($CourseReg)) { //if not registered
			//return json_encode($CourseReg);
			//get the student program
			$studprog = $dbo->SelectFirstRow("studentinfo_tb", "ProgID,SurName,FirstName,Phone", "RegNo='$sqlregNo' OR JambNo='$sqlregNo'");
			if (is_array($studprog)) { //student details exist
				//get all semester coureses
				$ProgIDc = $studprog['ProgID'];

				$Courses = $dbo->Select("course_tb", "", "DeptID=" . $ProgIDc . " AND Lvl=$Lvl AND Sem=$sem AND StartSesID <= $Ses AND (EndSesID >= $Ses OR EndSesID = 0) AND CourseStatus = 0");

				if (is_array($Courses) && $Courses[1] > 0) {
					//return "ddddd ".$Courses[1];
					$RegCoursesDet = [];
					$RegCourse = [];
					$maxch = GetMaxCH($ProgIDc, $Lvl, $sem);
					$totch = 0;
					while ($indc = $Courses[0]->fetch_assoc()) {
						$RegCoursesDet[$indc["CourseID"]] = $indc;
						$RegCourse[] = $indc["CourseID"];
						$totch += $indc['CH'];
					}

					$reg = $dbo->InsertID2("coursereg_tb", ["RegNo" => $sqlregNo, "Lvl" => $Lvl, "CoursesID" => implode("~", $RegCourse), "SesID" => $Ses, "Sem" => $sem, "RegDate" => date('Y-m-d'), "MaxCH" => $maxch, "CouresRegData" => json_encode($RegCoursesDet), "TotCH" => $totch]);
					if (!is_numeric($reg)) {
						//error registaring courses
					} else {
						//5. Generate New RegNo and Update as required
						$autoreg = AutoGenRegNo($sqlregNo);
						//Error(29," - ".$autoreg);
						//if error
						if (!is_array($autoreg) &&  $autoreg != "##"  &&  $autoreg != "####") {
							//remove course registered
							//$del = $dbo->Delete("coursereg_tb","ID=".$reg);
							if ($autoreg == "#") $autoreg = "Reading School Details Failed";
							if ($autoreg == "###") $autoreg = "Reading Student Details Failed";
							if ($autoreg == "#####") $autoreg = "Global Update Failed";
							//Error(29, ", and Course Registration Reversed - ".$autoreg); 
						} else {
							$AutoReg = [];
							//$autoreg = [$Param['RegNo']];
							if (is_array($autoreg)) {

								$NewReg = $autoreg[0];
								//Send Message - 
								$sendmail = $dbo->SendSMS($sch['Abbr'], "Hello, " . $studprog['SurName'] . " " . $studprog['FirstName'] . ", your school Registration Number is $NewReg", $studprog['Phone'], "234", $sch['OpUName'], $sch['OpUPassw'], $sch['OpSMSLive'] == "FALSE" ? false : true);
								$rstdet = explode("|", $sendmail);
								if (strtolower($rstdet[0]) == "success") {
									//$sendmail = TRUE;
								}
							}
						}
					}
				}
			}
		}
	}
	return TRUE;
}

//send notfcation
function Notify($RegNo, $msg = "", $title = "", $from = "")
{
	if (!isset($RegNo) || trim($RegNo) == "") return "Invalid Recepient";
	if (!isset($msg) || trim($msg) == "") return "Invalid Message";
	global $dbo;
	return $dbo->InsertID2("notification_tb", ["RegNo" => $RegNo, "Message" => $msg, "MDateTime" => date("Y-m-d H:i:s"), "SenderID" => $from, "Title" => $title]);
}

//function to get the current hiest semester
function SchoolHighestSemester()
{
	global $dbo;
	$hrec = $dbo->SelectFirstRow("semester_tb", "Num", "1 = 1 ORDER BY Num DESC LIMIT 1");
	if (is_array($hrec)) return $hrec['Num'];
	return 2;
}

//function to check payment local
function CheckPayLocal($regNo, $payID, $lvl = 0, $sem = 0, $sempart = 3, $RegID = 1, $SesID = 0)
{
	global $dbo;

	/*$putme = "";
	if($payID == 3){
		$putme = "p";
	}*/

	if ($lvl == 0) { //if no level suplied get the current student
		//get the studentinfo_tb prefix, by the payid in item_tb
		$pre = StudPreByPayID($payID, $RegID);
		$lvl = StudLevel($regNo, $pre);
	}

	//if session not set use the current ses
	if ($SesID == 0) {
		$Ses = CurrentSes();
		$SesID = $Ses['SesID'];
	}

	//if sempart is zero it means that the semester part is not a criteria, so far at least one payment is made it will been seen as paid
	$sempartquery = (int)$sempart != 0 ? (int)$sempart > 1 ? "(SemPart = 2 OR SemPart = 3)" : "(SemPart = {$sempart} OR SemPart = 3)" : "1 = 1"; //if sempart is 3 or 2 are financially thesame, because the two represent completion of payment,i.e are to be considered as such in payment verification
	$fullsem = SchoolHighestSemester() + 1; //the highest sem + 1 represent full session payment
	$semquery = ($sem == 0) ? " AND Sem = $fullsem" : " AND (Sem = $fullsem OR (Sem = {$sem} AND {$sempartquery}))";
	$lvl = (int)$lvl;
	$payID = (int)$payID;
	//Handling Session for Prev Payment Checking
	//****************************************
	$SesQ = "AND Ses = $SesID";
	if ($SesID < 0) { //if session is negative force checking not to consider ses
		$SesQ = "";
	}
	//***************************************
	$ProgID = GetStudentProgIDForPay($regNo);
	$sqlregNo = $dbo->SqlSave($regNo);
	$query = "SELECT * FROM payhistory_tb WHERE RegNo = '{$sqlregNo}' AND Lvl = {$lvl} AND PayID = {$payID} AND ProgID={$ProgID} {$semquery} {$SesQ} order by Sem desc, SemPart desc";
	$rst = $dbo->RunQuery($query);
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$paypol = "";
			$TopSem = 0; //the top payment 3 , 2 or 1
			$TopSemPart = 0;
			while ($rstrw = $rst[0]->fetch_array()) {
				if ($TopSem == 0) { //get the bigest payment policy
					$TopSem = (int)$rstrw['Sem'];
					$TopSemPart = (int)$rstrw['SemPart'];
				}
				if ((int)$rstrw['Sem'] == 3) {
					$paypol = "3";
					break;
				}
				$paypol .= $rstrw['Sem'] . ":";
			}
			$paypol = rtrim($paypol, ":");
			return array(1, $paypol, $payID, $lvl, $TopSem, "", 0, "", $TopSemPart);
		} else {
			return array(0, 0, $payID, $lvl, 0, "Make Payment", 6); //paid(1)NotPaid(0), Semester/PayPolicy(1=first:2=second:3=full), paymenttype(1=acceptance/2=schoolfees), Level 
		}
	} else {
		return array(0, 0, $payID, $lvl, 0, "Server Error: Local Check", 7);
	}
}

function CheckPayLocalRef($Ref, $orderdet)
{
	//return [0,"Testing"];
	global $dbo;
	if (trim($Ref) == "") return [0, 0, 0, 0, 0, "Invalid Payment Reference", 7];

	if (!isset($orderdet)) {
		//get the order details
		$orderdet = $dbo->SelectFirstRow("order_tb", "", "TransNum='" . $dbo->SqlSafe($Ref) . "'");
		if (!is_array($orderdet)) return [0, 0, 0, 0, 0, "Invalid Payment Reference", 7];
	}



	$query = "SELECT * FROM payhistory_tb WHERE TransID = '{$Ref}'";
	$rst = $dbo->RunQuery($query);
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$rst = $rst[0]->fetch_assoc();
			if ((int)$orderdet['Paid'] == 0) {
				//update order incase not updated
				$upord = $dbo->Update("order_tb", ["Paid" => 1], "ID=" . $orderdet['ID']);
			}

			//payment made
			return array(1, $rst['SemPart'], $rst['PayID'], $rst['Lvl'], $rst['Sem'], "", 0, "", $rst['SemPart']);
		} else {
			return array(0, 0, $orderdet['ItemID'], $orderdet['Lvl'], $orderdet['Sem'], "Make Payment", 6);
		}
	} else {
		return array(0, 0, $orderdet['ItemID'], $orderdet['Lvl'], $orderdet['Sem'], "Server Error: Local Check", 7);
	}
}

//function to check if paid in bank through etransact gateway
function CheckPay($regNo, $payID, $lvl = 0, $sem = 0, $sempart = 3, $RegID = 1, $SesID = 0)
{
	global $dbo;
	/*$putme = "";
	if($payID == 3){
		$putme = "p";
	}*/
	$payID = (int)$payID;

	$msg = ""; //holds the message from third party
	if ($lvl == 0) { //if no level suplied get the current student
		$pre = StudPreByPayID($payID, $RegID);
		$lvl = StudLevel($regNo, $pre);
	}

	//if ses not sent use the current ses
	if ($SesID == 0) {
		$Ses = CurrentSes();
		$SesID = $Ses['SesID'];
	}

	$sempartquery = (int)$sempart != 0 ? (int)$sempart > 1 ? "(SemPart = 2 OR SemPart = 3)" : "(SemPart = {$sempart} OR SemPart = 3)" : "1 = 1"; //if sempart is 3 or 2 are financially thesame, because the two represent completion of payment,i.e are to be considered as such in payment verification
	$semquery = ($sem == 0) ? " AND Sem = 3" : " AND (Sem = 3 OR (Sem = {$sem} AND {$sempartquery}))";
	$sqlregNo = $dbo->SqlSave($regNo);
	$lvl = (int)$lvl;
	//Handling Session for Prev Payment Checking
	//****************************************
	$SesQ = "AND Ses = $SesID";
	if ($SesID < 0) { //if session is negative force checking not to consider ses
		$SesQ = "";
	}

	$ProgID = GetStudentProgIDForPay($regNo);
	//***************************************
	//get if student place other
	$query = "SELECT * FROM order_tb WHERE RegNo = '{$sqlregNo}' AND Lvl = {$lvl} AND ItemID = {$payID} AND ProgID={$ProgID} {$semquery} {$SesQ} order by RegDate desc, Sem desc, SemPart desc";

	$rst = $dbo->RunQuery($query);
	//note - the system currently is not checking order on simester bases which will pose issue on school fee part payment - RESOLVED
	if (is_array($rst)) {

		if ($rst[1] > 0) { //st
			$det = $rst[0]->fetch_array();

			return VerifyPayFromGateway($det['TransNum'], $det);
		} else {
			return "3";	//no order placed 
		}
	} else {
		return "4";
		//return array("4",$rst); //error
	}
}

function VerifyPayFromGateway($Ref, $OrderDet, $d = "")
{
	$sch = GetSchool('PayVerifyType');
	if ($sch['PayVerifyType'] == "SHALLOW") {
		if (!isset($OrderDet)) {
			return [0, 0, 0, 0, 0, "Payment Not Made", 7];
		}
		return [0, $OrderDet["SemPart"], $OrderDet["ItemID"], $OrderDet["Lvl"], $OrderDet["Sem"], "Payment Not Made", 7];
	}
	$getinfopth = str_replace("\\", '/', __DIR__);
	global $dbo;
	$corestr = ltrim($dbo->Config['Core'], "../");
	$getinfopthroot = explode($corestr, $getinfopth);
	$root = $getinfopthroot[0];



	if (!isset($OrderDet)) { //if the order det nut supplied get it
		$OrderDet = $dbo->SelectFirstRow("order_tb", "", "TransNum='" . $dbo->SqlSafe($Ref) . "'");
		if (!is_array($OrderDet)) {
			return [0, 0, 0, 0, 0, "Invalid Payment Reference", 7];
		}
	}

	$gatewayID = $dbo->SelectFirstRow("item_tb", "", "ID=" . $OrderDet['ItemID']);
	//get the payment gateway
	if ((int)$OrderDet["PayGatewayID"] == 0) {

		$OrderDet["PayGatewayID"] = is_array($gatewayID) ? $gatewayID['PayGatewayID'] : 1;
	}


	//get the payment gateway details
	$paygtwaydet = $dbo->SelectFirstRow("thirdparty_tb", "", "ID=" . $OrderDet['PayGatewayID']);
	if (!is_array($paygtwaydet)) { //if not found
		return [0, $OrderDet["SemPart"], $OrderDet["ItemID"], $OrderDet["Lvl"], $OrderDet["Sem"], "Invalid Payment Gateway", 7];
	}

	//return array(1,$rst['SemPart'],$rst['PayID'],$rst['Lvl'],$rst['Sem'],"",0,"",$rst['SemPart']);
	//include the gateway script
	$script = trim($paygtwaydet['Script']);
	if ($script == "") return [0, $OrderDet["SemPart"], $OrderDet["ItemID"], $OrderDet["Lvl"], $OrderDet["Sem"], "Invalid Payment Gateway Script", 7];

	$scriptarray = explode("/", $script);



	//if($d != "")return [$root.$script];

	require_once $root . $corestr . "/general/Payment/Gateways/" . $scriptarray[count($scriptarray) - 1];

	//include script




	if (function_exists($paygtwaydet['QueryStatusMethod'])) {
		$gatewayparam = $paygtwaydet['USE'] == "LIVE" ? $paygtwaydet['PARAM'] : $paygtwaydet['DEMO_PARAM'];
		//return [0,$OrderDet["SemPart"],$OrderDet["ItemID"],$OrderDet["Lvl"],$OrderDet["Sem"],$paygtwaydet['QueryStatusMethod'],7];
		//remove gateway param
		unset($paygtwaydet['PARAM']);
		unset($paygtwaydet['DEMO_PARAM']);
		//make sure PayID is set
		$OrderDet['PayID'] = $OrderDet['ItemID'];
		$params = array_merge($OrderDet, $dbo->DataArray($gatewayparam), $gatewayID, $paygtwaydet, ["Ref" => $Ref]);
		$rst = call_user_func($paygtwaydet['QueryStatusMethod'], $params);
		if ($rst['Status'] == 0) return [0, $OrderDet["SemPart"], $OrderDet["ItemID"], $OrderDet["Lvl"], $OrderDet["Sem"], $rst['Message'], 7];

		//if status is paid
		//check if already exist in payhistory
		$payexist = $dbo->SelectFirstRow("payhistory_tb", "", "TransID='" . $rst['Ref'] . "'");

		if (!is_array($payexist)) {
			return MakePaidByRef($rst['Ref'], $OrderDet, ["Amt" => $OrderDet['Amt'], "Bank" => $rst['Bank'], "Branch" => $rst['Branch'], "DateTime" => $rst['DateTime']]);
			/* //$data = [];
		//if not exist insert it
		$RegNo = $OrderDet['RegNo'];
				  $sem = $OrderDet['Sem'];
				  $sempart = $OrderDet['SemPart'];
					$Lvl = $OrderDet['Lvl'];
					$dt = new DateTime($rst['DateTime']);
					$date = $dt->format("Y-m-d");
					$paytype = $OrderDet['ItemID'];
					$transaction_number = $rst['Ref'];
					$item = $OrderDet['ItemNo'];
					$Ses = $OrderDet['Ses'];
					$bank_name = $rst['Bank'];
					$amtPaid = $OrderDet['Amt'];
					$GatewayAmt = $rst['Amt'];
					$bank_branch = $rst['Branch'];
					$val_number = $transaction_number . $item;
					$brkdwn = $dbo->SqlSave($OrderDet['BrkDwn']);
					//$ses = CurrentSes();
					$sqlregNo = $dbo->SqlSave($RegNo);
					
					 //insert into pay history
				   $rstins = $dbo->RunQuery("INSERT INTO payhistory_tb(TransID, Amt, Bank, BnkBranch,itemNum,PayDate,Sem,Ses,Lvl,RegNo,PayID,validationNo,SemPart,PayBrkDn,Info,TransAmt,CollectBank,PayScope) VALUES ('".$dbo->SqlSave($transaction_number)."', ".$amtPaid.", '".$dbo->SqlSave($bank_name)."','".$dbo->SqlSave($bank_branch)."','".$dbo->SqlSave($item)."','".$dbo->SqlSave($date)."',".$sem.",".$Ses.",".$Lvl.",'".$sqlregNo."',".$dbo->SqlSave($paytype).",'".$val_number."',$sempart,'".$brkdwn."','".StudPatchDet($RegNo,$paytype)."',$GatewayAmt,'".GetCollectBank($paytype)."','".$OrderDet['PayScope']."')","hgdsgh");
				  if(is_array($rstins)){
//update the order tb (Paid field)
				  $item = $dbo->SqlSave($item);
				  $transaction_number = $dbo->SqlSave($transaction_number);
				   $rstord = $dbo->RunQuery("UPDATE order_tb SET Paid = 1 WHERE TransNum = '".trim($transaction_number)."'", "jadvskj");
				   $erro = "Internal Error: Updating Payment Order Details Failed";
				   if(is_array($rstord)){
					$autoreg = AutoRegCourses($sqlregNo,$Lvl,$sem,$Ses,$paytype);
					if($autoreg !== TRUE){ //if auto course registration failed
						$dbo->RunQuery("UPDATE order_tb SET Paid = 0 WHERE TransNum = '".trim($transaction_number)."'", "jadvskj");
						$erro = $autoreg;
					}else{
						return array(1,$sem,$paytype,$Lvl,$sem,"",0,"",$sempart);
					}
						
				   }
				   
					  //delete the inserted payment record
					  $del = $dbo->Delete("payhistory_tb","TransID = '".$dbo->SqlSave($transaction_number)."'");
					  return [0,$OrderDet["SemPart"],$OrderDet["ItemID"],$OrderDet["Lvl"],$OrderDet["Sem"],$erro,7];
				  // }
				   
				  }else{// payhistory insertion failed
					return [0,$OrderDet["SemPart"],$OrderDet["ItemID"],$OrderDet["Lvl"],$OrderDet["Sem"],"Internal Error: Adding Payment Details Failed",7];  
				  } */
		}
	} else {
		return [0, $OrderDet["SemPart"], $OrderDet["ItemID"], $OrderDet["Lvl"], $OrderDet["Sem"], "Invalid Payment Gateway Script", 7];
	}
}

// 07/10/2016 - TAG: function to check/comfirm payment from thirdparty
function VerifyPayRemote($orderNum, $rrr = false)
{
	global $dbo;
	//New 
	//get the

	//$thirdP = $dbo->Select4rmdbtbFirstRw("school_tb","PayThirdParty");
	// $cond = $rrr == true?"TransNum = '$orderNum'":"ItemNo = '$orderNum'";
	//$det = $dbo->Select4rmdbtbFirstRw("order_tb","","TransNum='$orderNum'");

	//if(!is_array($det)){return "7#No Payment Initiation";}
	$transNo = $orderNum; //rep PayeeId for Etransact / RRR - for Remita

	// $ItemNo = $det['ItemNo']; //rep - orderId for Remita
	/*  if(is_array($thirdP) && $thirdP[0] == "ETRANZACT"){
			  $etr = QueryEtransact($transNo);
			  $data = UrlToArray($etr);
			  
			  //$etr = implode("~",$data);
			  $data['BANK'] = 1; //Assume Bank Payment
			 // $data = array(); //querying etraansact disabled
			  //return $data;
			 }else{
				 $remitaid = $rrr == true?$transNo:$ItemNo;
				 $data = QueryRemita($remitaid,$rrr); //Order ID or RRR
				 $data['TRANS_AMOUNT'] = $det['Amt']; //remita dont return amt, (so we set amt to ordered amt)
				 $data['TRANS_DATE'] = date("Y-m-d");  //use order date because remiter dont return payment date
				// return $data;
				 
			 } */
	/* $data = QueryGateway($transNo);
			 //return $data;
			  $msg = isset($data['message'])?$data['message']:"";
			  
			  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 "0#".$msg ; //not yet paid in bank
				  }else if(count($data) == 0){
					 return "6#{$msg}"; //Invalid Parameter or Bad Network 
				  }else{
					 return "5#{$msg}"; //transaction failed 
				  }
				  
			  }else{
				if(isset($data['TRANS_AMOUNT'])){
					$amtPaid = (float)$data['TRANS_AMOUNT'];
					$amtOrder = (float)$det['Amt'];
					if($amtPaid < $amtOrder){
						return "1#{$msg}";
					}else{
						
				  $RegNo = $det['RegNo'];
				  $sem = $det['Sem'];
				  $sempart = $det['SemPart'];
				    $Lvl = $det['Lvl'];
					$date = $data["TRANS_DATE"];
					$paytype = $det['ItemID'];
					$transaction_number = $transNo;
					$item = $det['ItemNo'];
					$bank_name = $data["BANK_NAME"];
					$bank_branch = $data["BRANCH_NAME"];
					$val_number = $transaction_number . $item;
					$brkdwn = $dbo->SqlSave($det['BrkDwn']);
					//$ses = CurrentSes();
					$sqlregNo = $dbo->SqlSave($RegNo);
					 //insert into pay history
				   $dbo->RunQuery("INSERT INTO payhistory_tb(TransID, Amt, Bank, BnkBranch,itemNum,PayDate,Sem,Ses,Lvl,RegNo,PayID,validationNo,SemPart,PayBrkDn,Info) VALUES ('".$dbo->SqlSave($transaction_number)."', '".$amtPaid."', '".$dbo->SqlSave($bank_name)."','".$dbo->SqlSave($bank_branch)."','".$dbo->SqlSave($item)."','".$dbo->SqlSave($date)."',".$sem.",".$det['Ses'].",".$Lvl.",'".$sqlregNo."',".$dbo->SqlSave($paytype).",'".$val_number."',$sempart,'".$brkdwn."','".StudPatchDet($RegNo,$paytype)."')","hgdsgh");
				    
				  //update the order tb (Paid field)
				  $item = $dbo->SqlSave($item);
				  $transaction_number = $dbo->SqlSave($transaction_number);
				   $rst = $dbo->RunQuery("UPDATE order_tb SET Paid = 1 WHERE ItemNo = '".trim($item)."' and TransNum = '".trim($transaction_number)."'", "jadvskj");
				   //return "#";
				   return array(1,$sem,$paytype,$Lvl,$sem,"",0,"",$sempart);
					}
				}else{
				  return "2#{$msg}";	
				}
				  
			  } */
}

//function to query thirdparty payment gateway
function QueryGateway($ref)
{
	global $dbo;
	$thirdP = $dbo->Select4rmdbtbFirstRw("school_tb", "PayThirdParty,PayThirdPartyID");
	$tirdPID = $thirdP['PayThirdPartyID'];
	//get the third party details
	$thirdPDet = $dbo->Select4rmdbtbFirstRw("thirdparty_tb", "", "ID=$tirdPID LIMIT 1");
	$Use = $thirdPDet['USE'] == 'LIVE' ? "" : "DEMO_";
	$param = $thirdPDet[$Use . 'PARAM'];
	$cond = "TransNum = '$ref'";
	$det = $dbo->Select4rmdbtbFirstRw("order_tb", "", $cond);
	//include the ref to the param and PayID(ItemID)
	$param = trim($param) == "" ? "Ref=" . $ref . "&payID=" . $det['ItemID'] : $param . "&Ref=" . $ref . "&PayID=" . $det['ItemID'] . "&Amt=" . $det['Amt'];
	//return $thirdPDet['LogicName'];
	//call the Gateway Logic
	$data = call_user_func($thirdPDet['LogicName'], $param);
	return $data;
}

/* //function to confirm from etansact
function QueryEtransact($TransNum){
	global $dbo;
	
	//Etranzact
	//================================================================================
	$querys = "SELECT * FROM etranzact_tb Limit 1";
		$rst = $dbo->RunQuery($querys);
   //set POST variables
   
   if(is_array($rst)){
	   
	   $rstarr = $rst[0]->fetch_array();
	   
	   $use = (trim($rstarr['USE']) == "DEMO")?"_DEMO":"";
$url = $rstarr['POST_URL' . $use];
$fields = array(
						'TERMINAL_ID' => $rstarr['TERMINAL_ID'.$use],
						'PAYEE_ID' => urlencode($TransNum),
						'RESPONSE_URL' => ''
				);
				
$fields_string = "";
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string=rtrim($fields_string, '&');

//open connection
$ch = curl_init();
//echo $ch;
//print_r($ch);
//set the url, number of POST vars, POST data
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);
//curl_setopt_array($ch, array(CURLOPT_RETURNTRANSFER => 1));

//execute post
$rst = curl_exec($ch);
$rst = rtrim($rst,"</html>");
$rst = trim($rst);
curl_close($ch);
return urldecode($rst);
   }else{
	  return $rst;
   }
//close connection
//======================================================================================================

} */

//function to query remita
/* function QueryRemita($orderId,$rrr=false){

global $dbo;
global $MERCHANTID;
global $SERVICETYPEID;
global $APIKEY;
global $GATEWAYURL;
global $GATEWAYRRRPAYMENTURL;
global $CHECKSTATUSURL;
if(isset($MERCHANTID)){
	   if($rrr == false){
			$concatString = $orderId . $APIKEY . $MERCHANTID; //OrderNo+api_key+merchantId
			$hash = hash('sha512', $concatString);
			$url 	= $CHECKSTATUSURL . '/' . $MERCHANTID  . '/' . $orderId . '/' . $hash . '/' . 'orderstatus.reg';
	   }else{
		   $concatString = $orderId . $APIKEY . $MERCHANTID; //RRR+api_key+merchantId
			$hash = hash('sha512', $concatString);
			$url 	= $CHECKSTATUSURL . '/' . $MERCHANTID  . '/' . $orderId . '/' . $hash . '/' . 'status.reg';
	   }
		//  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);
		
		$response_code = $response['status'];
		//return $response;
		$response['URL'] = $url;
		  if (isset($response['RRR']))
			  {
			  $rrr = $response['RRR'];
			  }
		  $response_message = $response['message'];
		  $retArr = array();
		  if($response_code == '01' || $response_code == '00') { //if suceesfull
			 //$response['SUCCESS'] = 1;
			 
		  }else{
			  if($response_code == '021') { //if bank branch option and payment still pending
				  $response['BANK'] = 1; 
			  }
			  $response['SUCCESS'] = -1;
		  }
		  
		  return $response;
		}
		return array();
	
	
	
} */

// 07/10/2016 - TAG: Function to verify payment by payment id
function HasPaidByPayRef($payRef, $rrr = false)
{
	global $dbo;
	//check local first
	$rst = $dbo->Select4rmdbtbFirstRw("payhistory_tb", "", (!$rrr) ? "itemNum = '{$payRef}'" : "TransID = '{$payRef}'");
	if (is_array($rst)) { //if exist i.e paid
		return array(1, $rst['Sem'], $rst['PayID'], $rst['Lvl'], $rst['Sem'], "", 0, "", $rst['SemPart'], $rst['RegNo']);
	} else { //if not seen local
		//determine thirdparty
		return VerifyPayRemote((!$rrr) ? $rst['itemNum'] : $rst['TransID'], $rrr);
	}
}
//function to convert url string to array
function UrlToArray($str)
{
	$str = trim($str);
	$rst = array();
	if ($str != "") {
		$strarr = explode("&", $str);
		for ($a = 0; $a < count($strarr); $a++) {
			$strv = $strarr[$a];
			$stratrvallarr = explode("=", $strv);
			if (count($stratrvallarr) == 2) {
				$rst[$stratrvallarr[0]] = $stratrvallarr[1];
			}
		}
	}
	return $rst;
}

//function to get postutme result
function GetPUTMEResult($JambNo, $RegID = 1)
{
	global $dbo;
	$JambNo = $dbo->SqlSave($JambNo);
	$query = "select * from putme_result_tb where JambNo = '" . $JambNo . "' and RegID = {$RegID} limit 1";
	$rstt = false;
	$rst = $dbo->RunQuery($query);
	//return $query;
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$rstt = $rst[0]->fetch_array();
		}
	} else {
		return $rst;
	}
	return $rstt;
}


//function to get sub

function GetBasicInfo($fregno, $scope = "", $putme = "", $RegID = 1, $type = MYSQLI_BOTH)
{
	//negative $RegID means regid must be strictly the postive(absolute)
	global $dbo;
	$fregno = $dbo->SqlSave($fregno);
	$preAll = false;
	if (trim($putme) == "a") {
		$putme = "";
		$preAll = true;
	}
	$op = "<=";
	$ord = "DESC";
	if ($RegID == 0) {
		$op = ">";
		$ord = "";
	} elseif ($RegID < 0) {
		$op = "=";
		$RegID = abs($RegID);
	}
	//get basic information from database
	if ($scope == "stud") {
		$query = "(SELECT * FROM {$putme}studentinfo_tb WHERE (JambNo = '{$fregno}' OR RegNo = '{$fregno}') AND RegID {$op} {$RegID} ORDER BY RegID $ord)";
		if ($preAll) {
			$query .= " UNION (SELECT * FROM pstudentinfo_tb WHERE (JambNo = '{$fregno}' OR RegNo = '{$fregno}') AND RegID {$op} {$RegID} ORDER BY RegID $ord)";
		}
		$query .= " LIMIT 1";
	} elseif ($scope == "all") {
		$query = "(SELECT st.*, fac.*, dpt.*, pr.*, so.*, ac.*, se.*, facg.* FROM {$putme}studentinfo_tb st, fac_tb fac, facgroup_tb facg, dept_tb dpt, programme_tb pr, state_tb so, {$putme}accesscode_tb ac, session_tb se WHERE (st.JambNo = '{$fregno}' OR st.RegNo = '{$fregno}') AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND fac.GroupID=facg.FacGrpID AND st.StateId = so.StateID AND (st.JambNo = ac.JambNo OR st.RegNo = ac.JambNo) AND st.StartSes = se.SesID AND st.RegID {$op} {$RegID} ORDER BY st.RegID $ord)";
		if ($preAll) {
			$query .= " UNION (SELECT st.*, fac.*, dpt.*, pr.*, so.*, ac.*, se.*, facg.* FROM pstudentinfo_tb st, fac_tb fac, facgroup_tb facg, dept_tb dpt, programme_tb pr, state_tb so, paccesscode_tb ac, session_tb se WHERE (st.JambNo = '{$fregno}' OR st.RegNo = '{$fregno}') AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND fac.GroupID = facg.FacGrpID AND st.StateId = so.StateID AND (st.JambNo = ac.JambNo OR st.RegNo = ac.JambNo) AND st.StartSes = se.SesID AND st.RegID {$op} {$RegID} ORDER BY st.RegID $ord)";
		}
		$query .= " LIMIT 1";
	} elseif ($scope == "sch") {
		$query = "(SELECT st.*, fac.*, dpt.*, pr.*, facg.*, so.*, stu.Name as StudyName FROM {$putme}studentinfo_tb st, fac_tb fac,facgroup_tb facg, dept_tb dpt, programme_tb pr, state_tb so, study_tb stu WHERE (st.JambNo = '{$fregno}' OR st.RegNo = '{$fregno}') AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND fac.GroupID = facg.FacGrpID AND st.StateId = so.StateID AND st.StudyID = stu.ID AND st.RegID {$op} {$RegID} ORDER BY st.RegID $ord)";
		if ($preAll) {
			$query .= " UNION (SELECT st.*, fac.*, dpt.*, pr.*, facg.*, so.*, stu.Name as StudyName FROM pstudentinfo_tb st, fac_tb fac,facgroup_tb facg, dept_tb dpt, programme_tb pr, state_tb so, study_tb stu WHERE (st.JambNo = '{$fregno}' OR st.RegNo = '{$fregno}') AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND fac.GroupID = facg.FacGrpID AND st.StateId = so.StateID AND st.StudyID = stu.ID AND st.RegID {$op} {$RegID} ORDER BY st.RegID $ord)";
		}
		$query .= " LIMIT 1";
	} elseif ($scope == "sch2") {
		$query = "(SELECT st.*, fac.*, dpt.*, pr.*, facg.* FROM {$putme}studentinfo_tb st, fac_tb fac,facgroup_tb facg, dept_tb dpt, programme_tb pr WHERE (st.JambNo = '{$fregno}' OR st.RegNo = '{$fregno}') AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND fac.GroupID = facg.FacGrpID AND st.RegID >= {$RegID} ORDER BY st.RegID $ord)";
		if ($preAll) {
			$query .= " UNION (SELECT st.*, fac.*, dpt.*, pr.*, facg.* FROM pstudentinfo_tb st, fac_tb fac,facgroup_tb facg, dept_tb dpt, programme_tb pr WHERE (st.JambNo = '{$fregno}' OR st.RegNo = '{$fregno}') AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND fac.GroupID = facg.FacGrpID AND st.RegID >= {$RegID} ORDER BY st.RegID $ord)";
		}
		$query .= " LIMIT 1";
	} elseif ($scope == "ac") {
		$query = "(SELECT * FROM {$putme}accesscode_tb WHERE (JambNo = '{$fregno}' OR RegNo = '{$fregno}') AND RegID {$op} {$RegID} ORDER BY RegID $ord)";
		if ($preAll) {
			$query .= " UNION (SELECT * FROM paccesscode_tb WHERE (JambNo = '{$fregno}' OR RegNo = '{$fregno}') AND RegID {$op} {$RegID} ORDER BY RegID $ord)";
		}
		$query .= " LIMIT 1";
	} elseif ($scope == "studsch") {
		$query = "(SELECT st.*, fac.*, dpt.*, pr.*, fac.Abbr as FacAbbr, dpt.Abbr as DeptAbbr, pr.Abbr as ProgAbbr,facg.* FROM {$putme}studentinfo_tb st, fac_tb fac,facgroup_tb facg, dept_tb dpt, programme_tb pr WHERE (st.JambNo = '{$fregno}' OR st.RegNo = '{$fregno}') AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND fac.GroupID = facg.FacGrpID AND st.RegID {$op} {$RegID} ORDER BY st.RegID $ord)";
		if ($preAll) {
			$query .= " UNION (SELECT st.*, fac.*, dpt.*, pr.*, facg.* FROM pstudentinfo_tb st, fac_tb fac,facgroup_tb facg, dept_tb dpt, programme_tb pr WHERE (st.JambNo = '{$fregno}' OR st.RegNo = '{$fregno}') AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND fac.GroupID = facg.FacGrpID AND st.RegID {$op} {$RegID} ORDER BY st.RegID $ord)";
		}
		$query .= " LIMIT 1";
	} else {
		//if ($putme != "" && $putme != "a") {
			$pquery = ", st.PUTMECombID, st.SeatNo, st.VenueID, st.JmbComb";
		//} else if ($preAll) { //if combine
		//	$pquery = ", 0 as temp1, 0 as temp2, 0 as temp3"; //make the union field corresspond
		//} else {
		//	$pquery = "";
		//}
		/* Unknown column 'st.PUTMECombID' in 'field list'(SELECT st.id as StudID, st.SurName, st.FirstName, st.OtherNames, st.Gender, st.DOB, fac.FacName, fac.FacID, st.RegNo, st.JambNo, dpt.DeptName, pr.ProgName, pr.Degree as DegreeName,pr.YearOfStudy, st.ModeOfEntry, st.RegDate, st.Passport, st.StateId, st.LGA, st.JambAgg, st.Accept, st.RegLevel, st.Addrs, st.Email, st.ProgID,st.OlevelRstDetails, st.OlevelRst, st.Phone,st.BloodGroup, sd.Name as StudyName,sd.StudyHeadTitle, sd.AcceptLetter, st.StudyID, st.ClassID, st.OtherDet,st.StartSes,st.AdmSes, st.RegID, st.PUTMECombID, st.SeatNo, st.VenueID, st.JmbComb, facg.*, 'STUDENT' as StudType FROM studentinfo_tb st, fac_tb fac, dept_tb dpt, programme_tb pr, study_tb sd, facgroup_tb facg WHERE (st.JambNo = 'WOGIS/B5A/001' OR st.RegNo = 'WOGIS/B5A/001') AND 'WOGIS/B5A/001' != '' AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND fac.GroupID = facg.FacGrpID AND fac.StudyID = sd.ID AND st.RegID <= 1 ORDER BY RegID DESC) UNION (SELECT st.id as StudID, st.SurName, st.FirstName, st.OtherNames, st.Gender, st.DOB, fac.FacName, fac.FacID, st.RegNo, st.JambNo, dpt.DeptName, pr.ProgName, pr.Degree as DegreeName,pr.YearOfStudy, st.ModeOfEntry, st.RegDate, st.Passport, st.StateId, st.LGA, st.JambAgg, st.Accept, st.RegLevel, st.Addrs, st.Email, st.ProgID, st.OlevelRstDetails, st.OlevelRst, st.Phone,st.BloodGroup, sd.Name as StudyName,sd.StudyHeadTitle, sd.AcceptLetter, st.StudyID, st.ClassID, st.OtherDet,st.StartSes,0 as AdmSes, st.RegID, st.PUTMECombID, st.SeatNo, st.VenueID, st.JmbComb , facg.*, 'CANDIATE' as StudType FROM pstudentinfo_tb st, fac_tb fac, dept_tb dpt, programme_tb pr, study_tb sd, facgroup_tb facg WHERE (st.JambNo = 'WOGIS/B5A/001' OR st.RegNo = 'WOGIS/B5A/001') AND 'WOGIS/B5A/001' != '' AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND fac.GroupID = facg.FacGrpID AND fac.StudyID = sd.ID AND st.RegID <= 1 ORDER BY RegID DESC) LIMIT 1 */
		$query = "(SELECT st.id as StudID, st.SurName, st.FirstName, st.OtherNames, st.Gender, st.DOB, fac.FacName, fac.FacID, st.RegNo, st.JambNo, dpt.DeptName, pr.ProgName, pr.Degree as DegreeName,pr.YearOfStudy, st.ModeOfEntry, st.RegDate, st.Passport, st.StateId, st.LGA, st.JambAgg, st.Accept, st.RegLevel, st.Addrs, st.Email, st.ProgID,st.OlevelRstDetails, st.OlevelRst, st.Phone,st.BloodGroup, sd.Name as StudyName,sd.StudyHeadTitle, sd.AcceptLetter, st.StudyID, st.ClassID, st.OtherDet,st.StartSes,st.AdmSes, st.RegID{$pquery}, facg.*, 'STUDENT' as StudType FROM {$putme}studentinfo_tb st, fac_tb fac, dept_tb dpt, programme_tb pr, study_tb sd, facgroup_tb facg WHERE (st.JambNo = '{$fregno}' OR st.RegNo = '{$fregno}') AND '{$fregno}' != '' AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND fac.GroupID = facg.FacGrpID AND fac.StudyID = sd.ID AND st.RegID {$op} {$RegID} ORDER BY RegID $ord)";
		if ($preAll) {
			$query .= " UNION (SELECT st.id as StudID, st.SurName, st.FirstName, st.OtherNames, st.Gender, st.DOB, fac.FacName, fac.FacID, st.RegNo, st.JambNo, dpt.DeptName, pr.ProgName, pr.Degree  as DegreeName,pr.YearOfStudy, st.ModeOfEntry, st.RegDate, st.Passport, st.StateId, st.LGA, st.JambAgg, st.Accept, st.RegLevel, st.Addrs, st.Email, st.ProgID, st.OlevelRstDetails, st.OlevelRst, st.Phone,st.BloodGroup, sd.Name as StudyName,sd.StudyHeadTitle, sd.AcceptLetter, st.StudyID, st.ClassID, st.OtherDet,st.StartSes,0 as AdmSes, st.RegID{$pquery} , facg.*, 'CANDIATE' as StudType FROM pstudentinfo_tb st, fac_tb fac, dept_tb dpt, programme_tb pr, study_tb sd, facgroup_tb facg WHERE (st.JambNo = '{$fregno}' OR st.RegNo = '{$fregno}') AND '{$fregno}' != '' AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND fac.GroupID = facg.FacGrpID AND fac.StudyID = sd.ID AND st.RegID {$op} {$RegID} ORDER BY RegID $ord)";
		}
		$query .= " LIMIT 1";
	}
	//return $query;
	$rst = $dbo->RunQuery($query);

	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$rstrw = $rst[0]->fetch_array($type);
			$reg = trim($rstrw['RegNo']);
			if ($reg == "") {
				$reg = $fregno;
			}
			if ($scope == "") {
				$name = $rstrw['SurName'] . " " . $rstrw['FirstName'] . " " . $rstrw['OtherNames'];
				$gender = (strtoupper($rstrw['Gender']) == "M") ? "MALE" : "FEMALE";
				$fac = $rstrw['FacName'];
				$dept = $rstrw['DeptName'];
				$prog = $rstrw['ProgName'];
				$dt = $rstrw['RegDate'];
				$rstarr = array('StudID' => $rstrw['StudID'], 'Name' => $name, 'Gen' => $gender, 'DOB' => $rstrw['DOB'], 'Fac' => $fac, 'Dept' => $dept, 'Prog' => $prog, 'Reg' => $reg, 'Date' => $dt, 'Passport' => $rstrw['Passport'], 'StateId' => $rstrw['StateId'], 'lga' => $rstrw['LGA'], 'jamb' => $rstrw['JambAgg'], 'pay' => $rstrw['Accept'], 'RegLevel' => $rstrw['RegLevel'], 'Addr' => $rstrw['Addrs'], 'Email' => $rstrw['Email'], 'Phone' => $rstrw['Phone'], 'ProgID' => $rstrw['ProgID'], 'StudyID' => $rstrw['StudyID'], 'ModeOfEntry' => $rstrw['ModeOfEntry'], 'BloodGroup' => $rstrw['BloodGroup'], 'FacID' => $rstrw['FacID'], 'StudyName' => $rstrw['StudyName'], 'Degree' => $rstrw['Degree'], 'RegID' => $rstrw['RegID'], 'RegNo' => $rstrw['RegNo'], 'JambNo' => $rstrw['JambNo'], 'OlevelRstDetails' => $rstrw['OlevelRstDetails'], 'OlevelRst' => $rstrw['OlevelRst'], 'OtherDet' => $rstrw['OtherDet'], 'AcceptLetter' => $rstrw['AcceptLetter'], 'FacGrpID' => $rstrw['FacGrpID'], 'StudType' => $rstrw['StudType'], 'FacGrpName' => $rstrw['FacGrpName'], 'StartSes' => $rstrw['StartSes'], 'AdmSes' => $rstrw['AdmSes'], 'YearOfStudy' => $rstrw['YearOfStudy'], 'ClassID' => $rstrw['ClassID'], "StudyHeadTitle" => $rstrw['StudyHeadTitle']);
				// $rstrw['sql'] = 'dkjdkjdkjds'; 
				if ($putme == "p") {
					$rstarr['PUTMECombID'] =  $rstrw['PUTMECombID'];
					$rstarr['SeatNo'] =  $rstrw['SeatNo'];
					$rstarr['VenueID'] =  $rstrw['VenueID'];
					$rstarr['JmbComb'] =  $rstrw['JmbComb'];
				}
				return $rstarr;
			} else {
				// $rstrw['sql'] = $query; 
				return $rstrw;
			}
		} else {
			return "0";
		}
	} else {
		return $rst;
	}
}

//return the current session, which is assumed to be the last inserted session record in session_tb
function CurrentSes()
{
	global $dbo;
	$query = "SELECT * FROM session_tb WHERE Enable = 1 ORDER BY Current DESC, SesID DESC LIMIT 1";

	$rst = $dbo->RunQuery($query);
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$rstrw = $rst[0]->fetch_array();
			return $rstrw;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

//get the current ses id only
function CurrentSesID()
{
	$cs = CurrentSes();
	return $cs['SesID'];
}

function StudStartSes($regNo, $putme = "", $RegID = 1)
{
	global $dbo;
	$regNo = $dbo->SqlSave($regNo);
	$query = "SELECT StartSes FROM {$putme}studentinfo_tb WHERE (RegNo = '{$regNo}' OR JambNo = '{$regNo}') AND RegID = $RegID LIMIT 1";

	$rst = $dbo->RunQuery($query);
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$rstrw = $rst[0]->fetch_array();
			$startses = (int)$rstrw[0];
			return $startses;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

//function to get the student mode of entring
function GetMOE($regNo, $putme = "", $RegID = 1)
{
	global $dbo;
	$regNo = $dbo->SqlSave($regNo);
	$query = "SELECT ModeOfEntry FROM {$putme}studentinfo_tb WHERE (RegNo = '{$regNo}' OR JambNo = '{$regNo}') AND RegID = $RegID LIMIT 1";

	$rst = $dbo->RunQuery($query);
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$rstrw = $rst[0]->fetch_array();
			$startses = $rstrw[0];
			return $startses;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

//function to get the students department Year of study
function StudYearOfStudy($regNo, $putme = "", $RegID = 1)
{
	global $dbo;
	$regNo = $dbo->SqlSave($regNo);
	$query = "SELECT p.YearOfStudy FROM programme_tb p, {$putme}studentinfo_tb s WHERE (s.RegNo = '{$regNo}' OR s.JambNo = '{$regNo}') and s.ProgID = p.ProgID and RegID = $RegID LIMIT 1";

	$rst = $dbo->RunQuery($query);
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$rstrw = $rst[0]->fetch_array();
			$years = $rstrw[0];
			return $years;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

//function to get the students department Year of study
function YearOfStudy($ProgID)
{
	global $dbo;
	$ProgID = $dbo->SqlSave($ProgID);
	$query = "SELECT YearOfStudy FROM programme_tb WHERE ProgID = $ProgID LIMIT 1";

	$rst = $dbo->RunQuery($query);
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$rstrw = $rst[0]->fetch_array();
			$years = $rstrw[0];
			return $years;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

//get the operational level
function OperationalLevel($LevelID,$ProgID){
	$yearofSt = YearOfStudy($ProgID);
	//check if spillover
	if((int)$LevelID > (int)$yearofSt){
	 return (int)$yearofSt;
	}
	return (int)$LevelID;
}

//function to calculate the student current level
function StudLevel($regNo, $putme = "", $RegID = 1)
{
	$startses = StudStartSes($regNo, $putme, $RegID); //get the start session of the student
	$studModeofEn = GetMOE($regNo, $putme, $RegID); //get the student mode of entry
	$studModeofEn = GetMOEID($studModeofEn); //if utme 1 else 0

	if ($startses === false) return $startses;
	//if start ses is zero
	$currSes = CurrentSes();
	$currSesID = $currSes['SesID'];
	//$startses = (int)$rstrw[0];
	if ($startses < 1) { //if student has not registered use current seesion as the startsession
		$startses = (int)$currSesID;
	}
	//$startses = $startses - $studModeofEn; // calculate the startsession for direct entry student ( =1)
	//$startses = ($startses < 1)?1:$startses; //if the calculated startsession is less than 1 set start session to 1
	//$rstrw = mysql_fetch_array($rst[0]);

	$lvl = ((int)$currSesID - $startses) + $studModeofEn;
	//($lvl - $studModeofEn) + $startses = $currSesID;
	//calculate level
	$lvl = ($lvl < 1) ? 1 : $lvl;
	return "$lvl";
}

//function to calculate student level in a particular session 
function StudLevelSes($RegNo, $Ses = 0)
{
	global $dbo;
	$studD = $dbo->SelectFirstRow("studentinfo_tb", "", "RegNo='$RegNo' OR JambNo='$RegNo' LIMIT 1");
	//merge details if exist
	
	if (is_array($studD)) {
		if(isset($studD['OtherDet']) && trim($studD['OtherDet']) != ""){
			$otherdetObj = json_decode($studD['OtherDet'],true);
			if(!is_null($otherdetObj))$studD = array_merge($studD,$otherdetObj);
		}
		//check if degree
		
		$moe = $studD['ModeOfEntry'];
		$moe = GetMOEID($moe);
		$startSes = (int)$studD['StartSes'];
		if ($Ses == 0) {
			$currSes = CurrentSes();
			$Ses = $currSes['SesID'];
		}
		$lvl = ((int)$Ses - $startSes) + $moe;
		//($lvl - $studModeofEn) + $startses = $currSesID;
		//calculate level
		$lvl = ($lvl < 1) ? $moe : $lvl;
		return "$lvl";
	}
	return 1;
}

//function to calculate student level in a particular session 
function StudLevelStartSes($RegNo, $StartSes = 0)
{
	global $dbo;
	$studD = $dbo->SelectFirstRow("studentinfo_tb", "", "RegNo='$RegNo' OR JambNo='$RegNo' LIMIT 1");
	if (is_array($studD)) {
		$moe = $studD['ModeOfEntry'];
		$moe = GetMOEID($moe);
		$startSes = $StartSes == 0 ? (int)$studD['StartSes'] : $StartSes;

		$currSes = CurrentSes();
		$Ses = $currSes['SesID'];

		$lvl = ((int)$Ses - $startSes) + $moe;
		//($lvl - $studModeofEn) + $startses = $currSesID;
		//calculate level
		$lvl = ($lvl < 1) ? 1 : $lvl;
		return "$lvl";
	}
	return 1;
}

function LevelStartSes($StartSes = 0)
{
	$moe = 1;
	$startSes = $StartSes;

	$currSes = CurrentSes();
	$Ses = $currSes['SesID'];

	$lvl = ((int)$Ses - $startSes) + $moe;
	//($lvl - $studModeofEn) + $startses = $currSesID;
	//calculate level
	$lvl = ($lvl < 1) ? 1 : $lvl;
	return "$lvl";

	return 1;
}

//function to calculate student level in a particular session from course reg
function StudLevelSesSafe($RegNo, $Ses = 0)
{
	global $dbo;
	if ($Ses == 0) {
		$currSes = CurrentSes();
		$Ses = $currSes['SesID'];
	}
	//get from course reg
	global $dbo;
	$studDCR = $dbo->SelectFirstRow("coursereg_tb", "Lvl", "SesID=" . $Ses . " AND RegNo='$RegNo' ORDER BY Sem DESC LIMIT 1");
	if (is_array($studDCR)) return $studDCR['Lvl'];
	return StudLevelSes($RegNo, $Ses);
}

//function to get student level and spillover startus
function StudLevelSpill($regNo, $putme = "", $RegID = 1)
{
	$lvl = StudLevel($regNo, $putme, $RegID); // calculate students expected level
	$years = StudYearOfStudy($regNo, $putme, $RegID); //get the years of study
	$spill = $lvl - $years; //get the spillovers
	$lvl2 = ($lvl > $years) ? $years : $lvl; //reset level to number of years when spilled
	return array($lvl2, $spill, $lvl, $years);
}

//function to Get StartSes By lvel and moe
function GetStartSesByLevel($studlvl, $modeentry = 1)
{
	$lv = (int)$studlvl; //level
	$me = (int)$modeentry; //mode of entry
	$currSes = CurrentSes();
	$currSesID = (int)$currSes['SesID'];

	$startSes = $currSesID + $me - $lv;
	if ($startSes < 1 || $startSes > $currSesID) { //invalid start ses
		$startSes = $currSesID;
		//return "Invalid Level or Mode of Entry";
	}
	return $startSes;
}

function BreakDownRst($sitd, $sit)
{
	/*$sitd = @$rstrw['OlevelRstDetails'];
				$sit = @$rstrw['OlevelRst'];*/
	$sitdarr = explode("###", $sitd);
	$sitarr = explode("###", $sit);

	$sitd1 = @$sitdarr[0];
	$sitd2 = @$sitdarr[1];

	$sit1 = @$sitarr[0];
	$sit2 = @$sitarr[1];

	if (trim($sitd1) != "") {
		$sitrealdarr1 = explode("`~", $sitd1);
	} else {
		$sitrealdarr1 = array("", "", "", "");
	}
	if (trim($sitd2) != "") {
		$sitrealdarr2 = explode("`~", $sitd2);
	} else {
		$sitrealdarr2 = array("", "", "", "");
	}

	//results array
	if (trim($sit1) != "") {
		$sit1arr = explode(";", $sit1);
	} else {
		$sit1arr = array();
	}
	if (trim($sit2) != "") {
		$sit2arr = explode(";", $sit2);
	} else {
		$sit2arr = array();
	}

	return array($sitrealdarr1, $sit1arr, $sitrealdarr2, $sit2arr);
}

//function to Get payment information upon request from bank
function GetPayInfo($payeeID, $payType)
{
	global $dbo;
	$payType = $dbo->SqlSafe($payType);
	$queryPtype = "select ID, ControlTable from item_tb where ItemName = '{$payType}'"; //get the item id through the item name

	$prst = $dbo->RunQuery($queryPtype);
	if (is_array($prst)) {
		if ($prst[1] <= 0) {
			return "PayeeName=N/A~Faculty=N/A~Department=N/A~Level=N/A~ProgrammeType=N/A~Session=N/A~PayeeID=N/A~Amount=N/A~FeeStatus=N/A~Semester=N/A~PaymentType=Wrong Payment Type~MatricNumber=N/A~Email=N/A~PhoneNumber=N/A";
		}
		$itemarr = $prst[0]->fetch_array();
		$itemID = $itemarr[0];
		$controlTb = @$itemarr['ControlTable']; //get the control table of the collection using the payment item (the control table contain the record set by admin for the collection e.g the prefix
		$pref = "";

		if (trim($controlTb) != "") {
			$cond = "";
			if (trim($controlTb) == "putme") { //if general
				$cond = "where PayID=$itemID";
			}
			$prfrst = $dbo->RunQuery("select StudInfoPref from {$controlTb} $cond");
			if (is_array($prfrst)) {
				if ($prfrst[1] > 0) {
					$prefs = $prfrst[0]->fetch_array();
					$pref = $prefs[0];
				}
			}
		}
		//$putme = ((int)$itemID == 3)?"p":"";
		$payeeID = $dbo->SqlSafe($payeeID);
		$query = "SELECT st.SurName, st.FirstName, st.OtherNames, st.Phone, st.Email, fac.FacName, dpt.DeptName, pr.ProgName, ord.ItemNo, ord.TransNum, ord.ItemName, ord.Amt, ord.Currency, ord.RegNo, ord.Sem, ord.Lvl, ord.ItemID, ord.Paid, ord.RegDate, se.SesName FROM {$pref}studentinfo_tb st, order_tb ord, session_tb se, fac_tb fac, dept_tb dpt, programme_tb pr WHERE (st.JambNo = ord.RegNo OR st.RegNo = ord.RegNo) AND ord.TransNum = '{$payeeID}' AND ord.ItemName='{$payType}' AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND ord.Ses = se.SesID LIMIT 1";
		
		//return $query;
		//	exit;
		$rst = $dbo->RunQuery($query);

		if (is_array($rst)) {
			
			if ($rst[1] > 0) {
				$rstrw = $rst[0]->fetch_array();
				if(orderHasExpired($rstrw['RegDate'])){
					return "PayeeName=N/A~Faculty=N/A~Department=N/A~Level=N/A~ProgrammeType=N/A~Session=N/A~PayeeID=N/A~Amount=N/A~FeeStatus=Payment Order Expired~Semester=N/A~PaymentType=N/A~MatricNumber=N/A~Email=N/A~PhoneNumber=N/A";
				}
				$sname = trim($rstrw['SurName']) == "" ? "N/A" : $rstrw['SurName'];
				$fname = trim($rstrw['FirstName']) == "" ? "N/A" : $rstrw['FirstName'];
				$oname = trim($rstrw['OtherNames']) == "" ? "N/A" : $rstrw['OtherNames'];
				$fac = trim($rstrw['FacName']) == "" ? "N/A" : $rstrw['FacName'];
				$dept = trim($rstrw['DeptName']) == "" ? "N/A" : $rstrw['DeptName'];
				$prog = trim($rstrw['ProgName']) == "" ? "N/A" : $rstrw['ProgName'];
				$itemName = trim($rstrw['ItemName']) == "" ? "N/A" : $rstrw['ItemName'];
				$amt = trim($rstrw['Amt']) == "" ? "N/A" : $rstrw['Amt'];
				$phone = trim($rstrw['Phone']) == "" ? "N/A" : $rstrw['Phone'];
				$email = trim($rstrw['Email']) == "" ? "N/A" : $rstrw['Email']; //SesName
				$lvl = (int)$rstrw['Lvl'] * 100;
				$ses = trim($rstrw['SesName']) == "" ? "N/A" : $rstrw['SesName'];
				$status = ($rstrw['Paid'] == 1) ? "Fee has been paid" : "Fee has not been paid";
				$sem = $rstrw['Sem'];
				if ($sem == 1) {
					$sem = "FIRST";
				} else if ($sem == 2) {
					$sem = "SECOND";
				} else {
					$sem = "FIRST-SECOND";
				}
				$reg = trim($rstrw['RegNo']) == "" ? "N/A" : $rstrw['RegNo'];
				// $putme = PUTME();

				/* if(is_array($putme)){
						 $ses = SessionName($putme['Session']);
					 }*/
				// $itemName = $rstrw['ItemName'];
				return "PayeeName={$sname} {$fname} {$oname}~Faculty={$fac}~Department={$dept}~Level={$lvl}~ProgrammeType={$prog}~Session={$ses}~PayeeID={$payeeID}~Amount={$amt}~FeeStatus={$status}~Semester={$sem}~PaymentType={$itemName}~MatricNumber={$reg}~Email={$email}~PhoneNumber={$phone}";
			} else {
				//$payeeID,$payType
				//try from payee_tb
				$payeedet = $dbo->RunQuery("SELECT p.*, o.*, se.SesName FROM payee_tb p, order_tb o, session_tb se WHERE p.PayeeID=o.RegNo AND o.Ses = se.SesID AND o.TransNum = '$payeeID' AND o.ItemName='$payType' LIMIT 1");
				if (is_array($payeedet) && $payeedet[1] > 0) {
					$pdet = $payeedet[0]->fetch_array();
					if(orderHasExpired($pdet['RegDate'])){
						return "PayeeName=N/A~Faculty=N/A~Department=N/A~Level=N/A~ProgrammeType=N/A~Session=N/A~PayeeID=N/A~Amount=N/A~FeeStatus=Payment Order Expired~Semester=N/A~PaymentType=N/A~MatricNumber=N/A~Email=N/A~PhoneNumber=N/A";
					}
					$itemName = $pdet['ItemName'];
					$amt = $pdet['Amt'];
					$phone = $pdet['Descr'];
					$email = $pdet['Name']; //SesName
					$lvl = (int)$pdet['Lvl'] * 100;
					$ses = $pdet['SesName'];
					$status = ($pdet['Paid'] == 1) ? "Fee has been paid" : "Fee has not been paid";
					$sem = $pdet['Sem'];
					if ($sem == 1) {
						$sem = "FIRST";
					} else if ($sem == 2) {
						$sem = "SECOND";
					} else {
						$sem = "FIRST-SECOND";
					}
					$reg = $pdet['RegNo'];
					return "PayeeName={$pdet['Name']}~Faculty=N/A~Department=N/A~Level=N/A~ProgrammeType=N/A~Session=N/A~PayeeID={$payeeID}~Amount={$pdet['Amt']}~FeeStatus={$status}~Semester={$sem}~PaymentType={$itemName}~MatricNumber={$reg}~Email={$email}~PhoneNumber={$phone}";
				}
				return "PayeeName=N/A~Faculty=N/A~Department=N/A~Level=N/A~ProgrammeType=N/A~Session=N/A~PayeeID=Wrong Payee_ID~Amount=N/A~FeeStatus=N/A~Semester=N/A~PaymentType=Wrong Payment Type~MatricNumber=N/A~Email=N/A~PhoneNumber=N/A";
			}
		} else {
			return $rst;
		}
	} else {
		return "PayeeName=N/A~Faculty=N/A~Department=N/A~Level=N/A~ProgrammeType=N/A~Session=N/A~PayeeID=N/A~Amount=N/A~FeeStatus=N/A~Semester=N/A~PaymentType=Wrong Payment Type~MatricNumber=N/A~Email=N/A~PhoneNumber=N/A";
	}
}

function orderHasExpired($RegDate,$validity = -1){
	if($validity < 0){
			$schdet = GetSchool("OrderValidity,email,UniqueTransID");
			$validity = (int)$schdet['OrderValidity'];
	}

	$OrderDate = date_create($RegDate);
        $Now = date_create(date("Y-m-d"));
        $diff = date_diff($OrderDate, $Now);
        $days = (int)$diff->format('%R%a');
		if ($days > $validity)return true;
		return false;
}

//function to get all putme details
function PUTME($ID = 1)
{
	global $dbo;

	$rst2 = $dbo->RunQuery("select * from putme where ID <= $ID ORDER BY ID desc limit 1");
	//$subcomb = "";
	if (is_array($rst2)) {
		if ($rst2[1] > 0) {
			$subj = $rst2[0]->fetch_array();
			return $subj;
		}
	}
	return "";
}

//function to get the school registration type (Verification Type for bio data registration
function STUDREG($RegID = 1)
{
	global $dbo;
	$rst2 = $dbo->RunQuery("select * from form_tb where ID <= {$RegID} order by ID desc limit 1");
	$subcomb = "";
	if (is_array($rst2)) {
		if ($rst2[1] > 0) {
			$subj = $rst2[0]->fetch_array();
			return $subj;
		}
	}
	return "";
}

//function to Get student subjComb
function GetSubjComb($regNo, $studpre = "p", $RegID = 1)
{
	global $dbo;
	$rst = GetBasicInfo($regNo, "stud", $studpre, $RegID);
	$progID = (int)$rst['ProgID'];
	$rst2 = $dbo->RunQuery("select * from putme_subj_tb where DeptId = {$progID}");
	$subcomb = array();
	if (is_array($rst2)) {
		if ($rst2[1] > 0) {
			while ($subj = $rst2[0]->fetch_array()) {
				$sub1 = GetSubj2($subj[2]);
				$sub1 = $sub1[1];
				$sub2 = GetSubj2($subj[3]);
				$sub2 = $sub2[1];
				$sub3 = GetSubj2($subj[4]);
				$sub3 = $sub3[1];
				$sub4 = GetSubj2($subj[5]);
				$sub4 = $sub4[1];
				$key = $subj[0];
				$subcomb[$key . ""] = $sub1  . " | " . $sub2 . " | " . $sub3 . " | " . $sub4;
				//$subcomb[$subj[0]] = $subj[2]. " | ". $subj[3] . " | ". $subj[4] . " | ". $subj[5]; 
			}
		}
	}
	return $subcomb;
}

// Get subject combination by ID
function GetSubjCombID($ID)
{
	global $dbo;
	$ID = (int)$ID;
	$rst2 = $dbo->RunQuery("select * from putme_subj_tb where PutmeSubjId = {$ID}");
	$subcomb = "";
	if (is_array($rst2)) {
		if ($rst2[1] > 0) {
			$subj = $rst2[0]->fetch_array();
			$sub1 = GetSubj2($subj[2]);
			$sub1 = $sub1[1];
			$sub2 = GetSubj2($subj[3]);
			$sub2 = $sub2[1];
			$sub3 = GetSubj2($subj[4]);
			$sub3 = $sub3[1];
			$sub4 = GetSubj2($subj[5]);
			$sub4 = $sub4[1];
			$key = $subj[0];
			$subcomb = $sub1  . " | " . $sub2 . " | " . $sub3 . " | " . $sub4;
			//$subcomb[$subj[0]] = $subj[2]. " | ". $subj[3] . " | ". $subj[4] . " | ". $subj[5]; 

		}
	}
	return $subcomb;
}

//function to get subject by id
function GetSubj2($ID)
{
	global $dbo;
	$sub = "";
	$subavr = "";
	$ID = (int)$ID;
	$rst2 = $dbo->RunQuery("select * from  olvlsubj_tb where SubId = {$ID}");
	if (is_array($rst2)) {
		$subb = $rst2[0]->fetch_array();
		$sub = $subb[1];
	}

	if ($sub != "") {
		$subavr = substr($sub, 0, 3);
	}
	return array($sub, $subavr);
}

//function to get all subjects in alphabetic order
function GetSubjAll()
{
	global $dbo;
	$sub = "";
	$subavr = "";
	$subjarr = array();
	$rst2 = $dbo->RunQuery("select * from  olvlsubj_tb");
	if (is_array($rst2)) {
		while ($subb = $rst2[0]->fetch_array()) {
			$subjarr[$subb[0]] = $subb[1];
		}
	}
	return $subjarr;
}

function ResolveSeatNo($seatNo)
{
	$seatNo = $seatNo . "";
	$strlen = count($seatNo);
	$rem = 3 - $strlen;
	$zero = "";
	for ($d = 0; $d < $rem; $d++) {
		$zero .= "0";
	}
	return $zero . $seatNo;
}
//562389421357
//get a postutme venue and seat number of a student base on the department/programme
function GetVenue($RegNo, $RegID = 1)
{
	global $dbo;
	$venu = NULL;
	$RegNo = $dbo->SqlSave($RegNo);
	$progID = $dbo->RunQuery("select ProgID from pstudentinfo_tb where (JambNo = '{$RegNo}' or RegNo = '{$RegNo}') and RegID = {$RegID} limit 1");
	if (is_array($progID) && $progID[1] > 0) {
		$progIDarr = $progID[0]->fetch_array();
		$progID = $progIDarr[0];
		$totreg = TotalPutmeReg($progID, $RegID);
		$tottemp = $totreg; //hold the total  student registered for the department
		$progID = (int)$progID;
		$rst2 = $dbo->RunQuery("select * from  venue_tb where DeptID = {$progID}");
		//return $totreg;
		if (is_array($rst2) && $rst2[1] > 0) {
			//$cnt = 0;
			$lstvenue = array();
			while ($venu = $rst2[0]->fetch_array()) { //loop through all venue of the department
				if ($totreg < $venu['capacity']) {
					$venu['SeatNo'] = ResolveSeatNo($totreg + 1);
					return $venu;
				} else {
					$totreg -= $venu['capacity'];
				}
				$lstvenue = $venu;
			}
			//if all venue are field up return the last venue and increament the seat no
			$lstvenue['SeatNo'] = ResolveSeatNo($tottemp + 1);
			return $lstvenue;
			//$veb = $subb[1];
		}
	}
	return NULL;
}

function Venue($ID)
{
	global $dbo;
	$ven = "";
	$ID = (int)$ID;
	$rst2 = $dbo->RunQuery("select * from  venue_tb where venueId = {$ID}");
	if (is_array($rst2) && $rst2[1] > 0) {
		$venu = $rst2[0]->fetch_array();
		$ven = $venu['venue'];
	}
	return $ven;
}

function Venue2($ID)
{
	global $dbo;
	$ven = "";
	$ID = (int)$ID;
	$rst2 = $dbo->RunQuery("select * from  venue_tb where venueId = {$ID}");
	if (is_array($rst2) && $rst2[1] > 0) {
		$venu = $rst2[0]->fetch_array();
		$ven = $venu['campus'];
	}
	return $ven;
}

//get total post utme student that registerd in a partucular department
function TotalPutmeReg($ProgID, $RegID = 1)
{
	global $dbo;
	$ProgID = (int)$ProgID;
	$rst2 = $dbo->RunQuery("select count(*) from  pstudentinfo_tb where RegLevel = 6 and ProgID = $ProgID and RegID = " . $RegID);
	$tot = 0;
	if (is_array($rst2) && $rst2[1] > 0) {
		$totarr = $rst2[0]->fetch_array();
		$tot = $totarr[0];
	}
	return $tot;
}

//get putme date and time
function PUTMEDateTime($ProgID)
{
	global $dbo;
	if (isset($ProgID)) {
		//Select4rmdbtbFirstRw($tbs,$fields = "",$cond = "")
		$putmerst = $dbo->Select4rmdbtbFirstRw("pschedule_tb", "", "ProgID=$ProgID");
		if (is_array($putmerst)) {
			$day = $putmerst["pDateTime"];
			// $date = $putmerst["Date"];
			// $time = $putmerst["Time"];
			$dateputme = new DateTime($day);
			return $dateputme->format("d/m/y | h:m A");
		}/*else{
		  return "";
	  }*/
	}/*else{
	
	$putmerst = $dbo->RunQuery("select * from putme where ID = {$RegID}");
				$dateputmer = "";
				if(is_array($putmerst)){
					if($putmerst[1] > 0){
						$pdt = $putmerst[0]->fetch_array();
						$dateputme = new DateTime($pdt[1]);
						$dateputmer = $dateputme->format("d/m/y | h:m A");
					}
				}
				return $dateputmer;
	}*/
	return "";
}

function GetTimeSlot($ProgID, $MOE = 1, $RegID = 1)
{
	global $dbo;
	if (isset($ProgID)) {
		//Select4rmdbtbFirstRw($tbs,$fields = "",$cond = "")
		$putmerst = $dbo->Select("time_slot", "", "ProgID=$ProgID AND MOEID = $MOE ORDER BY PanelID");

		$totreg = TotalPutmeReg($ProgID, $RegID);
		//return $putmerst;
		$totcapSeen = 0; //hold the cummulative capacity
		$lastseenDet = NULL;
		if (is_array($putmerst)) {
			if ($putmerst[1] > 0) {
				while ($putmetm = $putmerst[0]->fetch_array()) {
					$totcapSeen += (int)$putmetm['Capacity']; //add to total capacity seen
					$lastseenDet = $putmetm;
					if ($totreg < $totcapSeen) {
						return $putmetm;
					}
				}
				return $lastseenDet;
			}
		}
		return NULL;
	}
}

//get state of origin by state id
function GetState($StateID)
{
	global $dbo;
	$StateID = (int)$StateID;
	$putmerst = $dbo->RunQuery("select * from state_tb where StateID = {$StateID} limit 1");
	$state = "";
	if (is_array($putmerst)) {
		if ($putmerst[1] > 0) {
			$pdt = $putmerst[0]->fetch_array();
			$state = $pdt[1];
			//$dateputmer = $dateputme->format("d/m/y | h:m A");
		}
	}
	return $state;
}

function GetSchool($fields = ["*"], $type = MYSQLI_BOTH)
{
	if (is_string($fields)) {
		$fields = explode(",", $fields);
	}
	$fields = "sc." . implode(",sc.", $fields);
	//return $fields;
	global $dbo;
	$putmerst = $dbo->RunQuery("select $fields,p.colorScheme, p.BrandName, p.BrandCompany, p.BrandLogo from school_tb sc, portal_tb p WHERE sc.ID = p.ID limit 1");
	$pdt = "";
	if (is_array($putmerst)) {
		if ($putmerst[1] > 0) {
			$pdt = $putmerst[0]->fetch_array($type);
			//$state = $pdt[1];
			//$dateputmer = $dateputme->format("d/m/y | h:m A");
		}
	}
	return $pdt;
}

function GetPortal()
{
	global $dbo;
	$putmerst = $dbo->RunQuery("select * from portal_tb limit 1");
	$pdt = "";
	if (is_array($putmerst)) {
		if ($putmerst[1] > 0) {
			$pdt = $putmerst[0]->fetch_array();
			//$state = $pdt[1];
			//$dateputmer = $dateputme->format("d/m/y | h:m A");
		}
	}
	return $pdt;
}

//function to verify payment //requires the caller page to have included the object.php, phplb.php, config.php
function Verify($regNo, $studPre = "", $payID = 3, $name = "", $verifyType = "", $RegID = 1)
{

	global $dbo;
	//get verification type bassed on the payment type(payID)
	/* if($payID == 3){ //if post-UTME
	  $putme = PUTME(); //get the putme detail
	  $verifyType = (is_array($putme) && $putme['Verify'] == "STUDENT")?"STUDENT":"NONE";
	 }elseif($payID == 4 || $payID == 1){ //application form fee or acceptance fee, meaning student is verifying upon bio data registrtion
		 $frm = STUDREG(); //get the form registration detail
		 $verifyType = $frm['Type'];
	 }*/

	//get student preloaded info ($studPre indicate the student table to use)
	//$studrecType = (is_array($putme) && $putme['Verify'] == "STUDENT")?"":"stud";
	$DB = GetBasicInfo($regNo, "", $studPre, -$RegID); //p represent target table (PUTME);

	if (is_array($DB)) { //if student record exist
		/*if($verifyType == "NONE"){ //if verification type is NONE, format the $DB paramater to suite the one of normal verification so that other code still apply
		    $DB['Name'] = $DB['SurName']." ". $DB['FirstName'] ." ". $DB['OtherNames'];
			$DB['pay'] = $DB['Accept'];
			//$DB['RegLevel'] = $DB['SurNames'];  
	  }*/

		if ($verifyType == "PU") { //if pstume result as to be verified

			//get the students putme result
			$prst = GetPUTMEResult($regNo, $RegID);
			if (is_array($prst)) {
				$aggr = (int)@$prst['Score1'] + (int)@$prst['Score2'] + (int)@$prst['Score3'] + (int)@$prst['Score4'];
				//get the students department(programme)'s putme passmark
				$passm = PUTMEPassMark($DB['ProgID']);
				if ($passm <= 0) {
					return "@@##"; //represent invalid putme passmark
					// return; 
				}
				if ($aggr < $passm) {
					return "@@@##"; //represent student score below passmark
					//return; 
				}
			} else {
				return "@##"; //represent student jamb result can not be found
				//return;
			}
		}

		return VerifyR($DB, $regNo, $payID, $verifyType, $studPre, $RegID);
	} else { //if student record not found

		if ($verifyType == "STUDENT" || $verifyType == "JN" || $verifyType == "PU") { // if verification is normal i.e STUDENT-for putme, JN- for biodata reg, PU-also biodata reg
			return "#"; //return # to ajax call to display invalid registration number
		} else { //if not normal verification

			if ($verifyType == "NONE") {
				//$printobj =   "PRegister";
				$putmes = PUTME($RegID);
				$closed  = ($putmes['Status'] == "CLOSED") ? 1 : 0;
			} else {
				//$printobj =   "FVerify";
				$putmes = STUDREG($RegID);
				$closed  = ($putmes['Status'] == "CLOSED") ? 1 : 0;
			}

			if ($name === "") { //if basic candidate information not send
				return "#"; //return invalid regno as well
				//return;
			} elseif ($name['name'] == "#") { //if name is "#" meaning the candidate try to verify for the first time, then return ## to ajax call meaning the student should be allowed to enter his/her details and verify again
				if ((int)$closed == 1) {
					return "##@";
				} else {
					//if($studPre != "p"){// if the verification is not from entrance verification, check if the student has register for entrance, then return with it other entrance details for data preload
					$DBP = GetBasicInfo($regNo, "", "a", 0); //0 RegID look for any registration done
					if (is_array($DBP)) { // student has registered for entrance
						$datstr = $dbo->DataString($DBP); //convert the student info array to a data string for ajax transfer
						return "##``" . $datstr;
					}
					//}
					return "##";
				}

				// return;
			}

			//else i.e the student sends his/her information, so it will be inserted as required
			$names = strtoupper($name['name']);
			$namearr = explode("~", $names);
			$surname = isset($namearr[0]) ? $namearr[0] : "";
			$firstname = isset($namearr[1]) ? $namearr[1] : "";
			$othername = isset($namearr[2]) ? $namearr[2] : "";
			/*$jamb = "";
		  if(isset($name['jamb'])){
		   $jamb = $name['jamb'];
		  }*/
			$ProgID = $name['dept'];
			$gender = $name['gender'];
			$study = $name['study'];
			$lvl = (int)$name['lvl'];
			$lvl = ($lvl == 0) ? 1 : $lvl;
			$moe = (int)$name['moe'] == 0 ? 1 : (int)$name['moe'];
			$admses = (int)$name['admses'] == 0 ? 0 : (int)$name['admses'];
			$currSes = CurrentSes();
			$payed = 0;
			$currSesID = $currSes['SesID'];
			$startSes = $currSesID - ($lvl - $moe);

			//Newly Added - 1/3/2018
			//@@@@@@@@@@@@@@@@@@@@@@@
			//&email="+_('nuemail').Text()+"&phone="+_('nuphone').Text()+"&jambno="+_('fujambno').Text()
			$email = $name['email'];
			$phone = $name['phone'];
			$addr = $name['addr'];
			//@@@@@@@@@@@@@@@@@@@@@@@@@

			if (isset($name['teller'])) { //if user already paid directly in bank

				$teller = $dbo->SqlSave($name['teller']);
				$recs = $dbo->Select4rmdbtbFirstRw("pay_teller_tb", "", "TellerNo='{$teller}'");
				if (is_array($recs)) {
					$regNoT = $recs['RegNo'];
					//if regno exist for the teller number
					if (trim($regNoT) != "") {
						//if regno is same with teller number regno
						if (trim($regNoT) == trim($regNo)) {
							//update student payment details
							$payed = MakePaid($regNo, 3800, 3, $currSesID, 1, 3);
						} else {
							return "#";
							// return;
						}
					} else { //if regNo is empty
						//update the pay_teller_tb to carry the regno for the teller number
						$sqlRegNo = $dbo->SqlSave($regNo);
						$payquery = "UPDATE pay_teller_tb SET RegNo = '{$sqlRegNo}' WHERE TellerNo = '{$teller}'";
						$payupd = $dbo->RunQuery($payquery, "hgdsgh");
						if (is_array($payupd)) {
							//update candidate payment status
							$payed = MakePaid($regNo, 3800, 3, $currSesID, 1, 3);
							//echo "pay_teller_tb updated"; 
						}
					}
				} else {
					return "###";
					//return;
				}
			}
			//

			if ($verifyType == "FN") {
				$gFN = trim($name['jambno']);
				//generate form number
				if ($gFN == "") {
					$gFN = mt_rand(1000000, 999999999);
					$gFN = strtoupper(substr($surname, 0, 2)) . $gFN;
					$chn = $dbo->CheckDbValue(array('JambNo' => $gFN), "{$studPre}studentinfo_tb");

					while ($chn === true) {
						$gFN = mt_rand(1000000, 999999999);
						$gFN = strtoupper(substr($surname, 0, 2)) . $gFN;
						$chn = $dbo->CheckDbValue(array('JambNo' => $gFN), "{$studPre}studentinfo_tb");
					}
				}
				$regNo = $gFN;
			}

			$query = "INSERT INTO {$studPre}studentinfo_tb(JambNo, SurName, FirstName, OtherNames,Gender, ProgID, Accept,StudyID,StartSes,ModeOfEntry,RegID,Email,Phone,Addrs) VALUES ('" . $dbo->SqlSave($regNo) . "', '" . $dbo->SqlSave($surname) . "', '" . $dbo->SqlSave($firstname) . "','" . $dbo->SqlSave($othername) . "','{$gender}',{$ProgID},{$payed},{$study},{$startSes},{$moe},{$RegID},'{$email}','{$phone}','{$addr}')";
			// echo $query;
			//exit; 

			//insert student
			$insert = $dbo->RunQuery($query, "hgdsgh");
			if (is_array($insert)) {
				$DB = GetBasicInfo($regNo, "", $studPre, -$RegID); //negative regid search with strict regid i.e must be equal to 
				// return $studPre;
				if (is_array($DB)) {
					//return json_encode($DB);
					return VerifyR($DB, $regNo, $payID, $verifyType, $studPre, $RegID);
				} else {
					//return $DB;
					return "#";
				}
			} else {
				return "#*";
			}
		}
	}
}

//function to make student paid
function MakePaid($RegNo, $amtPaid, $sem, $ses, $Lvl, $paytype)
{
	global $dbo;
	$date = date("Y-m-d");
	$qr = "INSERT INTO payhistory_tb(Amt,PayDate,Sem,Ses,Lvl,RegNo,PayID,Info,TransAmt) VALUES ('" . $amtPaid . "','" . $date . "'," . $sem . "," . $ses . "," . $Lvl . ",'" . $RegNo . "'," . $paytype . ",'" . StudPatchDet($RegNo, $paytype, $Lvl) . "',$amtPaid)";
	$dd = $dbo->RunQuery($qr, "hgdsgh");
	if (is_array($dd)) {
		return 1;
	} else {
		return 0;
	}
	/* echo $qr;
	exit;*/
	//check for acceptance or postUTME payment
	/* $putme = "";
					  if($paytype == 3){
						  $putme = "p";
					  }
				  if($paytype == 1 || $paytype == 3){
					 
					  //update the student accept field in studentent info_tb;
					  // $rst = $dbo->RunQuery("UPDATE {$putme}studentinfo_tb SET Accept = 1 WHERE RegNo = '".$RegNo."' OR JambNo = '".$RegNo."'", "a");
					   //return true;
				  }*/
}

//function to perform verification proper
function VerifyR($DB, $regNo, $payID, $verifyType, $pre = "p", $RegID = 1)
{
	global $curtitcolorind;
	global $phpf;
	global $dbo;
	$curtitcolorind = 3;
	$rtn = GroupBoxTitle_r("Candidate Details");
	$acceptletter = "";
	//$pre = StudPreByPayID($payID);
	if ($verifyType == "STUDENT" || $verifyType == "NONE") { //Entrance
		$printobj =   "PRegister";
		$putme = PUTME($RegID);
		$closed  = ($putme['Status'] == "CLOSED") ? 1 : 0;
		$regType = $putme['PayReg'];
	} else { //Bio Data
		$printobj =   "FVerify";
		$putme = STUDREG($RegID);
		$closed  = ($putme['Status'] == "CLOSED") ? 1 : 0;
		$regType = $putme['PayReg'];
		if ($DB['AcceptLetter'] == 'TRUE' || (int)$DB['AcceptLetter'] == 1) {
			$reged = str_replace(array('/', '\\'), "_", $regNo);
			$acceptletter =  "<strong style=\"color:#578404;\">ACCEPTED</strong><a style=\"color:#578404;float:right\" href=\"javascript:void\" onclick=\"PDFPrinter.Print('Admin/Slip.php','folder=AcceptLetter&RegNo={$regNo}&RegID={$RegID}&paper=A4&orientation=P','Acceptance_Letter_{$reged}')\" title=\"Print Acceptance Letter\" id=\"pracceptslip\" > <i class=\"fa fa-print\" style=\"color:#333; font-size:1.5em\" > </i> </a>";
		}
		//root+"Admin/Slip.php","folder=Payment&"+res+"&paper=A4&orientation=P&MT=4&MB=30"
	}

	//check if payment is to be made
	if ($regType != "REG") {
		//Check candidate payment status
		//if((int)$DB['pay'] == 0){ //if not pay
		//use the third party/local payment checker
		$DB['pay'] = 0;
		//$paystatus = HasPaid($regNo,$payID,1);
		$paystatus = HasPaid($regNo, $payID, 1, 1, 3, 1, -1);
		//AKSCOE
		//$paystatus = HasPaid($regNo,$payID,1,3,0,1,-1); //sempart is 0, meaning if student has paid anything for the sem
		//AKSCOE

		// echo implode(",",$paystatus);
		//return "hhhh";
		//return implode(" ... ",$paystatus);
		$paydet = GetBy("ID", $payID, "item_tb"); //get the payment details
		$itemnm = (is_array($paydet)) ? "<strong>" . strtoupper($paydet['ItemName']) . "</strong>" : "";
		if ((int)$paydet['Currency'] > 0) {
			$cur = $dbo->SelectFirstRow("currency_tb", "", "ID=" . $paydet['Currency']);
			$paydet['Currency'] = is_array($cur) ? $cur['Name'] : $paydet['Currency'];
		}

		//get order details
		$orderdet = $dbo->SelectFirstRow("order_tb", "ItemNo", "RegNo = '$regNo' and  ItemID='$payID' and Sem = 3 and Lvl = 1 ");

		if ($paystatus[0] == 0) { //if not paid 
			//$payfunc = ($closed == 1)?"MessageBox.ShowText('REGISTRATION CLOSED','')":"MessageBox.Show('Admin/Payment/mesPayOption.php?RegNo={$regNo}&PayId={$payID}&Sem=3&pre={$pre}&lvl=1&RegID={$RegID}',null,'',null,'Payment Option')";
			$payfunc = ($closed == 1) ? "MessageBox.ShowText('REGISTRATION CLOSED','')" : "NewPay.InitPay.Start({RegNo:'$regNo',PayID:$payID,Sem:3,Lvl:1,Loadlvl:1,SemPart:3,RegID:$RegID,Amt:''})";
			$pay =  "<a style=\"\" class=\"linkbtn errbtn\" href=\"javascript:void\" onclick=\"{$payfunc}\"><i class=\"fa fa-exclamation-triangle\"></i> #" . $paystatus[6] . " <strong>NOT PAID</strong> - Click to Make Payment</a>";
			if (!is_array($orderdet)) {
				$anal = PaymentBreakDown($paydet['PayBrkDn'], 1, 3, $DB, 3);
				if (!is_array($anal)) {
					$payfunc = "MessageBox.ShowText('PAYMENT ITEM NOT FOUND','')";
				}
				$pamt = $anal[1] . " " . strtoupper($paydet['Currency']);
			} else {
				$pamt = number_format($orderdet['Amt'], 2) . " " . strtoupper($paydet['Currency']);
			}
		} else { //paid
			/*ID 	ItemNo 	TransNum 	ItemName 	ItemDescr 	Amt 	Currency 	RegNo 	Sem 	Lvl 	ItemID 	Paid 	RegDate 	Ses*/

			if (is_array($orderdet)) {
				$orderNo = $orderdet["ItemNo"];
				//Pay.Printer.Preview('Payment Slip','Admin/Payment/Bank/Slip.php?ItemNo={$orderNo}',function(){_('prpayslip').StopLoadingsm();});
				//Pay.Printer.Print('Admin/Payment/Bank/Slip.php?ItemNo={$orderNo}',function(){_('prpayslip').StopLoadingsm();});
				$payfunc = "_('prpayslip').StartLoadingsm();Pay.PrintPay('ItemNo={$orderNo}&RegID={$RegID}',function(){_('prpayslip').StopLoadingsm();});";
				$pamt = number_format($orderdet['Amt'], 2) . " " . strtoupper($paydet['Currency']);
			} else {
				$payfunc = "MessageBox.Hint('PAYMENT ORDER DETAILS NOT FOUND')";
				$pamt = "UNKNOWN";
			}
			$pay = "<strong style=\"color:#578404;\">PAID</strong><a style=\"color:#578404;float:right\" href=\"javascript:void\" onclick=\"{$payfunc}\" title=\"Print Payment Receipt\" id=\"prpayslip\" > <i class=\"fa fa-print\" style=\"color:#333; font-size:1.5em\" > </i> </a>";
			$DB['pay'] = 1; //set payment to paid
		}


		/*}else{
		  $payfunc = "Pay.BankPay(null,'{$regNo}',{$payID},3,'{$pre}','1',this)";
		$pay = "<strong style=\"color:#578404;\">PAID</strong><a style=\"color:#578404;float:right\" href=\"javascript:\" onclick=\"{$payfunc}\" title=\"Print Payment Receipt\"> <img src=\"Resource/Images/printsm.png\" alt=\"Print\" /> </a>" ;
		  
	  }*/
	}

	//$regTitle = ($verifyType == "FN")?"FORM NUMBER":"REGISTRATION NUMBER";
	$regTitle = "REGISTRATION NUMBER";

	// $printobj = ($verifyType == "STUDENT" || $verifyType == "NONE")?"PRegister":"FVerify";
	$DB['pay'] = ($regType != "REG") ? $DB['pay'] : "-1";
	$pay .= "<input type=\"hidden\" id=\"payStatus\" name=\"payStatus\" value=\"" . $DB['pay'] . "\" />";

	//check if registration is allowed 
	if ($regType != "PAY") {
		$regLvl = ((int)$DB['RegLevel'] < 6) ? "<span style=\"color:#CC3300\"  ><strong><i class=\"fa fa-exclamation-triangle\"></i> NOT REGISTERED</strong></span>" : "<strong style=\"color:#578404;\">REGISTERED</strong><a href=\"javascript:void\" class=\"round-btn forebgcolor\" onclick=\"{$printobj}.PrintSlip('{$regNo}',null,null,'{$RegID}')\" id=\"reprSlip\" style=\"float:right\" title=\"Print Registration Slip\"><i class=\"fa fa-print\" style=\"\" > </i> </a>";
	}
	//$regNo = $phpf->SqlSave($regNo);
	$DB['RegLevel'] = ($regType != "PAY") ? $DB['RegLevel'] : "-1";
	$regLvl .= "<input type=\"hidden\" id=\"regStatus\" name=\"regStatus\" value=\"" . $DB['RegLevel'] . "\" /><input type=\"hidden\" id=\"closeStatus\" name=\"closeStatus\" value=\"" . $closed . "\" />";
	$arrval  = array(
		array("[NAME]", "<strong>" . strtoupper($DB['Name']) . "</strong><input type=\"hidden\" id=\"fName\" name=\"fName\" value=\"" . $DB['Name'] . "\" />"),
		array("[{$regTitle}]", "<strong>" . strtoupper($regNo) . "</strong><input type=\"hidden\" id=\"fRegNo\" name=\"fRegNo\" value=\"{$regNo}\" />")
	);

	//get the analysis

	//

	$arrval[] =  array("[GENDER]", $DB['Gen']);
	$arrval[] = array("[SCHOOL TYPE]", strtoupper($DB['StudyName']));
	$arrval[] = array("[FACULTY/SCHOOL]", strtoupper($DB['Fac']));
	$arrval[] = array("[DEPARTMENT]", strtoupper($DB['Dept']));
	$arrval[] = array("[PROGRAMME]", strtoupper($DB['Prog']));
	if ($verifyType == "STUDENT") {
		if ((int)$DB['StateId'] > 0) {
			$arrval[] = array("[STATE]", GetState($DB['StateId']));
		}
		if ((int)$DB['lga'] > 0) {
			$arrval[] = array("[LOCAL GOVT. AREA]", strtoupper(GetLGA($DB['lga'])));
		}
	}
	if ($verifyType != "FN" && $verifyType != "RN") {
		if ((int)$DB['jamb'] > 0) {
			$arrval[] = array("[JAMB AGGREGATE]", $DB['jamb']);
		}
	}

	if ($verifyType == "PU") {
		$prst = GetPUTMEResult($regNo, $RegID);
		if (is_array($prst)) {
			$aggr = (int)@$prst['Score1'] + (int)@$prst['Score2'] + (int)@$prst['Score3'] + (int)@$prst['Score4'];
			$arrval[] = array("[PUTME AGGREGATE]", $aggr);
		}
	}

	// }
	if ($regType != "PAY") { //if registration is enabled
		$arrval[] = array("[REGISTRATION STATUS]", $regLvl);
		if ($printobj == "FVerify") { //determine if not putme registration
			/*$scr = CheckScreen($regNo,$putme['StudInfoPref'],$RegID);
			if($scr !== false){
				$screen = $putme['Screening'];
				if($screen == 'TRUE'){
				$scrr = $scr === NULL?"<strong class=\"errorColor\">FAILED</strong><input type=\"hidden\" id=\"scrnval\" name=\"scrnval\" value=\"0\" />":"<strong class=\"successColor\">PASSED</strong><input type=\"hidden\" id=\"scrnval\" name=\"scrnval\" value=\"1\" />";
				$arrval[] = array("[SCREENING]",$scrr);
				}
			}*/
		}
	} else { //

		echo $regLvl;
	}
	if ($regType != "REG") {
		if ($itemnm != "") {
			$arrval[] = array("[PAYMENT TYPE]", $itemnm);
		}
		$arrval[] = array("[AMOUNT]", $pamt);
		$arrval[] = array("[PAYMENT STATUS]", $pay);
		if ((int)$DB['pay'] == 1 && trim($acceptletter) != "") { //if payment made and acceptance leter printing enabled
			//display the admission status
			$arrval[] = array("[ADMISSION STATUS]", $acceptletter);
		}
	} else {
		//if direct registration without payment display admission letter if enabled
		if (trim($acceptletter) != "") {
			$arrval[] = array("[ADMISSION STATUS]", $acceptletter);
		}
		echo $pay;
	}
	$rtn .= Table_r($arrval, "", "100%*550px");
	return $rtn;
}

function FormAC()
{
	$charset = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
	$ac = "";
	$s = 1;
	while ($s < 9) {
		$rand = mt_rand(0, 25);
		$ac .= $charset[$rand];
		$s++;
	}
	return $ac;
}

//function to create list of faculties for Filter combobox
function GetFacFilter()
{
	global $dbo;
	$facarr = array(strtoupper("0#Faculty/School"));
	$putmerst = $dbo->RunQuery("select * from fac_tb");
	//$pdt = "";
	if (is_array($putmerst)) {
		if ($putmerst[1] > 0) {
			while ($pdt = $putmerst[0]->fetch_array()) {
				$facarr[] = $pdt['FacID'] . "#" . strtoupper($pdt['FacName']);
			}
			//$state = $pdt[1];
			//$dateputmer = $dateputme->format("d/m/y | h:m A");
		}
	}
	return $facarr;
}

//function to get the studentinfo_tb prefix letter by payment type (ID)
function StudPreByPayID($payID, $RegID = 1)
{
	global $dbo;
	$payID = (int)$payID;
	$ratt = $dbo->RunQuery("select ControlTable from item_tb where ID = " . $payID);
	if (is_array($ratt)) {
		if ($ratt[1] > 0) {
			$pre = $ratt[0]->fetch_array();
			$tb = $pre[0];
			$ratt2 = $dbo->RunQuery("select StudInfoPref from {$tb} where ID=$RegID LIMIT 1");
			///return $ratt2;
			$pre2 = $ratt2[0]->fetch_array();
			return @$pre2[0];
		}
	}
	return "";
}

//function to get departmetal putme passmark
function PUTMEPassMark($ProgID)
{
	global $dbo;
	$ProgID = (int)$ProgID;
	$ratt = $dbo->RunQuery("select putmeagr from programme_tb where ProgID = " . $ProgID);
	if (is_array($ratt)) {
		if ($ratt[1] > 0) {
			$pre = $ratt[0]->fetch_array();
			return (int)$pre[0];
		}
	}
}

//function to get record by id
function GetBy($Key, $value, $table)
{
	global $dbo;
	$pre = array();
	$value = $dbo->SqlSave($value);
	$q = "select * from {$table} where {$Key} = '" . $value . "'";
	$ratt = $dbo->RunQuery($q);
	if (is_array($ratt)) {
		if ($ratt[1] > 0) {
			$pre = $ratt[0]->fetch_array();
			return $pre;
		}
	}
	return $pre;
}



//function to get course settings details
function COURSE()
{
	global $dbo;
	$rst2 = $dbo->RunQuery("select * from coursecontrol_tb");
	//$subcomb = "";
	if (is_array($rst2)) {
		if ($rst2[1] > 0) {
			$subj = $rst2[0]->fetch_array();
			return $subj;
		}
	}
	return "";
}

//function to get school type details by ID
function SchoolType($ID)
{
	global $dbo;
	$ID = (int)$ID;
	$rst2 = $dbo->RunQuery("select * from schooltype_tb where ID = {$ID}");
	//$subcomb = "";
	if (is_array($rst2)) {
		if ($rst2[1] > 0) {
			$subj = $rst2[0]->fetch_array();
			return $subj;
		}
	}
	return "";
}

//function to load payment analysis into table
function PayAnalysis($payID, $lvl, $paypol, $RegNo, $loadlvl = 0, $sempart = 3, $RegID = 1, $pretable = [])
{
	global $dbo;
	global $curtitcolorind;
	$paydet = GetPaymentItem($payID); //get the payment details based on payID
	if ($paydet != NULL) { //if payment details is found
		//get all student info
		$StudInfo = GetBasicInfo($RegNo, "all", "", $RegID);
		$loadlvl = $loadlvl > 0 ? $loadlvl : $lvl; //set the level to be used to load analysis
		$anal = PaymentBreakDown($paydet['PayBrkDn'], $loadlvl, $paypol, $StudInfo, $sempart);

		if (is_array($anal)) {
			$ramt = $anal[0];
			$brdwn = $anal[2];
			$tot = $anal[1];
			$curtitcolorind = 2;
			GroupBoxTitle("Payment Analysis");
			//PayAnalysis(2,1,3);
			$arrval = $pretable;
			$itemarr = explode("***", $brdwn);
			if (count($itemarr) > 0) {
				$arrval[] = array(array("class=header"), array("ITEM", "AMOUNT"));
				for ($sd = 0; $sd < count($itemarr); $sd++) {
					$item = $itemarr[$sd];
					$nameAmt = explode("~", $item);
					$name = strtoupper($nameAmt[0]);
					$amt = $nameAmt[1];
					$arrval[] =  array("[{$name}]", "{$amt}");
				}

				//Table($arrval,"","100%*370px");	
				TableNew($arrval, "style=width:100%,autoheightdiff=257px");

				$arrval2[] = array("<strong>[TOTAL]</strong>", "<strong>{$tot}</strong>");
				Table($arrval2, "", "100%*50px");
				//ButtonImg("money","Pay","id=paybtn,title=Pay Now,onclick=".SafeData("MessageBox.Show('Admin/Payment/mesPayOption.php?RegNo={$RegNo}&PayId={$payID}&Sem={$paypol}&pre=&lvl={$lvl}&loadlvl={$loadlvl}&sempart={$sempart}&RegID={$RegID}',null,'',null,'Payment Option')").",style=margin-top:10px");//	
				ButtonImg("money", "Pay", "id=paybtn,title=Pay Now,onclick=" . SafeData("NewPay.InitPay.Start({RegNo:'$RegNo',PayID:$payID,Sem:$paypol,Lvl:$lvl,Loadlvl:$loadlvl,SemPart:$sempart,RegID:$RegID,Amt:'$ramt'},this)") . ",style=margin-top:10px"); //
				echo '<div id="paybtnbrkdwn" style="display:none">' . $brdwn . '</div>';
			} else {
				echo "##"; //no payment details found
			}
			/* $arrval[] =  array("[TUITION FEE]","35,000");
			$arrval[] = array("[DEVELOPMENTAL FEE]","10,000");
			$arrval[] = array("[ID CARD]","2000");
			$arrval[] = array("[EXAMINATION]","3000");
	        $arrval[] = array("[TRANSACTION CHARGE]","500");*/
		} else {
			//echo "###"; //invalid payment analysis
			echo $anal;
		}
	} else {
		echo "####"; //server error canot get the payment item details from database
	}
}



//function to load courses for registration
function LoadCoursesReg($regNo, $lvl, $sem, $payID, $allpay = false)
{
	/*echo "aaa";
	return;*/
	global $dbo;
	global $curtitcolorind;
	$schpaydet = SchoolPayDet();
	$schpayShare = !is_array($schpaydet) ? 'HALF' : $schpaydet['PartPayShare'];
	$sqlregNo = $dbo->SqlSave($regNo);
	//
	//get student session from course reg
	$studses = $schpaydet['SessionCheck'] == "CURRENT" ? 0 : -1;
	/* $check = $dbo->SelectFirstRow("coursereg_tb","","RegNo = '{$sqlregNo}' and Lvl = {$lvl} and Sem = {$sem}");
	if(is_array($check)){
		$studses = (int)$check['SesID'];
	} */
	//HasPaid($regNo,$payID,$lvl = 0,$sem = 0,$sempart=3,$RegID=1,$SesID=0)

	$paid = HasPaid($regNo, $payID, $lvl, $sem, 0, 1, $studses); //sempart is 0, meaning if student has paid anything for the sem
	//exit(json_encode($paid));
	//AKSCOE
	//$paid = HasPaid($regNo,$payID,$lvl,$sem,0,1,-1); //sempart is 0, meaning if student has paid anything for the sem
	//AKSCOE
	//RegNo,payID,Paypol,Lvl
	if ($paid[0] == 0) {
		if ($allpay == true) {
		}
		//Text("style=color:red;font-size:1.4em,name=courselnk","PAYMENT NOT MADE");
		/* Auto Sem Operation :: 25/07/2017*/
		//*****************************************
		$AutoSem = !is_array($schpaydet) ? 'TRUE' : $schpaydet['AutoSem'];
		if ($AutoSem == 'ALL') {
			GroupBoxTitle("payment not made");
			//$paypols = $paid[1];

			echo "<div name=\"courselnk\">";
			if ($schpayShare == 'HALF') {
				InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,1\,$lvl),text=<i class\=\"fa fa-star-half-o\"></i> FIRST PAYMENT,error=true,style=margin-right:20px");
				InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,2\,$lvl),text=<i class\=\"fa fa-star-half-o\"></i> SECOND PAYMENT,error=true,style=margin-right:20px");
				InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,3\,$lvl),text=<i class\=\"fa fa-star\"></i> FULL PAYMENT");
			} else {
				InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,'1_1'\,$lvl),text=<i class\=\"fa fa-star-half-o\"></i> FIRST PAYMENT(PART),error=true,style=margin:10px");
				InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,'1_2'\,$lvl),text=<i class\=\"fa fa-star\"></i> FIRST PAYMENT(COMPLETE),style=margin:10px");
				InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,'1_3'\,$lvl),text=<i class\=\"fa fa-star-half-o\"></i> FIRST PAYMENT(FULL),style=margin:10px");
				InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,'2_1'\,$lvl),text=<i class\=\"fa fa-star-half-o\"></i> SECOND PAYMENT(PART),error=true,style=margin:10px");
				InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,'2_2'\,$lvl),text=<i class\=\"fa fa-star-half-o\"></i> SECOND PAYMENT(COMPLETE),error=true,style=margin:10px");
				InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,'2_3'\,$lvl),text=<i class\=\"fa fa-star\"></i> SECOND PAYMENT(FULL),style=margin:10px");
				InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,3\,$lvl),text=<i class\=\"fa fa-star\"></i> FULL PAYMENT,style=margin:10px");
			}
			echo "</div>";
			Box("style=display:none;color:#333;width:auto;height:auto;font-size:1.1em,id=cpayloading,class=");
			Logo("cog fa-spin");
			echo " &nbsp;Loading Payment Analysis. Please wait";
			_Box();
			return;
		} elseif ($AutoSem == 'FALSE') { //if system must use the current sem
			//get the current Semester
			$CurSemArr = GetCurrentSem();
			$CurSem = $CurSemArr[0];
			if ((int)$CurSem != (int)$sem) {
				$curtitcolorind = 1;
				GroupBoxTitle("INVALID SELECTION");
				/* Box("style=color:red;font-weight:bold;font-size:1.3em");
		  Logo("exclamation");
		  echo " Invalid Semester Selected";
		  _Box(); */
				Alert("Invalid Semester Selected");
				return;
			}
		}
		$prevcheck = !is_array($schpaydet) ? 'FALSE' : $schpaydet['PrevCheck'];
		//****************************************************
		$curtitcolorind = 1;
		GroupBoxTitle("payment not made");
		//$paypols = $paid[1];

		echo "<div name=\"courselnk\">";
		if ((int)$sem == 2) {
			//check if 1st sem paid
			//$paidfirst = HasPaid($regNo,$payID,$lvl,1,0,1,-1);
			$paidfirst = HasPaid($regNo, $payID, $lvl, 1, 0);
			if ($paidfirst[0] == 1) { //if payed first payment
				//echo "<li>";
				//(1,$paypol,$payID,$lvl,$TopSem,"",0,"",$TopSemPart)
				$TopSem = $paidfirst[4];
				$TopSemPart = (int)$paidfirst[8];

				if ($schpayShare == 'HALF') {
					InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,2\,$lvl),text=<i class\=\"fa fa-star-half-o\"></i> SECOND PAYMENT");
				} else { //else QUATER
					if ($TopSemPart < 2) { //if only first part is paid, display to complete part first
						InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,'1_2'\,$lvl),text=<i class\=\"fa fa-star\"></i> FIRST PAYMENT(COMPLETE)");
						//echo json_encode($paidfirst);
					} else { //if complete first payment, display second payments options
						InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,'2_1'\,$lvl),text=<i class\=\"fa fa-star-half-o\"></i> SECOND PAYMENT(PART),error=true,style=margin-right:20px");
						InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,'2_3'\,$lvl),text=<i class\=\"fa fa-star\"></i> SECOND PAYMENT(FULL)");
					}
				}

				//HLink("javascript:Course.LoadPay('{$regNo}',$payID,$sem,$lvl)","Complete your Payment","style=font-size:1.1em;text-decoration:;color:inherit");
				//echo "</li>";
			} else { //make full payment
				//echo "<li>";
				if ($schpayShare != 'HALF') { //quater payment devision

				}
				/* Check Prevpayment enabled :: 25/07/2017*/
				//*****************************************
				if ($prevcheck == 'TRUE') {
					/* Box("style=color:red;font-size:1.3em");
				   Logo("exclamation");
				   echo " PREVIOUS PAYMENT NOT MADE, ADVISE TO SUSPEND STUDY";
				   _Box(); */
					Alert("PREVIOUS PAYMENT NOT MADE, ADVISE TO SUSPEND STUDY");
				} else {
					InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,3\,$lvl),text=<i class\=\"fa fa-star\"></i> FULL PAYMENT,style=margin:10px");
				}
				//****************************************************
				//HLink("javascript:Course.LoadPay('{$regNo}',$payID,3,$lvl)","Make Full Payment","style=font-size:1.1em;text-decoration:;color:inherit");
				//echo "</li>";
			}
		} else { //Sem is 1


			if ($schpayShare == 'HALF') {
				InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,1\,$lvl),text=<i class\=\"fa fa-star-half-o\"></i> FIRST PAYMENT,error=true,style=margin-right:20px");
				InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,3\,$lvl),text=<i class\=\"fa fa-star\"></i> FULL PAYMENT,style=margin:10px");
			} else {
				//check if student has complete second payment 100 level, if level is more than 100 ***********
				$prevlvl = (int)$lvl - 1;
				$paidprevlev = array(0);
				$prevlvlseen = false;
				if ($prevlvl > 0) {
					$paidprevlev = HasPaid($regNo, $payID, $prevlvl, 2, 0);
					$prevlvlseen = true;
				}
				if (!$prevlvlseen || ($paidprevlev[0] == 1 && (int)$paidprevlev[8] > 2)) { //if no prev level found or prevpayment made
					InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,'1_1'\,$lvl),text=<i class\=\"fa fa-star-half-o\"></i> FIRST PAYMENT(PART),error=true,style=margin-bottom:10px");
					InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,'1_3'\,$lvl),text=<i class\=\"fa fa-star-half-o\"></i> FIRST PAYMENT(FULL),style=margin-left:20px;margin-bottom:10px");
					InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,3\,$lvl),text=<i class\=\"fa fa-star\"></i> FULL PAYMENT,style=margin:10px");
				} elseif ($prevlvlseen && ($paidprevlev[0] == 1 && (int)$paidprevlev[8] == 1)) {
					InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,'2_2'\,$prevlvl),text=<i class\=\"fa fa-star-half-o\"></i> SECOND PAYMENT(COMPLETE),error=true");
				} else {
					InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,'1_1'\,$lvl),text=<i class\=\"fa fa-star-half-o\"></i> FIRST PAYMENT(PART),error=true,style=margin-bottom:10px");
					InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,'1_3'\,$lvl),text=<i class\=\"fa fa-star-half-o\"></i> FIRST PAYMENT(FULL),style=margin-left:20px;margin-bottom:10px");
					InlineBtn("onclick=Course.LoadPay('{$regNo}'\,$payID\,3\,$lvl),text=<i class\=\"fa fa-star\"></i> FULL PAYMENT,style=margin:10px");
				}
			}
			//HLink("javascript:Course.LoadPay('{$regNo}',$payID,1,$lvl)","Make Part Payment","style=font-size:1.1em;text-decoration:;color:inherit");
			//echo "</li>";-half
		}
		echo "</div>";
		Box("style=display:none;color:#333;width:auto;height:auto;font-size:1.1em,id=cpayloading,class=");
		Logo("cog fa-spin");
		echo " &nbsp;Loading Payment Analysis. Please wait";
		_Box();
		//echo '<i  style="position:;z-index:1;margin-left:10px;display:none" id="cpayloading" class="fa fa-cog fa-spin" ></i>';
		return;
	}

	$yearofSt = StudYearOfStudy($regNo, "");
	$clvl = (($lvl - $yearofSt) > 0) ? $yearofSt : $lvl;
	$studinfo = GetBasicInfo($regNo, "stud");
	$progID = (int)$studinfo["ProgID"];

	$scourses = GetStudCourses($regNo, $clvl, $sem, false, $progID);

	if (is_array($scourses)) {
		//if($scourses[1] > 0){ //semester courses exist
		$curtitcolorind = 1;


		$presel = "";

		$lvl = (int)$lvl;
		$sem = (int)$sem;
		$curcourses = "";
		$OutsPreSel = ""; //the preselected string for outstanding courses
		$ReptPreSel = ""; //the preselected string for repeat courses
		$OutstCourses = null; //the Outstanding courses database rows if exist
		$RepeatCourses = null; //the repeat courses database rows if exist
		$genpresel = "";
		// $check = $dbo->RunQuery("select CoursesID from coursereg_tb where RegNo = '{$sqlregNo}' and Lvl = {$lvl} and Sem = {$sem}");


		if (is_array($check)) {
			$genpresel = $check["CoursesID"];

			$genpresel = ResolveRegCourses($genpresel);
			// echo $genpresel;
			/*if($check[1] > 0){
			  $presel =  $check[0]->fetch_array();
			  $presel = $presel["CoursesID"];
			  $presel = ResolveRegCourses($presel);
		   }*/
		}
		$totchdb = -1;
		$probyear = false; //if student in his probation year
		$courseCntr = COURSE();

		if ($courseCntr['CheckProb'] == 'TRUE' || $courseCntr['UnRegCourses'] == 'TRUE' || $courseCntr['ReptCourses'] == 'TRUE') {
			//get the immediate prev result  $RegNo,$CurLvl,$CurSem
			$imdprevrst = GetPrevResult($regNo, $lvl, $sem);
			//Process Probation
			if (is_array($courseCntr) && $courseCntr['CheckProb'] == 'TRUE') {
				if ($lvl > 1) {
					$probcgpa = -1;
					if ((int)$sem == 1) { //if sem is 1 i.e immdiate result = lvl - 1, sem = 2
						if (is_array($imdprevrst)) {
							$probcgpa = (int)$imdprevrst['CCH'] > 0 ? number_format((int)$imdprevrst['CGP'] / (int)$imdprevrst['CCH']) : $probcgpa;
						}
					} else {
						//get the last year cgpa
						$imdprevrstprob = GetPrevResult($regNo, $lvl, 1);
						if (is_array($imdprevrstprob)) {
							$probcgpa = (int)$imdprevrstprob['CCH'] > 0 ? number_format((int)$imdprevrstprob['CGP'] / (int)$imdprevrstprob['CCH']) : $probcgpa;
						}
					}
					$grdstr = $dbo->SelectFirstRow("resultinfo_tb", "", "ID = (select GrdStrucID from school_tb limit 1)");
					$problimit = (float)$grdstr['ProbationLimit'];
					$probTCH = (int)$grdstr['ProbationTCH'];
					if ($probcgpa > -1 && $probcgpa < $problimit) { //if in prob year
						$totchdb = $probTCH;
						$probyear = true;
					}
				}
			}
			//process probation end


			//check for oustanding and repeat course
			if (is_array($imdprevrst)) { //if prev result exist
				$OutSt = $imdprevrst['Outst'];
				$OutStArr = explode("+", $OutSt);
				$OutSt = count($OutStArr) > 1 ? $OutStArr[1] : $OutStArr[0];
				$Rept = $imdprevrst['Rept'];
				$ReptArr = explode("+", $Rept);
				$Rept = count($ReptArr) > 1 ? $ReptArr[1] : $ReptArr[0];
				//load oustanding courses 
				if (trim($OutSt) != "" && $courseCntr['UnRegCourses'] == 'TRUE') {
					$foutsStr = trim($OutSt, ":");
					$OutsPreSel = str_replace("::", "~", $foutsStr);
					$presel = $OutsPreSel;
					$queryOutst = str_replace("::", " OR CourseID=", $foutsStr);
					$OutstCRst = $dbo->Select("course_tb", "", "(CourseID=" . $queryOutst . ") AND Sem=" . $sem);
					if (is_array($OutstCRst)) {
						if ($OutstCRst[1] > 0) {
							$OutstCourses = $OutstCRst[0];
						}
					}
				}
				//load repeat courses 
				if (trim($Rept) != "" && $courseCntr['ReptCourses'] == 'TRUE') {
					$freptStr = trim($Rept, ":");

					$ReptPreSel = str_replace("::", "~", $freptStr);
					$presel .= trim($OutsPreSel) == "" ? $ReptPreSel : "~" . $ReptPreSel;
					$queryRept = str_replace("::", " OR CourseID=", $freptStr);
					$ReptCRst = $dbo->Select("course_tb", "", "(CourseID=" . $queryRept . ") AND Sem=" . $sem);
					if (is_array($ReptCRst)) {
						if ($ReptCRst[1] > 0) {
							$RepeatCourses = $ReptCRst[0];
						}
					}
				}
			}
		}
		$presel .= "~" . $genpresel;
		$preselArr = explode("~", $presel);
		$preselArr = array_unique($preselArr);
		$presel = trim(implode("~", $preselArr), "~");



		/// echo $genpresel;

		//check if courses not found
		if ($scourses[1] < 1 && is_null($OutstCourses) &&  is_null($RepeatCourses)) {
			exit("###");
		}
		$ortherinfo = $probyear ? " - Probation Year" : "";
		GroupBoxTitle("Courses" . $ortherinfo);
		//check if student already have result
		$hasRst = false;
		$hasRstOBJ = $dbo->SelectFirstRow("result_tb", "Rst", "Lvl=$lvl AND Sem=$sem AND RegNo='" . $dbo->SqlSafe($regNo) . "'");
		if (is_array($hasRstOBJ)) {
			if (trim($hasRstOBJ['Rst']) != "") {
				$hasRst = true;
			}
		}
		$disable = $hasRst ? "true" : "false";
		$loaded = array(); //array holding the displayed courses whill be used to eleminate duplicate courses
		$loadedpresel = $genpresel; //hold all real selected courses
		$totChCnt = 0; //calculate total Outst and Repeat loaded at a particular instance
		$AllCH = array(); //hold all courses CHs
		if ($totchdb < 0) {
			//$totchdb = GetBy("ProgID",$progID,"programme_tb");
			//$totchdb = $totchdb["TotalCH"];
			$totchdb = GetMaxCH($progID, $lvl, $sem);
		}
		Box("style=margin-bottom:4px;width:100%");
		if ($hasRst) { //if result already uploaded
			Alert("Course Registration Update Disabled - Result Already Uploaded");
		} else {
			//display the auto-reg and clear all button
			InlineBtn("onclick=CheckList.SelectAll(true\,'semcs'\,'courselist'\,Course.SelectCourse\,Course.UnSelectCourse),text=<i class\=\"fa fa-check-square\"></i> AUTO-REGISTER,error=false,style=margin-right:5px");
			InlineBtn("onclick=CheckList.SelectAll(false\,''\,'courselist'\,Course.SelectCourse\,Course.UnSelectCourse),text=<i class\=\"fa fa-square\"></i> CLEAR ALL,error=true");
		}
		_Box();
		//echo $totchdb;
		$rtnregc = OpenCheckList_r("name=courselist,id=courselist,style=width:100%;font-weight:,autoheightdiff=291px", $presel, "Course.SelectCourse", "Course.UnSelectCourse");
		$rtnregc .= CheckListHeader_r("<div style=\"width:20%\">CODE</div><div style=\"width:calc(60% - 16px);text-transform:uppercase\">TITLE</div><div style=\"width:10%\" id=\"{$id}ch\">CH</div><div style=\"width:10%\" >E-GRP</div>", "multiple=false");
		$first = true;
		$outStPreSelReal = "";
		$SemcElectivs = []; //hold total electives selected by level
		$UnselElective = []; //hold the unselect elective
		//display all outstanding courses
		if (!is_null($OutstCourses) && $courseCntr['UnRegCourses'] == 'TRUE') {
			$rtnregc .= CheckListHeader_r("<div style=\"width:100%;text-align:center;font-weight:bold\"> UN-REGISTERED COURSES </div>", "group=unreg,status=checked,disable=true,multiple=false");
			while ($outstC = $OutstCourses->fetch_array()) {

				$cls = ($first) ? "first" : "";
				$id = $outstC['CourseID'];
				if (in_array($id, $loaded)) { //if already loaded skip
					continue;
				}
				$courseCode = strtoupper($outstC['CourseCode']);
				$cTitle = $outstC['Title']; //Title
				$CH = $outstC['CH'];
				$cLvl = $outstC['Lvl'];
				if (((int)$CH + $totChCnt) > (int)$totchdb) { //if acumulated $CH is greater than total allowable CH
					break;
				}
				//elective group
				$ElectGrp = $outstC['Elective'];
				$ElecInd = ElectiveGroup($id, $ElectGrp, $cLvl, $SemcElectivs, $preselArr);
				$rtnregc .= CheckListItem_r("<div style=\"width:20%\">{$courseCode}</div><div style=\"width:calc(60% - 16px);text-transform:uppercase\">{$cTitle}</div><div style=\"width:10%\" id=\"{$id}ch\">{$CH}</div><div style=\"width:10%\">$ElecInd</div>", "name=courselist,id={$id},class={$cls},disable=true,group=unreg");
				$first = false;
				$loaded[] = $id;
				$AllCH[$id] = $CH;
				$outStPreSelReal .= $id . "~";
				$totChCnt += (int)$CH;
			}
			$outStPreSelReal = rtrim($outStPreSelReal, "~");
		}

		$reptPreSelReal = "";
		//display all repeat courses 
		if (!is_null($RepeatCourses) && $courseCntr['ReptCourses'] == 'TRUE') {
			$rtnregc .= CheckListHeader_r("<div style=\"width:100%;text-align:center;font-weight:bold\"> REPEAT COURSES </div>", "group=rept,status=checked,disable=true,multiple=false");
			while ($reptC = $RepeatCourses->fetch_array()) {
				$cls = ($first) ? "first" : "";
				$id = $reptC['CourseID'];
				if (in_array($id, $loaded)) { //if already loaded skip
					continue;
				}
				$courseCode = strtoupper($reptC['CourseCode']);
				$cTitle = $reptC['Title']; //Title
				$cLvl = $reptC['Lvl'];
				$CH = $reptC['CH'];
				if (((int)$CH + $totChCnt) > (int)$totchdb) { //if acumulated $CH is greater than total allowable CH
					break;
				}
				//elective group
				$ElectGrp = $reptC['Elective'];
				$ElecInd = ElectiveGroup($id, $ElectGrp, $cLvl, $SemcElectivs, $preselArr);
				$rtnregc .= CheckListItem_r("<div style=\"width:20%\">{$courseCode}</div><div style=\"width:calc(60% - 16px);text-transform:uppercase\">{$cTitle}</div><div style=\"width:10%\" id=\"{$id}ch\">{$CH}</div><div style=\"width:10%\" >$ElecInd</div>", "name=courselist,id={$id},class={$cls},disable=true,group=rept");
				$first = false;
				$loaded[] = $id;
				$AllCH[$id] = $CH;
				$reptPreSelReal .= $id . "~";
				$totChCnt += (int)$CH;
			}
			$reptPreSelReal = rtrim($reptPreSelReal, "~");
		}
		// $fgg = @$_POST['ss'];
		if ($scourses[1] > 0 && $probyear == false) {
			if (count($loaded) > 0) {
				$rtnregc .= CheckListHeader_r("<div style=\"width:100%;text-align:center;font-weight:bold\"> SEMESTER COURSES </div>", "group=semcs,multiple=false");
			}

			while ($curse = $scourses[0]->fetch_array()) {
				$cls = ($first) ? "first" : "";
				$id = $curse['CourseID'];
				if (in_array($id, $loaded)) { //if already loaded skip
					continue;
				}
				$courseCode = strtoupper($curse['CourseCode']);
				$cTitle = $curse['Title']; //Title
				$CH = $curse['CH'];
				$cLvl = $curse['Lvl'];
				$select = 'true';
				//elective group
				$ElectGrp = $curse['Elective'];
				$ElecInd = ElectiveGroup($id, $ElectGrp, $cLvl, $SemcElectivs, $preselArr);

				//keep the unselect elective course
				if ((int)$ElectGrp > 1) { //if a compalsor elective group
					if (!isset($UnselElective[$cLvl . '_' . $ElectGrp])) $UnselElective[$cLvl . '_' . $ElectGrp] = [];
					if (!in_array($id, $preselArr)) { //if not selected
						$UnselElective[$cLvl . '_' . $ElectGrp][] = $id;
					}
				}

				$rtnregc .= CheckListItem_r("<div style=\"width:20%\">{$courseCode}<strong></strong></div><div style=\"width:calc(60% - 16px);text-transform:uppercase\">{$cTitle}</div><div style=\"width:10%\" id=\"{$id}ch\">{$CH}</div><div style=\"width:10%\">{$ElecInd}</div>", "name=courselist,id={$id},class={$cls},disable=$disable,group=semcs,preset=$select");

				$first = false;
				if ((int)$ElectGrp == 0) { //if is a compulsary course
					$curcourses .= $id . "~";
				}

				$loaded[] = $id;
				$AllCH[$id] = $CH;
			}
		}
		$curcourses = rtrim($curcourses, "~");
		//$courseCntr = $dbo->SelectFirstRow("coursecontrol_tb");
		$lowerlvl = is_array($courseCntr) ? $courseCntr['LowerLevel'] : "TRUE";
		if ($lowerlvl == "TRUE" && $probyear == false) { //if lower level loading is allowed and student not in probation year
			$lcourses = GetStudCourses($regNo, $lvl, $sem, true, $progID, false); //include the disabled courses as well (because student might have failed the disabled courses, hense will be made available for student to register)
			if (is_array($lcourses)) {
				if ($lcourses[1] > 0) {
					$rtnregc .= CheckListHeader_r("<div style=\"width:100%;text-align:center;font-weight:bold\"> LOWER LEVEL COURSES </div>", "group=lowlevc,multiple=false");
					while ($lcurse = $lcourses[0]->fetch_array()) {
						$cls = ($first) ? "first" : "";
						$id = $lcurse['CourseID'];
						if (in_array($id, $loaded)) { //if already loaded skip
							continue;
						}
						$courseCode = strtoupper($lcurse['CourseCode']);
						$cTitle = $lcurse['Title']; //Title
						$CH = $lcurse['CH'];
						$cLvl = $lcurse['Lvl'];
						//elective group
						$ElectGrp = $lcurse['Elective'];
						$ElecInd = ElectiveGroup($id, $ElectGrp, $cLvl, $SemcElectivs, $preselArr);
						$rtnregc .= CheckListItem_r("<div style=\"width:20%\">{$courseCode}</div><div style=\"width:calc(60% - 16px);text-transform:uppercase\">{$cTitle}</div><div style=\"width:10%\" id=\"{$id}ch\">{$CH}</div><div style=\"width:10%\">$ElecInd</div>", "name=courselist,id={$id},class={$cls},disable=$disable,group=lowlevc");
						$first = false;
						$loaded[] = $id;
						$AllCH[$id] = $CH;
					}
				}
			}
		}
		//eee
		/*else{
		CheckListItem("<div style=\"width:99px\">[000]</div><div style=\"width:292px;text-transform:uppercase\">jhjj</div><div style=\"width:99px\">[10 Crd Unt]</div>","name=courselist,id=1,class=first");
	   //echo ;	
	}*/
		// $realsel = trim($outStPreSelReal."~".$reptPreSelReal."~".$genpresel,"~");
		$totch = 0;
		$tot = 0;
		$realsel = GetCheckListSelected();
		if (trim($realsel) != "") {
			$realSelArr = array_unique(explode("~", $realsel));
			$tot = count($realSelArr);
			$totch = 0;
			foreach ($realSelArr as $sel) {
				$CH = $AllCH[$sel];
				$totch += (int)$CH;
			}
			$realsel = implode("~", $realSelArr);
		}
		// $realsel = trim($realsel) == ""?"#":$realsel;
		$rtnregc .= CloseCheckList_r();
		echo $rtnregc;

		//form elective array string
		$electarrstr = json_encode($SemcElectivs);
		//put in an hidden div
		echo '<div style="display:none" id="courselist_elect">' . $electarrstr . '</div>';

		//form the unregistered elective courses
		//$UnselElective
		$unelectarrstr = json_encode($UnselElective);
		//put in an hidden div
		echo '<div style="display:none" id="courselist_unregelect">' . $unelectarrstr . '</div>';
		//$realsel = str_replace("#","",$realsel);
		/* if(trim($realsel) != ""){
			$selarr = explode("~",$realsel);
			$tot = count($selarr);
			$totch = 0;
			foreach($selarr as $sel){
				$CH = $AllCH[$sel];
				$totch += (int)$CH;
			}
		} */

		Hidden("name=totCH,id=totCH,value=" . $totch);
		Hidden("id=curcourses,value=" . $curcourses);
		TextBox("name=selcourse,id=selcourse,value=Total Course Selected - {$tot}         Total Credit Unit - {$totch},disabled=disabled,style=font-weight:bolder,width=100%,logo=tag");
		// echo $realsel;
		echo '<input type="hidden" id="totavCH" value="' . $totchdb . '" />';
		//generate RegNo 
		$autogendata = AutoGenRegNo($regNo);
		if (is_array($autogendata)) {
			list($newReg, $passpn) = $autogendata;
		} else {
			list($newReg, $passpn) = array($autogendata, "");
		}

		Hidden("name=newreg,id=newreg,value=" . $newReg);
		Hidden("name=passpreg,id=passpreg,value=" . $passpn);
		if ($newReg != "#" && $newReg != "##" && $newReg != "###" && $newReg != "####" && $newReg != "#####") {
			//if generated
			$regNo = $newReg;
		}

		if (!$hasRst) { //if no result
			if (trim($genpresel) == "") { //if no registration found
				ButtonImg("list-alt", "Register", "id=regcoursebtn,title=Register Selected Courses,onclick=Course.Register(this\,'{$regNo}'\, $lvl\, $sem)");
			} else {
				ButtonImg("list-alt", "Update", "id=regcoursebtn,title=Update Registered Courses,onclick=Course.Register(this\,'{$regNo}'\, $lvl\, $sem)");
				ButtonImg("print", "Print", "id=regcourseprintbtn,title=Print Course Form,style=margin-left:20px,onclick=Course.PrintSlip('{$regNo}'\,{$lvl}\,{$sem})");
			}
		} else { //if has result allow print only
			ButtonImg("print", "Print", "id=regcourseprintbtn,title=Print Course Form,style=margin-left:0px,onclick=Course.PrintSlip('{$regNo}'\,{$lvl}\,{$sem})");
		}
		/*}else{
			echo "###";//no course found
		}*/
	} else {
		echo "##";
	}
}

//function to process the elective indicators
function ElectiveGroup($id, $ElectGrp, $cLvl, &$SemcElectivs, $preselArr)
{
	//global $SemcElectivs; global $preselArr; global $id;
	$ElectGrp = (int)$ElectGrp;
	$ElecInd = "";
	if ($ElectGrp > 0) {
		$ElectGrpDis = $ElectGrp > 1 ? $ElectGrp - 1 : '0';
		$ElecInd = "E" . $cLvl . $ElectGrpDis;
		if (!isset($SemcElectivs[$cLvl . '_' . $ElectGrp])) $SemcElectivs[$cLvl . '_' . $ElectGrp] = 0;
		//check if maximum elective reach
		if ($SemcElectivs[$cLvl . '_' . $ElectGrp] >= $ElectGrp - 1) {
			//dont select it
			$select = 'false'; //force selection to unselect, even if the id is part of preset
		} else if (in_array($id, $preselArr)) {
			$SemcElectivs[$cLvl . '_' . $ElectGrp]++;
		}
	} else {
		$ElecInd = 'CP' . $cLvl;
	}
	echo '<input type="hidden" value="' . $ElectGrp . '" id="electgrp_' . $id . '" />';
	echo '<input type="hidden" value="' . $cLvl . '" id="clvl_' . $id . '" />';
	return $ElecInd;
}

//function to return the credit unit of the supplied course ID
function GetCH($courseID)
{
	global $dbo;
	$courseID = (int)$courseID;
	$check = $dbo->RunQuery("select CH from course_tb where CourseID = {$courseID}");
	if (is_array($check)) {
		if ($check[1] > 0) {
			$presel =  $check[0]->fetch_array();
			$presel = $presel["CH"];
			return $presel;
		}
	}
	return "";
}

//function to resolve the older partern of storing registered course into database to the new format
function ResolveRegCourses($regcourse)
{
	// echo $regcourse;
	$regcoursearr = explode("||", $regcourse);
	$courseStr = "";
	if (count($regcoursearr) > 1) { //check if former patern
		for ($d = 0; $d < count($regcoursearr); $d++) { //loop through and get only the Course IDs
			$course = $regcoursearr[$d];
			$courseID = (int)$course;
			$courseStr .= $courseID . "~"; //form the new type course reg string
		}
	} else { //if format not realy old
		if (count($regcoursearr) == 1) { //if only one string formed
			$rccc = explode("~~", $regcourse); //check if it is old but its only one course registered by student
			if (count($rccc) > 1) {
				$courseID = (int)$regcourse;
				$courseStr .= $courseID . "~";
			} else { //if not old patern
				//check the string if it is new pertern
				$rccc2 = explode("~", $regcourse);
				//i.e it is in new version/perthern

				if (count($rccc2) > 1) {
					$courseStr = $regcourse;
				} else {
					$courseStr = (int)$regcourse;
				}
			}
		}
	}
	$courseStr = rtrim($courseStr, "~");
	return $courseStr;
}

//function to get level name based on the level id
function LevelName($lvl, $StudyID = 5)
{
	global $dbo;
	$lvl = (int)$lvl;
	$StudyID = (int)$StudyID;
	$rst = $dbo->RunQuery("select Name, IF(Descr='',Name,Descr) as DES from schoollevel_tb where Level = {$lvl} and StudyID = {$StudyID}");
	//   $rst = $dbo -> RunQuery("select Name, IF(Descr='',Name,Descr) as DES from schoollevel_tb where SchoolTypeID = (select Type from school_tb limit 1) and Level = {$lvl} and StudyID = {$StudyID}");
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$rstval = $rst[0]->fetch_array();
			return $rstval[1];
		}
	}
	return $lvl;
}

//function to get cuorse details by supplying the courseID
function CourseDetails($courseID)
{
	global $dbo;
	global $phpf;
	$courseID = $dbo->SqlSave($courseID);
	$rst = $dbo->RunQuery("select * from course_tb where CourseID = {$courseID}");
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$rstval = $rst[0]->fetch_array();
			return $rstval;
		}
	}
	return "";
}

// function to resolve the old student passprot path
function ResolvePassport($path)
{

	$str = str_replace("StudPassP", "../epconfig/UserImages/Student", $path);
	if (strpos($path, "epconfig") === false) {
		$str = str_replace("UserImages", "../epconfig/UserImages", $str);
	}
	return $str;
}



//function to get paymnet type details (information) using the id
function PaymnetInfo($payID)
{
	global $dbo;
	$payID = (int)$payID;
	$rst = $dbo->RunQuery("select * from item_tb where ID = {$payID}");
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$rstval = $rst[0]->fetch_array();
			$cntrTb =  $rstval['ControlTable'];
			$rst2 = $dbo->RunQuery("select * from {$cntrTb}");
			if (is_array($rst2)) {
				if ($rst2[1] > 0) {
					$rstval2 = $rst2[0]->fetch_array();
					return $rstval2;
				}
			}
		}
	}
	return "";
}

//function to Get the admission Status
function AdmissionStatus($RegNo, $RegID = 1)
{
	global $dbo;
	$str = "";
	$rst = $dbo->RunQuery("select * from studentbank_tb ORDER BY ID");
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			//$rw = mysql_fetch_array($rst[0]);GetBasicInfo
			//move through all student bank moving from the first which nust be studentinfo
			while ($sbrw = $rst[0]->fetch_array()) {
				$studpref = $sbrw["StudInfoPref"];
				$det = GetBasicInfo($RegNo, "", $studpref, 0);
				if (is_array($det)) {
					$str .= GroupBoxTitle_r("Adimission Details");
					$arrval[] =  array("[NAME]", "<strong>" . strtoupper($det['Name']) . "</strong>");
					$arrval[] = array("[REGISTRATION NUMBER]", "<strong>" . strtoupper($RegNo) . "</strong>");
					$arrval[] =  array("[GENDER]", strtoupper($det['Gen']));
					$arrval[] = array("[FACULTY/SCHOOL]", strtoupper($det['Fac']));
					$arrval[] = array("[DEPARTMENT]", strtoupper($det['Dept']));
					$arrval[] = array("[PROGRAMME]", strtoupper($det['Prog']));

					$form = STUDREG();
					//$RegIDsc = (trim($studpref) == "")?1:$RegID; // if user admited change RegID to one general for main student in studentinfo_tb
					if (is_array($form) && $form['Screening'] == "TRUE") {
						$scr = CheckScreen($RegNo, $studpref, $RegID);
						//echo $scr;
						if ($scr !== false) {
							$scrr = $scr === NULL ? "<strong class=\"errorColor\">FAILED</strong>" : "<strong class=\"successColor\">PASSED</strong>";
							$arrval[] = array("[SCREENING]", $scrr);
						}
					}
					//if found in main studentinfo_tb, meaning is admitted else, though register entrance but not registered
					$status = (trim($studpref) == "") ? "<strong class=\"successColor\">ADMITTED</strong>" : "<strong class=\"errorColor\">NOT YET ADMITTED</strong>";
					$arrval[] = array("[ADMISSION STATUS]", $status);
					$str .= Table_r($arrval, "", "100%*550px");
					if (trim($studpref) == "") {
						$str .= Text_r("", "Click the <span class=\"bold\">Bio Data</span> menu to continue Registration");
					}
					return $str;
				}
			}
		} else {
			$str = "##"; //no student data bank found  
		}
	} else {
		$str = "#@"; //error loading student data bank 
	}

	return $str;
}



//function to get grade from the general grading structure string -(Produce in GetGrade function when -1 is sent as score)
function GetGradeFromString($score, $genstr)
{
	global $dbo;
	if (trim($genstr) == "") return ["Grade" => "", "Level" => 0, "Desc" => "", "PASS" => 0];
	//	$gengradestruc = $dbo->DataArray($genstr);
	//if(count($gengradestruc) < 1)return ["Grade"=>"","Level"=>0,"Desc"=>"","PASS"=>0];
	//break into individual grades
	$indgrads = explode("&", $genstr);
	if (count($indgrads) > 0) {
		for ($s = 0; $s < count($indgrads); $s++) {
			$indgrad = $indgrads[$s];
			if (trim($indgrad) != "") {
				//break to get score and equivalent grade
				$scoregrd = explode("=", $indgrad);
				if (count($scoregrd) == 2) {
					$val = trim($scoregrd[0]);
					$grd = trim(rawurldecode($scoregrd[1]));

					//get gradepoint
					/*$grdpntarr = explode("|",$grd);
					 $point = 0;
					 if(count($grdpntarr) == 2){
						 $grd = $grdpntarr[0];
						 $point = (float)$grdpntarr[1];
					 }*/
					//check for < and >
					//get the first char
					$fcahr = substr($val, 0, 1);
					if ($fcahr == "<") { //if lessthan
						$val = substr($val, 1);
						//check if score certisfy cond
						if ($score < (float)$val) {
							return json_decode($grd, true);
						}
					} else if ($fcahr == ">") {
						$val = substr($val, 1);
						if ($score > (float)$val) {
							return json_decode($grd, true);
						}
					} else { //if not < or >
						//check if is range
						$rangarr = explode("-", $val);
						if (count($rangarr == 2)) { //if range
							$lval = (float)$rangarr[0];
							$mval = (float)$rangarr[1];
							if ($score >= $lval && $score <= $mval) {
								return json_decode($grd, true);
							}
						} else { //if direct value
							if ($score == (float)$val) {
								return json_decode($grd, true);
							}
						}
					}
				}
			}
		}
	}
	return ["Grade" => "", "Level" => 0, "Desc" => "", "PASS" => 0];
}

//format the grade string 

//function to get grade
function GetGrade($score, $gradstr = "", $grades = array(), $RstInfoID = 1)
{
	global $dbo;
	if ($gradstr == "") { //if grade string not send get from database
		$rst = $dbo->RunQuery("select * from resultinfo_tb where ID = $RstInfoID");
		if (is_array($rst)) {
			if ($rst[1] > 0) {
				$grad = $rst[0]->fetch_array();
				$gradstr = @$grad['Grading'];
			}
		}
	}
	//if grading structure processing nedded (all grades in datastring format)
	if ($score < 0) {
		if (count($grades) == 0) { //if no grading supplied, get them
			$grades = GetGradeDetAll($RstInfoID);
		}
		$processgrdstr = "";
		$indgrads = explode("&", $gradstr);
		if (count($indgrads) > 0) {
			for ($s = 0; $s < count($indgrads); $s++) {
				$indgrad = $indgrads[$s];
				if (trim($indgrad) != "") {
					//break to get score and equivalent grade
					$scoregrd = explode("=", $indgrad);
					if (count($scoregrd) == 2) {
						$val = trim($scoregrd[0]);
						$grd = trim($scoregrd[1]);
						$grddet = $grades[$grd];
						// $processgrdstr .= $val ."=".rawurlencode($grddet["Grade"]."|".$grddet["Level"]."|".$grddet["Desc"]."|".$grddet["PASS"]) . "&";
						$processgrdstr .= $val . "=" . rawurlencode(json_encode($grddet)) . "&";
					}
				}
			}
			$processgrdstr = rtrim($processgrdstr, "&");
		}
		return $processgrdstr == "" ? $gradstr : $processgrdstr;
	}
	if (trim($gradstr) != "") {
		//break into individual grades
		$indgrads = explode("&", $gradstr);
		if (count($indgrads) > 0) {
			for ($s = 0; $s < count($indgrads); $s++) {
				$indgrad = $indgrads[$s];
				if (trim($indgrad) != "") {
					//break to get score and equivalent grade
					$scoregrd = explode("=", $indgrad);
					if (count($scoregrd) == 2) {
						$val = trim($scoregrd[0]);
						$grd = trim($scoregrd[1]);

						//get gradepoint
						/*$grdpntarr = explode("|",$grd);
								$point = 0;
								if(count($grdpntarr) == 2){
									$grd = $grdpntarr[0];
									$point = (float)$grdpntarr[1];
								}*/
						//check for < and >
						//get the first char
						$fcahr = substr($val, 0, 1);
						if ($fcahr == "<") { //if lessthan
							$val = substr($val, 1);
							//check if score certisfy cond
							if ($score < (float)$val) {
								return isset($grades[$grd]) ? $grades[$grd] : GetGradeDet($grd);
							}
						} else if ($fcahr == ">") {
							$val = substr($val, 1);
							if ($score > (float)$val) {
								return isset($grades[$grd]) ? $grades[$grd] : GetGradeDet($grd);
							}
						} else { //if not < or >
							//check if is range
							$rangarr = explode("-", $val);
							if (count($rangarr == 2)) { //if range
								$lval = (float)$rangarr[0];
								$mval = (float)$rangarr[1];
								if ($score >= $lval && $score <= $mval) {
									return isset($grades[$grd]) ? $grades[$grd] : GetGradeDet($grd);
								}
							} else { //if direct value
								if ($score == (float)$val) {
									return isset($grades[$grd]) ? $grades[$grd] : GetGradeDet($grd);
								}
							}
						}
					}
				}
			}
		}
	}
	//}
	//}
	return "0";
}
//fetch all grade structure from school grade to be use in GetGrade function Preload
function GetGradeDetAll($RstInfoID = 1)
{
	global $dbo;
	$rtn = array();
	$rst = $dbo->RunQuery("select * from schgrade_tb WHERE RstInfoID = $RstInfoID");

	if (is_array($rst)) {
		if ($rst[1] > 0) {
			while ($grds = $rst[0]->fetch_array(MYSQLI_ASSOC)) {
				$rtn[$grds["ID"]] = $grds;
			}
		}
	}
	return $rtn;
}
//function to get gradedet from schgrade table
function GetGradeDet($GradeID)
{
	global $dbo;
	$rtn = array();
	$rst = $dbo->RunQuery("select * from schgrade_tb where ID = {$GradeID} limit 1");
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			return $rst[0]->fetch_array();
		}
	}
}

function GetClassPassDetAll($RstInfoID = 1)
{
	global $dbo;
	$rtn = array();
	$rst = $dbo->RunQuery("select * from classofpass_tb where SchoolID = (select Type from school_tb limit 1) AND RstInfoID=" . $RstInfoID);

	if (is_array($rst)) {
		if ($rst[1] > 0) {
			while ($grds = $rst[0]->fetch_array()) {
				$rtn[$grds[0]] = $grds;
			}
		}
	}
	return $rtn;
}

function GetClassPassBySchool($SchoolID, $RstInfoID = 1)
{
	global $dbo;
	$rtn = array();
	$rst = $dbo->RunQuery("select * from classofpass_tb where SchoolID = $SchoolID AND RstInfoID=" . $RstInfoID);

	if (is_array($rst)) {
		if ($rst[1] > 0) {
			while ($grds = $rst[0]->fetch_array()) {
				$rtn[$grds[0]] = $grds;
			}
		}
	}
	return $rtn;
}

//function to get gradedet from schgrade table
function GetClassPassDet($ClassID)
{
	global $dbo;
	$rtn = array();
	$rst = $dbo->RunQuery("select * from classofpass_tb where ID = {$ClassID} and SchoolID = (select Type from school_tb limit 1) limit 1");
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			return $rst[0]->fetch_array();
		}
	}
}

//function to get the class of pass structure
function GetClassPassStruct($RstInfoID = 1)
{
	global $dbo;
	//if($classstr == ""){ //if classofpass string not send get from database
	$rst = $dbo->RunQuery("select * from resultinfo_tb where ID = " . $RstInfoID);
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$grad = $rst[0]->fetch_array();
			return $grad['ClassOfPass'];
		}
	}
	return "";
	//}
}

//function to get the class of pass based on the cgpa sent
function GetClassPass($cgpa = 0, $classstr = "", $clasesDet = array(), $RstInfoID = 1)
{
	global $dbo;
	if ($classstr == "") { //if classofpass string not send get from database
		$classstr = GetClassPassStruct($RstInfoID);
	}

	if (count($clasesDet) == 0) { //if class of pass details not sent
		$clasesDet = GetClassPassDetAll($RstInfoID);
	}

	//breackdown class structure
	$classStrArr = explode("&", $classstr);
	if (count($classStrArr) > 0) { //if structure element found
		//loop throug each structure element 
		foreach ($classStrArr as $indclassstr) {
			//get the range and classid 
			$rangvalArr = explode("=", $indclassstr);
			if (count($rangvalArr) == 2) {
				$classRange = trim($rangvalArr[0]);
				$rangeClassID = (int)$rangvalArr[1];
				//test range
				$firstChar = substr($classRange, 0, 1);
				if ($firstChar == "<" || $firstChar == ">") { //if is lessthan or greaterthan range structure
					//get the rangeval
					$testval = (float)substr($classRange, 1);
					$cond = $firstChar == "<" ? $cgpa < $testval : $cgpa > $testval;
					if ($cond) {
						return isset($clasesDet[$rangeClassID]) ? $clasesDet[$rangeClassID] : GetClassPassDet($rangeClassID);
					}
				} else {
					$ranges = explode("-", $classRange);
					if (count($ranges) == 2) { //if range boundary set
						$min = (float)$ranges[0];
						$max = (float)$ranges[1];
						if ($cgpa >= $min && $cgpa <= $max) {
							return isset($clasesDet[$rangeClassID]) ? $clasesDet[$rangeClassID] : GetClassPassDet($rangeClassID);
						}
					}
				}
			}
		}
	}

	return NULL;
}

//function to get grade point from grade
function GetPoint($igrd)
{
	global $dbo;
	$igrd = trim($igrd);
	$rst = $dbo->RunQuery("select * from resultinfo_tb");
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$grad = $rst[0]->fetch_array();
			$gradstr = @$grad['Grading'];
			if (trim($gradstr) != "") {
				//break into individual grades
				$indgrads = explode("~", $gradstr);
				if (count($indgrads) > 0) {
					for ($s = 0; $s < count($indgrads); $s++) {
						$indgrad = $indgrads[$s];
						if (trim($indgrad) != "") {
							//break to get score and equivalent grade
							$scoregrd = explode("=", $indgrad);
							if (count($scoregrd) == 2) {
								$val = trim($scoregrd[0]);
								$grd = trim($scoregrd[1]);
								//get gradepoint
								$grdpntarr = explode("|", $grd);
								//$point = 0;
								if (count($grdpntarr) == 2) {
									$grd = trim($grdpntarr[0]);
									if (strtolower($grd) == strtolower($igrd)) {
										return (float)$grdpntarr[1];
									}
								}
							}
						}
					}
				}
			}
		}
	}
	return 0;
}
//$GPU = array("A"=>5,"B"=>4,"C"=>3,"D"=>2,"E"=>1,"F"=>0);
//calculate GPA and CGPA - Not Used
function GPA($regNo, $lvl, $sem)
{
	global $dbo;
	$sqlregNo = $dbo->SqlSave($regNo);
	$lvl = (int)$lvl;
	$sem = (int)$sem;
	$rsult = $dbo->RunQuery("select * from result_tb where RegNo='{$sqlregNo}' and Lvl <= $lvl and Sem <= $sem");
	// and Lvl = {$lvl} and Sem = {$sem}
	$GPA = 0.0;
	$CGPA = 0.0;
	$TGPV = 0.0;
	$TCH = 0.0;
	$CTGPV = 0.0;
	$CTCH = 0.0;
	if (is_array($rsult)) {
		if ($rsult[1] > 0) {
			while ($rstarr = $rsult[0]->fetch_array()) {
				$results = $rstarr['Rst'];
				if (trim($results) != "") {
					$indrst = explode("~", $results);
					if (count($indrst) > 0) {
						for ($a = 0; $a < count($indrst); $a++) {
							$result = $indrst[$a];
							if (trim($result) != "") {
								//break to form result details
								$resultdet = explode("|", $result);
								if (count($resultdet) == 3) {
									$courseID = $resultdet[0];
									$CA = (float)$resultdet[1];
									$Exm = (float)$resultdet[2];
									$courseDet = CourseDetails($courseID); //get the course Details
									if (is_array($courseDet)) {
										$Cd = trim($courseDet['CourseCode']);
										$tit = $courseDet['Title'];
										$CH = (float)$courseDet['CH'];
										$tot = $CA + $Exm;
										$grd = GetGrade($tot);
										$pnt = GetPoint($grd);
										$GPV = $pnt * $CH;
										$CTGPV += $GPV;
										$CTCH += $CH;
										if ($lvl == $rstarr['Lvl'] && $sem == $rstarr['Sem']) { //if the current result
											$TGPV += $GPV;
											$TCH += $CH;
										}
										//$arrval2[] = array(str_replace(" ","&nbsp;",$Cd),"[".strtoupper($tit)."]","[{$CA}]","[{$Exm}]",$tot,$grd);  
									}
								}
							}
						}
					}
				}
			}
		}
	}
	if ($TCH > 0) {
		$GPA = $TGPV / $TCH;
	}

	if ($CTCH > 0) {
		$CGPA = $CTGPV / $CTCH;
	}
	return array(number_format($GPA, 2), number_format($CGPA, 2));
}


//function to resolve the individual result
function GetIndResult($indrststr)
{
	$result = $indrststr;
	$rtn = "";
	if (trim($result) != "") {
		//break to form result details
		$resultdet = explode("|", $result);
		if (count($resultdet) == 3) {
			$courseID = $resultdet[0];
			$CA = (float)$resultdet[1];
			$Exm = (float)$resultdet[2];
			$courseDet = CourseDetails($courseID); //get the course Details
			if (is_array($courseDet)) {
				$Cd = trim($courseDet['CourseCode']);
				$tit = $courseDet['Title'];
				$CH = $courseDet['CH'];
				$tot = $CA + $Exm;
				$grd = GetGrade($tot);
				$pnt = GetPoint($grd);
				// $grdd = $grd. "-" .GetPoint($grd);
				return array($Cd, $tit, $CH, $CA, $Exm, $tot, $grd, $pnt);
			}
		}
	}
	return $rtn;
}

//function to get immediate prevouse level semester details
function GetPrevLvlSem($rlvl, $rsem)
{
	$higsem = SchoolHighestSemester();
	$rlvl = (int)$rlvl;
	$rsem = (int)$rsem;
	if ($rlvl == 1 && ($rsem == 1)) return array("err" => "None"); //if freshers, i.e no prevous payment record
	if ($rlvl == 0 || $rsem == 0) return array("err" => "Invalid"); //if freshers, i.e no prevous payment record
	$rsem = ($rsem == ($higsem + 1)) ? 1 : $rsem; //if current payment is full take like first payment so that it can check for prev lvel sem 1
	$lvl = $rlvl;
	$sem = $rsem - 1; //calculate prevouse semester
	//if sem is zero mening it is previous level
	if ($sem == 0) {
		//resset the sem to the highest sem
		$sem = $higsem;
		//decrement lvl
		$lvl = $rlvl - 1;
		if ($lvl < 1) return array("err" => "Invalid");
	}
	//$sem = ($sem == 0)?$higsem:$sem; // if no semester for prev, den set semester to 2, meaning second semester of the prev level
	//$lvl = $rlvl - $sem + 1; //calculate prevous level
	return array("err" => "", "level" => $lvl, "semester" => $sem);
}

//function to get the modeof entry id by name
function GetMOEID($MOE)
{
	if ((int)$MOE > 0) return $MOE;
	return (strtolower(trim($MOE)) == "direct-entry") ? 2 : 1;
}

//function to get MOE name by ID
function GetMOEName($id)
{
	global $dbo;
	$rst = $dbo->RunQuery("SELECT Name FROM modeofentry_tb WHERE Level = $id LIMIT 1");
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			$rstarr = $rst[0]->fetch_array();
			return $rstarr[0];
		}
		return "NA";
	}
	return "Error";
}

//function to check is screened
function CheckScreen($regNo, $pref = "", $RegID = 1)
{
	//get level
	global $dbo;
	$RegIDr = trim($pref) == "" ? 1 : $RegID; //if checking stud level from main studentinfo_tb, set RegID to 1(general for all Student)
	$studLvl = StudLevel($regNo, $pref, $RegIDr);
	//$studModeofEn = GetMOE($regNo,$pref,$RegID); //get the student mode of entry
	// $studModeofEn = GetMOEID($studModeofEn); //get id
	// $rlvl = (int)$studLvl - ($studModeofEn - 1);
	//return $studLvl;
	if ($studLvl == 1) {
		//check if student exist in screening table
		$studscreen = $dbo->SelectFirstRow("screening_tb", "", "RegNo = '$regNo' AND RegID = $RegID");
		if (is_array($studscreen)) { //if found
			return $studscreen; //screend
		}
	} else {

		return false; //wrong student
	}
	return NULL; //not screened
	//
}

//this function will generate RRR (Remita payment platform only)
//it receives the payee details as array of the following keys => amt,orderId,pname,pemail,pphone,resurl 
function GenerateRRR($payeeDet)
{
	global $dbo;
	global $REMITAPARAM;
	//extract($REMITAPARAM);

	/*global $SERVICETYPEID;
global $APIKEY;
global $GATEWAYURL;
global $GATEWAYRRRPAYMENTURL;
global $CHECKSTATUSURL;*/
	if (isset($REMITAPARAM['MERCHANTID'])) {
		//return json_encode($REMITAPARAM);
		$MERCHANTID = $REMITAPARAM['MERCHANTID'];
		$APIKEY = $REMITAPARAM['APIKEY'];
		$GATEWAYURL = $REMITAPARAM['GATEWAYURL'];
		$GATEWAYRRRPAYMENTURL = $REMITAPARAM['GATEWAYRRRPAYMENTURL'];
		$CHECKSTATUSURL = $REMITAPARAM['CHECKSTATUSURL'];
		//LE => Using Service Type to detratmine bank/payment details #4
		$SERVICETYPEID = $payeeDet['serviceType'];
		$ITEM = $REMITAPARAM['ITEM_' . $SERVICETYPEID];
		$BN = $REMITAPARAM['BN_' . $SERVICETYPEID];
		$BA = $REMITAPARAM['BA_' . $SERVICETYPEID];
		$BC = $REMITAPARAM['BC_' . $SERVICETYPEID];
		$DFF = $REMITAPARAM['DFF_' . $SERVICETYPEID];
		$totalAmount = $payeeDet["amt"];
		$timesammp = DATE("dmyHis");
		$orderID = $payeeDet["orderId"];
		$payerName = $payeeDet["pname"];
		$payerEmail = $payeeDet["pemail"];
		$payerPhone = $payeeDet["pphone"];
		$responseurl = $payeeDet["resurl"];
		$hash_string = $MERCHANTID . $SERVICETYPEID . $orderID . $totalAmount . $responseurl . $APIKEY;
		$hash = hash('sha512', $hash_string);
		$itemtimestamp = $timesammp;
		//return $BC.";".$DFF;
		$ITEMAR = explode("~", $ITEM);
		$BNAR = explode("~", $BN);
		$BAAR = explode("~", $BA);
		$BCAR = explode("~", $BC);
		$DFFAR = explode("~", $DFF);
		$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];
			$BAMTCUR = $BAMTAR[$s];
			$content .= '{"lineItemsId":"' . $ITEMCUR . '","beneficiaryName":"' . $BNCUR . '","beneficiaryAccount":"' . $BACUR . '","bankCode":"' . $BCCUR . '","beneficiaryAmount":"' . $BAMTCUR . '","deductFeeFrom":"' . $DFFCUR . '"},';
		}
		$content = rtrim($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);
		curl_close($curl);
		$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 array("RRR" => $rrr, "Code" => $statuscode, "Message" => $statusMsg);
		} else {
			return array("RRR" => "", "Code" => $statuscode, "Message" => $statusMsg);
		}
	}
	return "Wrong Payment Parameter Set";
}

//function to get the student payment load level sending the student level and moe
function PayLoadLevel($lvl = 0, $MOE = 1)
{
	if ($lvl == 0 || $lvl == $MOE) return 1; //if student level is the MOE id means the student is just starting, then load 100 level payment
	return $lvl;
}

//function to return the slip footer
function SlipFooter($schabbr, $qrurl, $print = "", $thirdpartpay = "")
{
	$thirdpartpay = trim($thirdpartpay) != "" ? '| <strong>' . $thirdpartpay . '</strong>' : "";
	echo '<div style="text-align:; bottom:0px; margin:auto; width:95%; font-size:1em; border-top:#000 2px solid; border-bottom:none; margin-top:30px">
   <div style="float:left; width:150px; height:150px;">
	   <img src="' . $qrurl . '" alt="QR Code" title="Scan To Verify Documnet" style="width:inherit; height:inherit" />
	 </div>
     <div style="float:left; padding-top:20px; margin-left:20px;"><div style="">' . $print . '</div><div style="display:block; font-size:0.9em">' . date("d/m/Y | g:i:s A") . '</div><div style="display:block; font-size:0.9em">WEB PRINT</div><div style="display:block; font-size:0.9em">' . mt_rand() . '</div> <div style="">&copy;' . date("Y") . ' ' . $schabbr . ' | eduPorta ' . $thirdpartpay . ' </div><div style="display:block; font-size:0.9em">Powered by TAQUATECH</div>
	 </div>
	
     <div style="clear:both"></div>
  </div>';;
}

// 24/09/2016 - TAG: Function to Get the Semester and Semester Part Payment String e.g FIRST PAYMENT(PART)
function FormPayPolicy($Sem, $SemPart = 3, $partPayShare = NULL)
{
	global $dbo;
	if (is_null($partPayShare)) {
		$partPayShare = "HALF";
		$schpay = SchoolPayDet();
		if (is_array($schpay)) {
			$partPayShare = $schpay['PartPayShare'];
		}
	}

	if (!isset($Sem)) {
		return "NO PAYMENT";
	}
	//get the sem details
	$sems = $dbo->Select("semester_tb");
	if (!is_array($sems) || $sems[1] < 1) {
		$semnames = array(1 => "FIRST", 2 => "SECOND", 3 => "FULL");
	} else {
		$semnames = [];
		$Num = 0;
		while ($indsem = $sems[0]->fetch_assoc()) {
			$Num = (int)$indsem['Num'] < 1 ? (int)$indsem['ID'] : (int)$indsem['Num'];
			$Name = trim($indsem['Descr']) == "" ? $indsem['Sem'] : $indsem['Descr'];
			$semnames[$Num] = $Name;
		}
		$semnames[$Num + 1] = "FULL";
	}

	if ($partPayShare != "HALF") {
		$semparts = array(1 => "(PART)", 2 => "(BALANCE)", 3 => "(FULL)");
	} else {
		$semparts = array(1 => "(PART)", 2 => "(BALANCE)", 3 => "");
	}
	if ((int)$Sem == 3 && (int)$SemPart == 3) {
		return $semnames[(int)$Sem] . " PAYMENT";
	} else {
		return $semnames[(int)$Sem] . "" . $semparts[(int)$SemPart] . " PAYMENT";
	}
}

// 26/09/2016 - TAG: Function to get school payment Details
function SchoolPayDet()
{
	global $dbo;
	$schpay = $dbo->Select4rmdbtbFirstRw("schoolpayment_tb");
	return $schpay;
}

// 21/10/2016 - TAG: get state of origin by state id
function GetLGA($LGA)
{
	global $dbo;
	$LGAID = (int)$LGA;
	if ($LGAID < 1) return $LGA;
	$putmerst = $dbo->RunQuery("select * from lga_tb where LGAID = {$LGAID} limit 1");
	$lganm = "";
	if (is_array($putmerst)) {
		if ($putmerst[1] > 0) {
			$pdt = $putmerst[0]->fetch_array();
			$lganm = $pdt[1];
			//$dateputmer = $dateputme->format("d/m/y | h:m A");
		}
	}
	return $lganm;
}

//function to get olevel grades
function GetOLevelGrades()
{
	global $dbo;
	$rst = $dbo->RunQuery("select * from olvlgrade_tb where Status = 1 ORDER BY Level");
	if (is_array($rst)) {
		if ($rst[1] > 0) {
			return $rst[0];
		}
	}
	return NULL;
}

function GetOLevelGrade($ID)
{
	global $dbo;
	return $dbo->SelectFirstRow("olvlgrade_tb", "", "Status = 1 AND ID = $ID");
}

function SessionName($sesID)
{
	$sesdet = GetBy("SesID", $sesID, "session_tb");
	if (is_array($sesdet)) {
		return $sesdet['SesName'];
	}
	return "";
}
//function to get user paid policy and the remaining
function GetPayPolicyRem($RegNo, $Lvl, $PayID)
{
	//get database object 
	global $dbo;
	$rRegNo = $RegNo;
	//clean datas for db 
	$RegNo = $dbo->SqlSafe($RegNo);
	$Lvl = $dbo->SqlSafe($Lvl);
	$PayID = $dbo->SqlSafe($PayID);
	$PaymentItem = GetPaymentItem($PayID);
	$CurSes = CurrentSes();
	$CurSes = $CurSes['SesID'];
	$studType = $PaymentItem['studType'];
	if ($studType == "f") { //if the payment type if for fresh student load only Full Payment (which is the only allowable payment policy)
		return array("3_3" => "FULL PAYMENT");
	}

	$schpay = $dbo->Select4rmdbtbFirstRw("schoolpayment_tb");
	$AutoSem = $schpay['AutoSem'];
	if ($AutoSem == 'ALL') {
		$partpay = $schpay['PartPay'];
		$partpayShare = $schpay['PartPayShare'];
		$pays = $partpayShare != 'QUATER' ? array('1' => 'FIRST PAYMENT', '2' => 'SECOND PAYMENT', '3' => 'FULL PAYMENT') : array('1_1' => 'FIRST PAYMENT(PART)', '1_2' => 'FIRST PAYMENT(COMPLETE)', '1_3' => 'FIRST PAYMENT(FULL)', '2_1' => 'SECOND PAYMENT(PART)', '2_2' => 'SECOND PAYMENT(COMPLETE)', '2_3' => 'SECOND PAYMENT(FULL)', '3' => 'FULL PAYMENT');
		return $pays;
	}

	$ProgID = GetStudentProgIDForPay($rRegNo);
	$query = "SELECT * FROM payhistory_tb WHERE Lvl = $Lvl AND RegNo = '$RegNo' AND PayID = $PayID AND ProgID=$ProgID AND Ses=$CurSes ORDER BY Sem ASC, SemPart ASC";
	//return array($query);
	//get the student Payments for the supplied level
	$pays = $dbo->RunQuery($query);
	$PaypolArr = array();
	if (is_array($pays)) { //if query runs
		//get the payment policy part share 
		$partPayShare = "HALF";
		//return $partpayShare;
		$schpay = SchoolPayDet();

		if (is_array($schpay)) {
			$partPayShare = strtoupper($schpay['PartPayShare']);
		}
		$highestPay = "0_0";

		$paypols = PayPolNames();

		if ($pays[1] > 0) { //if rows found
			//move through rows
			while ($pay = $pays[0]->fetch_array()) {
				$paypolid = $pay['Sem'] . "_" . $pay['SemPart'];
				$cpaypolname = $paypols[$partPayShare][$paypolid];
				if ($cpaypolname != null) {
					$PaypolArr[$paypolid] =  $cpaypolname;
					$highestPay = $paypolid;
				}
			}
		}

		//determine the remaining expected paypolicy
		$RemPayPolArr = PayPolRem();
		$RemPayPol = $RemPayPolArr[$highestPay][$partPayShare];
		//return $partpayShare;
		if ($RemPayPol != null) {
			$RemPayPolArr = explode(",", $RemPayPol);
			foreach ($RemPayPolArr as $rempayid) {
				$PaypolArr[$rempayid] =  $paypols[$partPayShare][$rempayid];
			}
		}
	}
	return $PaypolArr;
}

function PayPolRem($PayPolID='')
{
	$arrRemPayPol["0_0"] = array("HALF" => "1_3,3_3", "QUATER" => "1_1,1_3,3_3");
	$arrRemPayPol["1_1"] = array("HALF" => null, "QUATER" => "1_2");
	$arrRemPayPol["1_2"] = array("HALF" => null, "QUATER" => "2_1,2_3");
	$arrRemPayPol["1_3"] = array("HALF" => "2_3", "QUATER" => "2_1,2_3");
	$arrRemPayPol["2_1"] = array("HALF" => null, "QUATER" => "2_2");
	$arrRemPayPol["2_2"] = array("HALF" => null, "QUATER" => null);
	$arrRemPayPol["2_3"] = array("HALF" => null, "QUATER" => null);
	$arrRemPayPol["3_3"] = array("HALF" => null, "QUATER" => null);
	return $arrRemPayPol;
}

//function to get payment policy name
function PayPolNames()
{
	//Get current set share payment policy (HALF/QUATER)
	$arrNames = array();

	//set names
	$arrNames["HALF"]["1_1"] = null;
	$arrNames["HALF"]["1_2"] = null;
	$arrNames["HALF"]["1_3"] = "FIRST PAYMENT";
	$arrNames["HALF"]["2_1"] = null;
	$arrNames["HALF"]["2_2"] = null;
	$arrNames["HALF"]["2_3"] = "SECOND PAYMENT";
	$arrNames["HALF"]["3_3"] = "FULL PAYMENT";

	$arrNames["QUATER"]["1_1"] = "FIRST PAYMENT(PART)";
	$arrNames["QUATER"]["1_2"] = "FIRST PAYMENT(COMPLETE)";
	$arrNames["QUATER"]["1_3"] = "FIRST PAYMENT(FULL)";
	$arrNames["QUATER"]["2_1"] = "SECOND PAYMENT(PART)";
	$arrNames["QUATER"]["2_2"] = "SECOND PAYMENT(COMPLETE)";
	$arrNames["QUATER"]["2_3"] = "SECOND PAYMENT(FULL)";
	$arrNames["QUATER"]["3_3"] = "FULL PAYMENT";
	return $arrNames;
}
function GetPayPolicy($RegNo, $Lvl, $PayID, $All = false, $nocheck = false)
{
	//get the student payment parameters
	//RegNo+"' and Lvl = "+Lvl+" and PayID = "+PayID

	global $dbo;
	$rRegNo = $RegNo;
	$RegNo  = $dbo->SqlSafe($RegNo);
	$Lvl  = $dbo->SqlSafe($Lvl);
	$PayID  = $dbo->SqlSafe($PayID);
	$retnval = "";
	//get the school payment settings
	$schpay = $dbo->Select4rmdbtbFirstRw("schoolpayment_tb");
	$payItem = $dbo->Select4rmdbtbFirstRw("item_tb", "", "ID=" . $PayID);
	$studType = trim($payItem["studType"]);
	//$partpay = $schpay['PartPay'];

	if (is_array($schpay)) {
		$partpay = $schpay['PartPay'];
		$partpayShare = $schpay['PartPayShare'];
		$pays = $partpayShare != 'QUATER' ? array('1' => 'FIRST PAYMENT', '2' => 'SECOND PAYMENT', '3' => 'FULL PAYMENT') : array('1_1' => 'FIRST PAYMENT(PART)', '1_2' => 'FIRST PAYMENT(COMPLETE)', '1_3' => 'FIRST PAYMENT(FULL)', '2_1' => 'SECOND PAYMENT(PART)', '2_2' => 'SECOND PAYMENT(COMPLETE)', '2_3' => 'SECOND PAYMENT(FULL)', '3' => 'FULL PAYMENT');
		$AutoSem = $schpay['AutoSem'];
		if ($AutoSem == 'ALL') {
			return $dbo->DataString($pays);
		}
		$prevcheck = $schpay['PrevCheck'];
		//Get if Payment will strictly check the current semester
		//***************************************

		$CurrSem = GetCurrentSem();
		$CurrSem = $CurrSem[0];
		$CurSes = CurrentSes();
		$CurSes = $CurSes['SesID'];
		//
		//get student session from course reg
		$studses = $schpay['SessionCheck'] == "CURRENT" ? " AND Ses={$CurSes}" : "";
		/* $check = $dbo->SelectFirstRow("coursereg_tb","","RegNo = '{$sqlregNo}' and Lvl = {$lvl} and Sem = {$sem}");
	if(is_array($check)){
		$studses = (int)$check['SesID'];
	} */
		//HasPaid($regNo,$payID,$lvl = 0,$sem = 0,$sempart=3,$RegID=1,$SesID=0)

		//$paid = HasPaid($regNo,$payID,$lvl,$sem,0,1,$studses);
		//*************************************
		$progID = GetStudentProgIDForPay($rRegNo);
		//get all payment made by student in the selected level
		$payhist = $dbo->RunQuery("SELECT * FROM payhistory_tb WHERE RegNo = '$RegNo' AND Lvl = $Lvl AND ProgID=$progID AND PayID = $PayID $studses");

		//AKSCOE  WORK AROUND

		//$payhist = $dbo->RunQuery("SELECT * FROM payhistory_tb WHERE RegNo = '$RegNo' AND Lvl = $Lvl AND PayID = $PayID");
		//AKSCOE  WORK AROUND
		if (is_array($payhist)) {
			//echo $payhist[1];
			if ($payhist[1] < 1) {
				//no payment found//
				//set the policy based on the part pay division set
				//echo "hhhh3";
				// exit;
				if ($studType  == "f") {
					return "3=FULL PAYMENT";
				}
				//***************************************
				//if autosem is disabled and currsem is 2
				if ((int)$CurrSem == 2 && $AutoSem == 'FALSE') {
					return "##"; //prevous payment not found advise to suspend study
				}
				$rst = ($partpayShare != 'QUATER') ? "1=FIRST PAYMENT&3=FULL PAYMENT" : "1_1=FIRST PAYMENT(PART)&1_3=FIRST PAYMENT(FULL)&3=FULL PAYMENT";
				$retnval .= $rst;
			} else { //if student has made payment

				$paidstr = "";
				while ($recs = $payhist[0]->fetch_array()) {
					$Sem = $recs['Sem'] . "";
					$SemPart = $recs['SemPart'] . "";
					if ((int)$Sem == 3) { //complete payment already made
						$retnval .= $All ? "3=FULL PAYMENT" : "#";
						return $retnval;
					} else {
						if ($partpayShare != 'QUATER') { //half sharing payment
							$paidstr .= $Sem . "=" . $pays[$Sem] . "&";
							$pays[$Sem] = "";
						} else {
							$paidstr .= $Sem . "_" . $SemPart . "=" . $pays[$Sem . "_" . $SemPart] . "&";
							$pays[$Sem . "_" . $SemPart] = "";
						}
					}
				}
				$paidstr = rtrim($paidstr, "&");
				if ($studType  == "f") {
					return "3=FULL PAYMENT";
				}
				// print_r($pays['2']);
				//Check for invalid stud payment
				/* Check Prevpayment enabled :: 25/07/2017*/
				if ((int)$CurrSem == 2 && $AutoSem == 'FALSE') {
					if (($pays['1'] != '' && $pays['2'] != '') && $partpayShare != 'QUATER') {
						return "##"; //prevous payment not found advise to suspend study
					}
					if (($pays['1_2'] != '' && $pays['1_3'] != '') && $partpayShare == 'QUATER') {
						return "##"; //prevous payment not found advise to suspend study
					}
				}
				//form the display policy list
				if ($partpayShare != 'QUATER') { //half sharing payment
					//case first paid and second not paid
					if ($pays['1'] == '' && $pays['2'] != '') $retnval .= $All ? "1=FIRST PAYMENT&2=SECOND PAYMENT" : "2=SECOND PAYMENT";
					//case first not paid second paid (unusual)
					if ($pays['1'] != '' && $pays['2'] == '') $retnval .= $All ? "1=FIRST PAYMENT&2=SECOND PAYMENT" : "#";
					//case first not paid second not paid (unusual)
					if ($pays['1'] != '' && $pays['2'] != '') $retnval .= "1=FIRST PAYMENT&3=FULL PAYMENT";
					//case first paid second paid 
					if ($pays['1'] == '' && $pays['2'] == '') $retnval .= $All ? "1=FIRST PAYMENT&2=SECOND PAYMENT" : "#";
				} else { //quater sharing payment
					//Paid second full only

					if ($pays['2_3'] == '') {
						$retnval .= $All ? $paidstr : "#";
						return $retnval;
					}
					//Paid second complete only
					if ($pays['2_1'] == '' && $pays['2_2'] == '') {
						$retnval .= $All ? $paidstr : "#";
						return $retnval;
					}
					//Paid Second Part only
					if ($pays['2_1'] == '' && $pays['2_2'] != '') {
						$retnval .= $All ? $paidstr . "&2_2=SECOND PAYMENT(COMPLETE)" : "2_2=SECOND PAYMENT(COMPLETE)";
						return $retnval;
					}
					//Paid First Full
					if ($pays['1_3'] == '') {
						$retnval .= $All ? $paidstr . "&2_1=SECOND PAYMENT(PART)&2_3=SECOND PAYMENT(FULL)" : "2_1=SECOND PAYMENT(PART)&2_3=SECOND PAYMENT(FULL)";
						return $retnval;
					}
					//Paid First complete only
					if ($pays['1_1'] == '' && $pays['1_2'] == '') {
						$retnval .= $All ? $paidstr . "&2_1=SECOND PAYMENT(PART)&2_3=SECOND PAYMENT(FULL)" : "2_1=SECOND PAYMENT(PART)&2_3=SECOND PAYMENT(FULL)";
						return $retnval;
					}
					//Paid First Part only
					if ($pays['1_1'] == '' && $pays['1_2'] != '') {
						$retnval .= $All ? $paidstr . "&1_2=FIRST PAYMENT(COMPLETE)" : "1_2=FIRST PAYMENT(COMPLETE)";
						return $retnval;
					}

					//unusual cases
					//not paid First Part, But Paid First Complete
					if ($pays['1_1'] != '' && $pays['1_2'] == '') {
						if ($prevcheck == "TRUE") {
							$retnval .= $All ? $paidstr . "&1_1=FIRST PAYMENT(PART)" : "1_1=FIRST PAYMENT(PART)";
							return $retnval;
						} else {
							$retnval .= $All ? $paidstr . "&1_1=FIRST PAYMENT(PART)&2_1=SECOND PAYMENT(PART)&2_3=SECOND PAYMENT(FULL)" : "2_1=SECOND PAYMENT(PART)&2_3=SECOND PAYMENT(FULL)";
							return $retnval;
						}
					}
					//not paid Second Part, But Paid Second Complete
					if ($pays['2_1'] != '' && $pays['2_2'] == '') {
						if ($prevcheck == "TRUE") {
							$retnval .= $All ? $paidstr . "&2_1=SECOND PAYMENT(PART)" : "2_1=SECOND PAYMENT(PART)";
							return $retnval;
						} else {
							$retnval .= $All ? $paidstr . "&2_1=SECOND PAYMENT(PART)" : "#";
							return $retnval;
						}
					}
				}
			}
		}
	} //Added to correctly close all opened bracket 22-5-17 #1
	return $retnval;
}

function ExtraLevelString()
{
	$sch = GetBy("ID", "1", "school_tb");
	$ExtraLevelStr = "Spillover";
	if (count($sch) > 0) {
		$ExtraLevelStr = $sch["ExtraYearPrefix"];
	}
	return $ExtraLevelStr;
}

//function to generate itemnum and transnum(unique) 
function generateTransInfoOnly()
{
	global $dbo;
	$item_num = mt_rand(1000, 999999999) . date("dmyHis");
	do {
		$trans_nums = mt_rand(1000000000, 9999999999); //rep PAYEE ID here
		//$trans_nums = $trans_nums;
		$chek = $dbo->Select4rmdbtbFirstRw("order_tb", "", "TransNum = '" . $dbo->SqlSave($trans_nums) . "' OR ExpiredRef LIKE '%:" . $dbo->SqlSave($trans_nums) . ":%'");
	} while (is_array($chek));

	return array($item_num, $trans_nums);
}
function generateTransInfo()
{
	//return array(747488484,744884746);
	global $dbo;
	global $thirdP;
	global $Amt;
	global $studinfo;
	global $PayID;
	global $Sem;
	global $sempart;
	$item_num = mt_rand(1000, 999999999) . date("dmyHis"); //rep orderID for REMITA
	if ($thirdP == 2) {

		do {
			$trans_nums = mt_rand(1000000000, 9999999999); //rep PAYEE ID here
			//$trans_nums = $trans_nums;
			$chek = $dbo->Select4rmdbtbFirstRw("order_tb", "", "TransNum = '" . $dbo->SqlSave($trans_nums) . "' OR ExpiredRef LIKE '%:" . $dbo->SqlSave($trans_nums) . ":%'");
		} while (is_array($chek));
		/*{
					  //$item_num = mt_rand(1000,999999999);
					  $trans_nums = mt_rand(1000000000,9999999999);
					  //$trans_nums = $trans_nums."".$item_num;
					  $chek = $dbo -> Select4rmdbtbFirstRw("order_tb","","TransNum = '".$dbo->SqlSave($trans_nums)."'");
				  }*/
	} else { //if remita
		//call the function that generate the RRR for the current payment request of the payee
		//amt,orderId,pname,pemail,pphone,resurl http://localhost/projects/rportals/Admin/remita/sample-receipt-page.php
		$payitem = GetPaymentItem($PayID); //get the payment item details
		$serviceType = $payitem['PaymentID']; //get the service charge
		//LE = #3
		//check if based on stud info
		$servTarr = explode("~", $serviceType);
		if (count($servTarr) == 2) {
			//get the determinal
			$determ = trim(strtolower($servTarr[0]));
			$valarr = $dbo->DataArray($servTarr[1]);
			if ($determ == "fac") { //if based on fac
				$serviceType = isset($valarr[$studinfo['FacID']]) ? $valarr[$studinfo['FacID']] : array_shift($valarr);
			} else if ($determ == "prog") { //if based on programme
				$serviceType = isset($valarr[$studinfo['ProgID']]) ? $valarr[$studinfo['ProgID']] : array_shift($valarr);
			}
		}
		$amtsplit = GetPaymentSplit(array("Sem" => $Sem, "SemPart" => $sempart, "Amt" => $Amt, "PayID" => $PayID)); //get the amt split
		$studinfo["Email"] = trim($studinfo["Email"]) == "" ? "support@" . $_SERVER['HTTP_HOST'] : $studinfo["Email"];
		$requestData = array("amt" => array_sum($amtsplit) . "", "orderId" => $item_num, "pname" => $studinfo["Name"], "pemail" => $studinfo["Email"], "pphone" => $studinfo["Phone"], "resurl" => 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/finish.php", "serviceType" => $serviceType, "AmtSplit" => $amtsplit);
		//print_r($requestData);
		$rrrarr = GenerateRRR($requestData);
		//return $rrrarr;
		if (is_array($rrrarr)) { //if valid
			$RRR = $rrrarr["RRR"];
			$Code = $rrrarr["Code"];
			$Msg = $rrrarr["Message"];
			if ($RRR == "") {
				return '<h1 style="font-size:1.1em; font-weight: lighter">Error1: Cannot Generate Payment Reference<h1><h1 style="font-size:1.2em; font-weight: lighter">' . $Msg . $Code . '<h1>';
				//exit;
			} else {
				$trans_nums = $RRR;
			}
		} else { //invalid parameter
			return '<h1 style="font-size:1.1em; font-weight: lighter">Error2: Cannot Generate Payment Reference<h1><h1 style="font-size:1.2em; font-weight: lighter">' . $rrrarr . '<h1>';
			//exit;
		}
	}

	return array($item_num, $trans_nums);
}

//Auto Registration Number Functions 
//function to get the RegNoFormat
function GetAutoRegNoParam($ProgID = 1)
{
	global $dbo;
	$fmt = "";
	$RegNoStart = 0;
	$fmtTable = "programme_tb";
	$NumStartTable = "programme_tb";
	//get from programme_tb (LOCAL)
	$rst = $dbo->SelectFirstRow("programme_tb", "RegNoFormat,RegNumStart", "ProgID = $ProgID");
	if (is_array($rst)) {
		$fmt = trim($rst['RegNoFormat']);
		$RegNoStart = (int)$rst['RegNumStart'];
	}

	//get from school_tb (GLOBAL) if not found locally
	if ($fmt == "" || $RegNoStart == 0) {
		$rst2 = $dbo->SelectFirstRow("school_tb", "RegNoFormat,RegNumStart");
		if (is_array($rst2)) {
			if ($fmt == "") {
				$fmt = trim($rst2['RegNoFormat']);
				$fmtTable = "school_tb";
			}
			if ($RegNoStart == 0) {
				$RegNoStart = (int)$rst2['RegNumStart'];
				$NumStartTable = "school_tb";
			}
		}
	}

	//if no found atall
	if ($fmt == "") {
		$fmt = "?AUTONUM?";
		$fmtTable = "";
	}
	if ($RegNoStart == 0) {
		$RegNoStart = 1;
		$NumStartTable = "";
	}
	return array($fmt, $RegNoStart, $fmtTable, $NumStartTable);
}

//function to generate registration number for the selected student
function AutoGenRegNo($RegNo, $RegID = 1, $SNewRegNo = NULL, $StudDet = NULL)
{
	global $dbo;

	$Sch = $dbo->SelectFirstRow("school_tb");
	if (is_array($Sch)) {
		if ($Sch['AutoRegNo'] == "FALSE" && is_null($SNewRegNo)) { //check if auto reg is enabled
			return "##"; //auto regno generation disabled
		}
		//check if student exist
		//$StudDet = $dbo->SelectFirstRow("studentinfo_tb","","(RegNo = '$RegNo' OR JambNo = '$RegNo') AND REGID = $RegID");
		$StudDet = is_null($StudDet) ? GetBasicInfo($RegNo, "studsch", "", -$RegID) : $StudDet;
		$RegCleared = false; //indicate if regno is to be cleared
		if (is_array($StudDet)) {
			$StudRegNo = $StudDet['RegNo'];
			//Check if Direct Update(Not autogen)
			if (!is_null($SNewRegNo)) { //if update regno sent
				//Update RegNo
				//check if RegNo is to be cleared
				if (trim($SNewRegNo) == "") { //if regno is to be cleared
					//get the student JambNo
					$JambNo = $StudDet['JambNo'];
					if (trim($JambNo) == "") { //if no tempoary number (RegNo cannot be cleared)
						//generate a tempoary number as JambNo
						$JambNo = AutoGenRegNoRand(strtoupper(substr($StudDet['Surname'], 0, 2)));
						//update the jambno
						//$updjamb = $dbo->Update("studentinfo_tb",["JambNo"=>$JambNo],"id=".$StudDet['id']);	
					}
					$RegCleared = true;
					$NewRegNo = $JambNo;
				} else { //if regno to be updated
					//check if already exist
					$rext = $dbo->SelectFirstRow("studentinfo_tb", "id", "RegNo = '$SNewRegNo' OR JambNo = '$SNewRegNo' LIMIT 1");
					if (is_array($rext)) return "Registration Number Already Exist";
					$NewRegNo = $SNewRegNo;
				}
				$UseAutoNum = 0;
				$autogenreg = "FALSE";
			} else { //Auto Generate Reg No

				if ($StudRegNo == "" || is_null($StudRegNo)) { //if student has no regno or student jambno is regno
					$StartSes = (int)$StudDet['StartSes'];
					$curSes = CurrentSes();
					$SesID = (int)$curSes['SesID'];
					if ($SesID != $StartSes && $Sch['AutoRegNoSet'] == 'FRESH') { //if not fresh student
						return "##"; //return as if auto reg is disabled
					}
					$StudRegNo = strtoupper(trim($StudDet['RegNo']));
					$StudJambNo = strtoupper(trim($StudDet['JambNo']));

					$sprogID = $StudDet['ProgID'];
					//No RegNo
					//Get the RegNoFormat and RegNoStart
					list($RegoFormat, $AutoNumStart, $frmTable, $NumStartTable) = GetAutoRegNoParam($sprogID);
					$FacAbbr = $StudDet['FacAbbr'];
					$DeptAbbr = $StudDet['DeptAbbr'];
					$ProgAbbr = $StudDet['ProgAbbr'];
					//get student start ses details
					$studsesdet = $dbo->SelectFirstRow("session_tb", "", "SesID=" . $StartSes);
					$ScurSes = is_array($studsesdet) ? $studsesdet : CurrentSes();
					$SesName = $ScurSes['SesName'];
					$SesAbbr = $ScurSes['Abbr'];
					$SchAbbr = "SCH";
					$GenScope = "BATCHPROG";
					//$sch = GetSchool();
					$sch = $Sch;
					if (is_array($sch)) {
						$SchAbbr = $sch['Abbr'];
						if (isset($sch['AutoRegNoScope'])) $GenScope = $sch['AutoRegNoScope'];
					}
					//Get on startses bases
					if ($GenScope == 'BATCH') { //generate base on the startses
						$sesquery = " AND StartSes = $StartSes";
					} else if ($GenScope == 'PROG') { //generate based on the programme
						$sesquery = " AND ProgID = $sprogID";
					} else { //generare based on the student in a batch and in a programme
						$sesquery = " AND ProgID = $sprogID AND StartSes = $StartSes";
					}
					//$sesquery = " AND StartSes = $StartSes";
					$tolerance = -1; //use to search next available generation if current generated exist
					do {
						$tolerance++;

						//get last regno generated student record
						$LastGenStud = $dbo->SelectFirstRow("studentinfo_tb", "", "AutoGenReg = 'TRUE' AND RegID = $RegID $sesquery ORDER BY AutoNum DESC");
						//  $LastGenStud = $dbo->SelectFirstRow("studentinfo_tb","","AutoGenReg = 'TRUE' AND RegID = $RegID AND ProgID = $sprogID $sesquery ORDER BY AutoNum DESC");
						$LastAutoNum = 0;
						if (is_array($LastGenStud)) { //if last generated student exist
							$LastAutoNum = $LastGenStud['AutoNum'];
						}
						$UseAutoNum = 1; //the new AutoNum
						//check if AutoNumStart is Negative (i.e reset generation (Force to increament from the AutoNumStart))
						if ($AutoNumStart < 0) {
							$UseAutoNum = abs($AutoNumStart);
							//update Auto Start to positive
							if ($NumStartTable != "") {
								$cond = $NumStartTable == "programme_tb" ? "ProgID = " . $StudDet['ProgID'] : "";
								$dbo->Update($NumStartTable, array("RegNumStart" => $UseAutoNum), $cond);
							}
						} else {
							if ($AutoNumStart <= $LastAutoNum) { //increment LastAutoNum
								$UseAutoNum = $LastAutoNum + 1 + $tolerance;
							} else {
								$UseAutoNum = $AutoNumStart + $tolerance;
							}
						}
						//format UseAutoNum to have minimium of 2 digit
						$UseAutoNumStr = $UseAutoNum . "";
						$len = strlen($UseAutoNumStr);
						$rem = 3 - $len;
						if ($rem > 0) {
							$UseAutoNum = str_repeat("0", $rem) . $UseAutoNum;
						}
						//Form the RegNo 
						$NewRegNo = str_replace(array("?FAC?", "?DEPT?", "?PROG?", "?SESNAME?", "?SES?", "?SCH?", "?AUTONUM?"), array($FacAbbr, $DeptAbbr, $ProgAbbr, $SesName, $SesAbbr, $SchAbbr, $UseAutoNum), $RegoFormat);
					} while (is_array($dbo->SelectFirstRow("studentinfo_tb", "", "(RegNo = '$NewRegNo' OR JambNo = '$NewRegNo') AND RegID = $RegID")));
					$autogenreg = "TRUE";
				} else {
					return "####"; //Already Has a RegNo
				}
			}

			//If a new regno exist - update student records
			if (isset($NewRegNo) && trim($NewRegNo) != "") {
				//Update Student RegNo 
				$dbo->Bigin();

				//Update Student accesscode det 
				$accescod = $dbo->Updatedbtb("accesscode_tb", array("JambNo" => $NewRegNo), "JambNo = '$RegNo' AND RegID = $RegID");
				//update in course reg
				$coursereg = $dbo->Updatedbtb("coursereg_tb", array("RegNo" => $NewRegNo), "RegNo = '$RegNo'");
				//update in order 
				$order = $dbo->Updatedbtb("order_tb", array("RegNo" => $NewRegNo), "RegNo = '$RegNo'");
				//update in order_ex
				$order = $dbo->Updatedbtb("order_ex_tb", array("RegNo" => $NewRegNo), "RegNo = '$RegNo'");
				//update in payment history
				$payhist = $dbo->Updatedbtb("payhistory_tb", array("RegNo" => $NewRegNo), "RegNo = '$RegNo'");
				//update in result tb
				$result = $dbo->Updatedbtb("result_tb", array("RegNo" => $NewRegNo), "RegNo = '$RegNo'");
				//update in screaning screening_tb
				$screening = $dbo->Updatedbtb("screening_tb", array("RegNo" => $NewRegNo), "RegNo = '$RegNo'");
				//update in wallet payment history
				$wallet = $dbo->Updatedbtb("wallet_tb", array("RegNo" => $NewRegNo), "RegNo = '$RegNo'");
				//update in notification
				$wallet = $dbo->Updatedbtb("notification_tb", array("RegNo" => $NewRegNo), "RegNo = '$RegNo'");
				//*************************************** */
				//find a way to update CandidateStr in cbt_schedule_tb
				//*************************************** */

				$passp = trim($StudDet['Passport']);
				$newpassp = $passp;
				$rname = true;
				if ($passp != "") {
					$passp = ResolvePassport($passp);
					$passp = explode("?", $passp);
					$passp = $passp[0];
					$passpu = "../../" . $passp;
					//echo $passpu;
					if (file_exists($passpu)) {
						$pregNo = str_replace("/", "_", $NewRegNo);
						$patharr = explode("/", $passp);
						$names = array_pop($patharr);
						$newpassp = implode("/", $patharr) . "/" . $pregNo . ".jpg";

						$newpasspu = "../../" . $newpassp;
						$rname = rename($passpu, $newpasspu);
					}
				}
				//Update Student student det 
				$dataupdate = $RegCleared === true ? ["RegNo" => "", "JambNo" => $NewRegNo, "AutoNum" => $UseAutoNum, "Passport" => $newpassp, "AutoGenReg" => $autogenreg] : array("RegNo" => $NewRegNo, "AutoNum" => $UseAutoNum, "Passport" => $newpassp, "AutoGenReg" => $autogenreg);
				$studreg = $dbo->Updatedbtb("studentinfo_tb", $dataupdate, "id = " . $StudDet['id']);
				if (!is_array($coursereg) || !is_array($order)  || !is_array($payhist)  || !is_array($result)  || !is_array($screening)  || !is_array($studreg)  || !is_array($wallet)  || !is_array($accescod) || $rname == false) {
					//update files
					/* $arr = [$RegNo];
				$folder = ["JambResult","Origin","Waec"];
				foreach($arr as $rrr){
					$rrr = str_replace("/","_",$rrr);
				foreach($folder as $fd){
				if(file_exists("../../../../../../".$_POST['SubDir']."Files/UserImages/{$fd}/{$rrr}.jpg")){
					rename("../../../../../../".$_POST['SubDir']."Files/UserImages/{$fd}/{$rrr}.jpg","../../../../../../".$_POST['SubDir']."Files/UserImages/{$fd}/{$regfile}.jpg");
					}
				}
				} */
					$dbo->Rollback();
					return "#####"; //Error Updating generated RegNo
				} else {
					$dbo->Commit();
					return array($NewRegNo, $newpassp);
					//$totupdate += $coursereg[1] + $order[1] + $payhist[1] + $result[1] + $screening[1];
				}
			}
		} else {
			return "###"; //student not exist
		}
	} else { //cannot get school deteails
		return "#";
	}
}

//Generate Unique Random RegNo
function AutoGenRegNoRand($prefix = "")
{
	global $dbo;
	$NewRegNo = ""; //strtoupper(substr($_POST[$i.'_4'],0,2))
	do {
		//generate a random number
		$NewRegNo = $prefix . mt_rand(1000000, 9999999);
		$chk = $dbo->SelectFirstRow("studentinfo_tb", "id", "RegNo='" . $dbo->SqlSafe($NewRegNo) . "' OR JambNo='" . $dbo->SqlSafe($NewRegNo) . "'");
	} while (is_array($chk) || $NewRegNo == "");
	return $NewRegNo;
}


//function to load a staff courses in cportal result upload
function LoadStaffCourses($loadcond, $ses = NULL, $showdept = false)
{
	//extract($_POST);
	global $dbo;
	if (!isset($ses) || is_null($ses)) {
		$curses = CurrentSes();
		$ses = $curses['SesID'];
	}
	//$loadcond = !isset($loadcond)?"c.Lvl = " .$lvl." AND c.Sem = ".$sem." AND c.DeptID = ".$dept." AND c.StudyID = ".$stid:
	if (isset($loadcond)) {
		$clsstb = $showdept ? ",studentclass_tb sc" : "";
		$clssfeild = $showdept ? ",sc.Name as ClassName,sc.ID as ClassID" : "";

		$courses = $dbo->Select("course_tb c,fac_tb f, dept_tb d, study_tb s, session_tb se, programme_tb p, schoollevel_tb l, semester_tb sem" . $clsstb, "c.CourseCode,c.Title,c.CH,c.CourseID,c.StudyID,c.Lvl,c.Sem,c.DeptID, p.ProgName, s.Name, se.SesID, se.SesName,f.FacID, f.FacName, d.DeptID as Dept, d.DeptName,l.Name as Level,sem.Sem as Semester,sem.Descr as SemName,IF(p.Abbr = '',p.ProgName,p.Abbr) as Abbr" . $clssfeild, "(" . $loadcond . ") AND f.FacID = d.FacID AND d.DeptID = p.DeptID AND p.ProgID = c.DeptID AND c.Lvl = l.Level AND l.SchoolTypeID = (select Type from school_tb limit 1) AND l.StudyID = c.StudyID AND se.SesID = $ses AND sem.Num = c.Sem AND s.ID = c.StudyID");
		//echo "course_tb c,fac_tb f, dept_tb d, study_tb s, session_tb se, programme_tb p, schoollevel_tb l, semester_tb sem","c.CourseCode,c.Title,c.CH,c.CourseID,c	.StudyID,c.Lvl,c.Sem,c.DeptID, p.ProgName, s.Name, se.SesID, se.SesName,f.FacID, f.FacName, d.DeptID as Dept, d.DeptName,l.Name as Level,sem.Sem as Semester",$loadcond." AND f.FacID = d.FacID AND d.DeptID = p.DeptID AND p.ProgID = c.DeptID AND c.Lvl = l.Level AND l.SchoolTypeID = (select Type from school_tb limit 1) AND l.StudyID = c.StudyID AND se.SesID = $ses AND sem.,ID = c.Sem AND s.ID = c.StudyID";
		//return;
		$courseset = COURSE();
		$alowdupl = $courseset['DuplicateCourse'] == 'TRUE' ? true : false;
		$duplicatehtml = '';
		$seenCCode = [];
		$seenOther = [];
		$mainhtml = '';
		if (is_array($courses)) {
			if ($courses[1] > 0) {
				$mainhtml .= __TextBoxGroup("width:calc(100% - 20px);margin:5px auto") . __TextBox("title=Filter,style=width:calc(100% - 6px),id=coursetb_filtertb,textchange=TextBox.Filter(this),logo=filter,required=false") . ___TextBoxGroup();
				$mainhtml .= '<div style="overflow:auto;width:100%;padding-bottom:30px;height:calc(100% - 65px)">';
				$mainhtml .= __Table("rowselect=true,style=width:95%;margin:auto;font-size:0.7em;margin:auto,id=coursetb,onselect=Exams.ResultUpload.Load,onunselect=,multiselect=false,data-type=table");
				//$rtnstr .= __TRecord(array(""),"id=0");
				if ($showdept) {
					$mainhtml .= __THeader(array("DEPT", "TITLE", "LEVEL"));
				} else {
					$mainhtml .= __THeader(array("CODE", "TITLE", "CH"));
				}
				$cnt = 1;
				while ($course = $courses[0]->fetch_array()) {
					$trid = $course['CourseID'];
					//get the former old course if exist
					$oldcourse = $dbo->SelectFirstRow("course_tb", "", "Former=" . $trid);
					if (is_array($oldcourse)) { //if old course exist
						$oldcCode = $oldcourse['CourseCode'];
						$oldcCH = (int)$oldcourse['CH'];
						$oldtitle = $oldcourse['Title'];
						if (trim(strtolower($oldcCode)) != trim(strtolower($course[0]))) {
							$course[0] = $course[0] . " / " . $oldcCode;
						}

						if (trim(strtolower($oldtitle)) != trim(strtolower($course[1]))) {
							$course[1] = $course[1] . " / " . $oldtitle;
						}

						if ((int)$oldcCH != (int)$course[2]) {
							$course[2] = $course[2] . "/" . $oldcCH;
						}
					}
					if ($showdept) {
						//$course['ProgName']
						$mainhtml .= __TRecord(array($course['Abbr'], '<div style="text-align:left">' . str_replace(" ", "&nbsp;", $course[0]) . "(" . $course[2] . ') - ' . $course[1] . '</div>', '<div style="text-align:left">' . $course['Level'] . " (" . $course['ClassName'] . ")" . " " . $course['SemName'] . '</div>'), "data-id={$trid},id={$trid},data-class-id=" . $course['ClassID'] . ",data-class-name=" . CleanText($course['ClassName']));
					} else {
						$mainhtml .= __TRecord(array(str_replace(" ", "&nbsp;", $course[0]), '<div style="text-align:left">' . $course[1] . '</div>', $course[2]), "data-id={$trid},id={$trid}"); //"data-id=$reglw"
					}
					//get fac and dept det 
					//$facDept = $dbo->SelectFirstRow("fac_tb f, dept_tb d, programme_tb p","f.FacID,f.FacName,d.DeptID,d.DeptName,p.ProgID,p.ProgName","f.DeptID = d.DeptID and p.DepID = d.DeptID and p.ProgID = ".$course['DeptID']);
					$SesID = $course['SesID'];
					$SesName = rawurlencode($course['SesName']);
					$StudyID = $course['StudyID'];
					$StudyName = rawurlencode($course['Name']);
					$FacID = $course['FacID'];
					$FacName = rawurlencode($course['FacName']);
					$DeptID = $course['Dept'];
					$DeptName = rawurlencode($course['DeptName']);
					$ProgName = rawurlencode($course['ProgName']);
					$LvlName = rawurlencode($course['Level']);
					$Lvl = $course['Lvl'];
					$SemID = $course['Sem'];
					$SemName = rawurlencode($course['Semester']);
					$ProgID = $course['DeptID'];

					$cdett = "rstudstudy=$StudyID:$StudyName&rstudfac=$FacID:$FacName&rstuddept=$DeptID:$DeptName&rstudprog=$ProgID:$ProgName&rstudlvl=$Lvl:$LvlName&semest=$SemID:$SemName";
					if ($showdept) {
						$ClassID = $course['ClassID'];
						$ClassName = $course['ClassName'];
						//$cdett .=  "&classid=$ClassID:$ClassName";
					}
					Hidden($trid . "_det", $cdett);
					$exist = array_search(trim(strtolower(str_replace(" ", "", $course[0]))), $seenCCode);
					if ($exist !== FALSE && $alowdupl == false && $seenOther[$exist][1] == (int)$course[2] && $seenOther[$exist][3] == (int)$course['DeptID'] && (!isset($course['ClassID']) || (int)$seenOther[$exist][4] == (int)$course['ClassID'])) { //if duplicate exist

						$duplicatehtml .= __TRecord(array($cnt, strtoupper($seenOther[$exist][0] . ":" . $seenOther[$exist][2] . " ({$seenOther[$exist][1]})"), strtoupper($course['CourseID'] . ":" . $course[0] . " ({$course[2]})")), "style=text-align:left");
						$cnt++;
					}
					$seenCCode[] = trim(strtolower(str_replace(" ", "", $course[0])));
					$seenOther[] = [$course['CourseID'], (int)$course[2], $course[0], $course['DeptID'], $course['ClassID']];
				}
				$mainhtml .= ___Table();
				$mainhtml .= '</div>';
				if (trim($duplicatehtml) != "") { //if duplicate 
					$rec = '
			<div class="altColor" style="font-weight:bold;padding:5px"><i class="fa fa-exclamation-triangle"></i>DUPLICATE COURSE<small>(s)</small> FOUND</div>
			<div class="rptbx" style="height:auto;width:auto"><div class="rptrow">
    <div style="width:80%" class="rptitem">' . ($cnt - 1) . ' Duplicate<small>(s)</small></div>
    <div style="width:20%;text-align:center;cursor:pointer" onclick="_(\'dupltbcont2\').ToggleShowHide()" class="altColor2Hover rptitem" title="View Details"><i class="fa fa-ellipsis-h"></i></div>
    <div style="clear:both"></div>
</div>
<div id="dupltbcont2" style="display:none">
    ';
					echo $rec;
					Table("rowselect=true,style=width:250px;font-size:0.7em;margin:5px auto,id=duplcoursetb,multiselect=false,data-type=table");
					THeader(array("#", "OLD", "NEW"));
					echo $duplicatehtml;
					_Table();
					echo "</div>";

					echo "</div>";

					Note("style=text-transform:none");
					echo 'You can automatically resolve Duplicate Course Issue (Update all occurence of the Old Courses to New Courses in Student Course Registration, Result and Staff assigned Courses) in <br /><a href="javascript:Page.OpenByTabName(\'MngCourse\')">Course Management Module</a>';
					_Note();
					SmallButton("logo=undo,title=Reload,onclick=Exams.ResultUpload.CourseReload()");
				} else {
					echo $mainhtml;
				}
			} else {
				Icon("exclamation-triangle");
				echo " NO COURSE FOUND";
			}
		} else {
			Icon("exclamation-triangle");
			echo " INTERNAL ERROR: CANNOT LOAD COURSES ";
		}
	} else {
		Icon("exclamation-triangle");
		echo " INVALID SELECTION";
	}
}

//function to load the style sheet for printing
function PrintStyle()
{
	$style = <<<sss
<style type="text/css"  >
.topic{
	/*background:#999999;*/
	text-align:center;
	font-size:1.2em;
	font-weight:600;
	border-bottom:#CCCCCC solid 2px;
	text-transform:uppercase;	
}

.title, .value{
	font-weight:600;
	width:50%;
}
.value{
	font-weight:normal;
}
table{
	width:95%; margin:auto; border-collapse:collapse; margin-top:15px;align:center; font-weight:500;
}

tr,td,th{
	border:#D5D5D5 thin solid;
	
	padding:5px;
	
}
th{text-transform:uppercase; text-align:center;background-color:rgba(0,0,0,.06);
	}
.err{
   background-color:rgba(0,0,0,.06);
	}

.inv{
   color:#555;
	}

td.title{
	padding-left:20px;
	vertical-align:top;
	text-align:start;
	
}
#passp{
	width:200px;
	height:200px;
	display:block;
	margin-left:auto;
	margin-right:auto;
	margin-bottom:15px;
	margin-top:8px;
	border:#CCCCCC solid thin;	
}

.linebottom{
	border-bottom:#CCCCCC solid 2px;
}

.secondColor{
	color:;
}

body{
	font-family:"Segoe UI Light","Segoe UI" ;
	font-weight:lighter;
	margin:0px;
	padding:0px;
	margin-bottom:50px;
	
	background-color:;
	font-size:0.8em;
}

#TitleDiv{
	width:100%;
	height:auto;
	margin-top:0px;
}

#TitleDiv #InnerDiv{
	min-width:100px;
	width:auto;
	margin:auto;
	height:auto;
	background-color:;	
	
}

#TitleDiv #InnerDiv img{
	display:block;
	width:150px;
	height:150px;
	background-color:;
	margin:auto;
}

#TitleDiv #InnerDiv #TitleBox{
	display:block;
	background-color:;
	text-align:center;
}

#TitleDiv #InnerDiv #TitleBox #SchoolName{
	font-size:1.5em;
	text-transform:uppercase;
	font-weight:normal;
}

#TitleDiv #InnerDiv #TitleBox #SchoolAddress{
	font-size:1.2em;
	
	
}

#TitleDiv #InnerDiv #TitleBox #payTitle{
	font-size:1.3em;
	text-transform:uppercase;
	font-weight:normal;
}

.InfoDiv, #AnalDiv{
	width:calc(95% - 20px);
	margin:auto;
	border:#D5D5D5 thin solid;
	background:rgba(0,0,0,.06);
	margin-top:10px;
	height:auto;
	border-radius:0px;
	font-size:1em;
	padding:10px;
	font-weight:normal;
	overflow:hidden;
}

.InfoDiv .detailSide{
	width:60%;
	float:left;
}

.InfoDiv #passp{
	width:170px;
	height:170px;
	float:right;
	
	background-color:;
	margin:7px;
}

.InfoDiv #passp img{
	width:inherit;
	height:inherit;
}

#AnalDiv{
	background:none;
}

.InfoDiv .IndItem, .IndItemHeader{
	width:100%;
	height:auto;
	padding-top:4px;
	padding-bottom:4px;
	border-bottom:#D5D5D5 thin solid;
}
.IndItemHeader{
  border-bottom:#AAA 2px solid;
  background-color:rgba(255,255,255,.01);
  text-align:center;
  text-transform:uppercase;
  font-weight:bold;
}

.InfoDiv .IndItem .itemname{
	width:35%;
	text-indent:10px;
	display: inline-block;
	vertical-align:middle;
	text-transform:uppercase;
}

.InfoDiv .IndItem .itemvalue{
	width:60%;
	margin-left:10px;
	display: inline-block;
	vertical-align:middle;
	font-weight:600;
	text-transform:uppercase;
}

#AnalDiv{
	border-collapse:collapse;
	/*border:inherit;*/
	
}

#AnalDiv th{
	text-align:center
}

#AnalDiv td{
	text-indent:10px
}

#AnalDiv strong{
	font-weight:bolder;
}

.errl{margin-top:30px; text-align:center; font-size:2.5em;	
}
body{
font-family: 'Segoe UI Light', 'Segoe UI Semilight', 'Segoe UI Semibold', 'Segoe UI', 'Eras Light ITC', Calibri
	}
.bx{
    display:inline-block;border:#D5D5D5 thin solid;
	background-color:rgba(255,255,255,.7);margin-right:10px; vertical-align:top
	}
</style>
sss;
	echo $style;
}

//function to display info on slip
function PrintInfoBox()
{
	echo "<div class=\"InfoDiv\">";
}
function _PrintInfoBox()
{
	echo "</div>";
}

function PrintInfo($title, $value)
{
	echo "<div class=\"IndItem\" >";
	echo "<div class=\"itemname\" >$title</div>";
	echo "<div class=\"itemvalue\" >$value</div>";
	echo "</div>";
}

function PrintInfoTitle($title)
{
	echo "<div class=\"IndItemHeader\" >";
	echo $title;
	echo "</div>";
}

function PrintBox($size = 4)
{
	$size = floor($size * 25) - 2;
	echo "<div class=\"bx\" style=\"width:{$size}%\">";
}
function _PrintBox()
{
	echo "</div>";
}

//function to get print header 
function PrintHeader($title, $school)
{
	$school = !isset($school) ? GetSchool("logo,Abbr,Name,ShortAddr") : $school;
	$logo = _CONFIGDIR_ . $school['logo'];
	$abbr = $school['Abbr'];
	$nm = $school['Name'];
	$shtabbr = $school['ShortAddr'];
	$header = <<<sss
<div id="TitleDiv">
   <div id="InnerDiv">
      <img src="{$logo}" name="SchoolImg" alt="{$abbr}"  />
      <div id="TitleBox">
        <div id="SchoolName">{$nm}</div>
         <div id="SchoolAddress">{$shtabbr}</div>
         <div id="payTitle">{$title}</div>
      </div>
   </div>
</div>
sss;
	echo $header;
}

//function to form semester cond string
function SemesterCondition($semfield)
{
	global $dbo;
	//Get all the semester in and form if cond
	$allsem = $dbo->Select("semester_tb", "Num,Sem");
	$ifsemcond = "";
	if (is_array($allsem) && $allsem[1] > 0) {
		while ($indsem = $allsem[0]->fetch_assoc()) {
			$ifsemcond .= "IF($semfield = {$indsem['Num']},'" . strtoupper($indsem['Sem']) . "',";
		}
		$ifsemcond .= "'FULL'" . str_repeat(")", $allsem[1]);
	}
	return $ifsemcond;
}
//function to load the resultinfo
function LoadPaymentAppr($deptCond, $limit = 500, $searchval = "", $filter = 0)
{
	//echo "sss";
	global $dbo;
	global $UID;
	$searchvalp = $searchval;
	$filterCond = "";
	if ($filter == 1) {
		//approved only 
		$filterCond = "AND od.Paid=1";
	} else if ($filter == 2) {
		$filterCond = "AND od.Paid=0";
	}
	$dump = array();

	$tb = "order_tb od, session_tb s, schoollevel_tb l, study_tb sy";
	//$tb2 = "order_tb od, pstudentinfo_tb st, fac_tb f, dept_tb d, programme_tb p, session_tb s, schoollevel_tb l, item_tb it, study_tb sy";
	$semcond = SemesterCondition("od.Sem"); //IF(od.Sem = 1,'FIRST',IF(od.Sem = 2,'SECOND','FULL'))
	$fields = "od.*,s.SesName,l.Name as LvlName, $semcond as Semester, sy.Name as StudyName, FORMAT(od.Amt,2) as FAmt, IF(od.SemPart = 1,'PART',IF(od.SemPart = 2,'COMPLETE','FULL')) as PayPol, DATE_FORMAT(od.RegDate, '%M %d %Y') as ODate";

	$cond = $deptCond . " AND od.Ses = s.SesID AND l.Level = od.Lvl AND l.SchoolTypeID = sy.SchoolType AND l.StudyID = sy.ID AND od.Channel = 'OFFLINE' AND od.Info LIKE CONCAT('%\"StudyID\":\"',sy.ID,'\"%')$filterCond ";

	/* {"Name":"Ubom Mercy Effiong","ProgID":"10","ProgName":"Performing Arts","DeptID":"10","DeptName":"Performing (Theatre Arts)","FacID":"3","FacName":"Arts","StartSes":"8","ModeOfEntry":"1","StudyID":"5","RegID":"1","PayName":"AKSU ACCEPTANCE FEE"} */




	//exit("SELECT $fields FROM $tb WHERE $cond ORDER BY ID DESC LIMIT $limit ");
	//get the result info 
	$rstinfos = $dbo->RunQuery("SELECT $fields FROM $tb WHERE $cond ORDER BY ID DESC LIMIT $limit ");
	// exit("SELECT $fields FROM $tb WHERE $cond ORDER BY ID DESC LIMIT $limit ");
	// $rstinfos = $dbo->RunQuery("(SELECT $fields FROM $tb WHERE $cond) UNION (SELECT $fields FROM $tb2 WHERE $cond) ORDER BY ID DESC LIMIT $limit ");
	//          $rstinfos = $dbo->Select($tb,$fields,$cond);
	//echo "resultapprove_tb ra, fac_tb f, dept_tb d, programme_tb p, course_tb c, session_tb s, study_tb st, schoollevel_tb l,semester_tb se","ra.*,f.FacID,d.DeptID,s.SesName,st.Name as StudyName,f.FacName,d.DeptName,p.ProgName,l.Name as LvlName,se.Sem as Semester, CONCAT(c.Title,' (',c.CourseCode,')') as CourseName, ra.ID as RSID",$deptCond." AND f.FacID = d.FacID AND d.DeptID = p.DeptID AND p.ProgID = ra.ProgID AND ra.CourseID = c.CourseID AND ra.Ses = s.SesID AND st.ID = ra.StudyID AND st.SchoolType = (Select Type from school_tb limit 1) AND l.Level = ra.Lvl AND l.SchoolTypeID = st.SchoolType AND l.StudyID = st.ID AND se.ID = ra.Sem ORDER BY ra.ID DESC LIMIT $limit";
	// echo "resultapprove_tb ra, fac_tb f, dept_tb d, programme_tb p","ra.*,f.FacID,d.DeptID","(".$deptCond.") AND f.FacID = d.FacID AND d.DeptID = p.DeptID AND p.ProgID = ra.ProgID ORDER BY ra.ID DESC LIMIT 500";
	if (is_array($rstinfos)) {
		if ($rstinfos[1] > 0) {
			//( [rstudstudy] => 5 [rstudfac] => 1 [rstuddept] => 3 [rstudprog] => 3 [rstudlvl] => 1 [semest] => 1 [sestb] => 1 [rcourse] => 1 )
			$fieldarr = array("ID", "Name", "SesName", "StudyName", "FacName", "ProgName", "LvlName", "Semester", "PayName", "ReceiptNum", "ODate", "FAmt", "Paid");
			$cnt = 1;
			while ($rstinfo = $rstinfos[0]->fetch_array()) {
				//$rstinfo['Paid'] = $rstinfo['Paid'] == "TRUE"?1:0;
				$cnt++;
				$rw = array();
				$searchval = strtolower($searchval);
				$searchvalarr = explode(" ", $searchval);
				if (trim($rstinfo['Info']) == "") {
					$rstinfo['Info'] = '{"Name":"Unknown Student","ProgID":"0","ProgName":"Unknown","DeptID":"0","DeptName":"Unknown","FacID":"0","FacName":"Unknown","StartSes":"0","ModeOfEntry":"0","StudyID":"0","RegID":"1","PayName":"Unknown"}';
				}
				$Info = json_decode($rstinfo['Info'], true);
				$rstinfo = array_merge($rstinfo, $Info);
				//$replarr = array();

				// $replarr[] = '<strong class="altColor">'.strip_tags($searcc).'</strong>';	
				//}
				foreach ($fieldarr as $fieldName) {

					$strdis = strtolower($rstinfo[$fieldName]);
					if ($fieldName == "Semester" && $strdis != "full") $strdis = $strdis . " (" . strtolower($rstinfo['PayPol']) . ")";
					if ($fieldName == "Name") $strdis = $strdis . " (" . strtolower($rstinfo['RegNo']) . ")";
					foreach ($searchvalarr as $searcc) {
						if (strpos($strdis, $searcc) !== false) {
							$strdis = str_replace($searcc, '<strong class="altColor">' . strip_tags($searcc) . '</strong>', $strdis);
							break;
						}
					}
					$rw[] = $strdis;
				}
				//$rw[] =  $status;
				$rw["logo"] =  "*ellipsis-h";
				$rw["info"] =  "View/Delete Request";
				$rw["Action"] =  "Payment.PayApproval.View('{$rstinfo['ID']}','" . strtoupper(str_replace("'", "\'", "<ul><li>" . $rstinfo['Name'] . "</li>" . "<li>" . $rstinfo['RegNo'] . "</li>" . "<li>" . $rstinfo['PayName'] . "</li>" . "<li>" . $rstinfo['LvlName'] . " " . $rstinfo['Semester'] . "</li></ul>")) . "',$cnt)";
				//$dump[] = array($rstinfo['SesName'],$rstinfo['StudyName'],$rstinfo['FacName'],$rstinfo['DeptName'],$rstinfo['ProgName'],$rstinfo['LvlName'],$rstinfo['Semester'],$rstinfo['CourseName'],$rstinfo['RSID'],$status,"logo"=>"*eye","info"=>"View/Print","Action"=>"Exams.Approval.View('rstudstudy=".$rstinfo['StudyID']."&rstudfac=".$rstinfo['FacID']."&rstuddept=".$rstinfo['DeptID']."&rstudprog=".$rstinfo['ProgID']."&rstudlvl=".$rstinfo['Lvl']."&semest=".$rstinfo['Sem']."&sestb=".$rstinfo['Ses']."&rcourse=".$rstinfo['CourseID']."')");
				$dump[] = $rw;
			}
		}
	}
	//$fieldarr = array("StudName","SesName","StudyName","FacName","DeptName","ProgName","LvlName","Semester","ItemName","FAmt","Paid");
	if (count($dump) > 0) {
		$header = array(
			"-PayAppOrderID" => "ORDERID",
			"*Payyee" => "PAYEE",
			"*PAppSesName" => "SESSION",
			"*StudyIDpap" => "STUDY TYPE",
			"*Facpap" => "FACULTY/SCHOOL",
			"*ProgIDpap" => "PROGRAMME",
			"*Lvlpap" => "LEVEL",
			"*Sempap" => "POLICY",
			"*PApprPayItem" => "PAY TYPE",
			"*PApprReceiptNum" => "RECEIPT",
			"*PApprPayDate" => "DATE",
			"*PAppAmt" => "AMOUNT",
			"*Payappr" => array("APPROVED", "YES|NO")
		);
		SpreadSheet("rowselect=false,style=width:calc(100% - 16px);margin:auto;margin-top:6px;margin-bottom:6px,id=payapprssb,multiselect=false,cellfocus=,cellblur=,cellkeypress=,dynamiccolumn=false,dynamicrow=false,minrow=-1,readonly=Payyee;PAppSesName;StudyIDpap;Facpap;ProgIDpap;Lvlpap;Sempap;PApprPayItem;PAppAmt;PayAppOrderID;PApprPayDate,rowdelete=false,allowclear=false,trimtext=<strong class=\"altColor\">;</strong>;<strong class=\"altcolor\">", $header, $dump);
		Hidden("parampayapp", "UID=$UID&limit=$limit&val=$searchvalp&filter=$filter");
	} else {
		Info("EMPTY SET", "No Offline Payment Found", "trash", "altColor");
	}
}

//function to load the resultinfo
function LoadResultAppr($deptCond, $limit = 500, $searchval = "", $filter = 0)
{
	//echo "sss";
	global $dbo;
	global $UID;
	$searchvalp = $searchval;
	$filterCond = "";
	$sch = GetSchool('SemLabel');
	if ($filter == 1) {
		//approved only 
		$filterCond = "AND ra.Status='TRUE'";
	} else if ($filter == 2) {
		$filterCond = "AND ra.Status='FALSE'";
	}
	$dump = array();
	//get the result info 
	$rstinfos = $dbo->Select("resultapprove_tb ra, fac_tb f, dept_tb d, programme_tb p, course_tb c, session_tb s, study_tb st, schoollevel_tb l,semester_tb se", "ra.*,f.FacID,d.DeptID,s.SesName,st.Name as StudyName,f.FacName,d.DeptName,p.ProgName,l.Name as LvlName,se.Sem as Semester, CONCAT(c.Title,' (',c.CourseCode,' - ',c.CH,')') as CourseName, ra.ID as RSID,c.CourseCode,c.Title,c.CourseID,c.CH", $deptCond . " AND f.FacID = d.FacID AND d.DeptID = p.DeptID AND p.ProgID = ra.ProgID AND ra.CourseID = c.CourseID AND ra.Ses = s.SesID AND st.ID = ra.StudyID AND st.SchoolType = (Select Type from school_tb limit 1) AND l.Level = ra.Lvl AND l.SchoolTypeID = st.SchoolType AND l.StudyID = st.ID AND se.Num = ra.Sem $filterCond ORDER BY ra.ID DESC LIMIT $limit");
	//echo "resultapprove_tb ra, fac_tb f, dept_tb d, programme_tb p, course_tb c, session_tb s, study_tb st, schoollevel_tb l,semester_tb se","ra.*,f.FacID,d.DeptID,s.SesName,st.Name as StudyName,f.FacName,d.DeptName,p.ProgName,l.Name as LvlName,se.Sem as Semester, CONCAT(c.Title,' (',c.CourseCode,')') as CourseName, ra.ID as RSID",$deptCond." AND f.FacID = d.FacID AND d.DeptID = p.DeptID AND p.ProgID = ra.ProgID AND ra.CourseID = c.CourseID AND ra.Ses = s.SesID AND st.ID = ra.StudyID AND st.SchoolType = (Select Type from school_tb limit 1) AND l.Level = ra.Lvl AND l.SchoolTypeID = st.SchoolType AND l.StudyID = st.ID AND se.ID = ra.Sem ORDER BY ra.ID DESC LIMIT $limit";
	// echo "resultapprove_tb ra, fac_tb f, dept_tb d, programme_tb p","ra.*,f.FacID,d.DeptID","(".$deptCond.") AND f.FacID = d.FacID AND d.DeptID = p.DeptID AND p.ProgID = ra.ProgID ORDER BY ra.ID DESC LIMIT 500";
	if (is_array($rstinfos)) {
		if ($rstinfos[1] > 0) {
			//( [rstudstudy] => 5 [rstudfac] => 1 [rstuddept] => 3 [rstudprog] => 3 [rstudlvl] => 1 [semest] => 1 [sestb] => 1 [rcourse] => 1 )
			while ($rstinfo = $rstinfos[0]->fetch_array()) {
				$rstinfo['Status'] = $rstinfo['Status'] == "TRUE" ? 1 : 0;
				$rstinfo['Editable'] = $rstinfo['Editable'] == "TRUE" ? 0 : 1;
				$cid = $rstinfo['CourseID'];
				//get the old course
				$oldcourse = $dbo->SelectFirstRow("course_tb", "", "Former=" . $cid);
				if (is_array($oldcourse)) { //if old course exist
					$oldcourseid = (int)$oldcourse['CourseID'];
					$oldcCode = $oldcourse['CourseCode'];
					$oldcCH = (int)$oldcourse['CH'];
					$oldtitle = $oldcourse['Title'];
					if (trim(strtolower($oldcCode)) != trim(strtolower($rstinfo['CourseCode']))) {
						$rstinfo['CourseCode'] = $rstinfo['CourseCode'] . " / " . $oldcCode;
					}

					if (trim(strtolower($oldtitle)) != trim(strtolower($rstinfo['Title']))) {
						$rstinfo['Title'] = $rstinfo['Title'] . " / " . $oldtitle;
					}

					if ((int)$oldcCH != (int)$rstinfo['CH']) {
						$rstinfo['CH'] = $rstinfo['CH'] . "/" . $oldcCH;
					}
					$rstinfo['CourseName'] = $rstinfo['Title'] . " (" . $rstinfo['CourseCode'] . " - " . $rstinfo['CH'] . ")";
				}
				$fieldarr = array("SesName", "StudyName", "FacName", "DeptName", "ProgName", "LvlName", "Semester", "CourseName", "RSID", "Editable", "Status");
				$rw = array();
				$searchval = strtolower($searchval);
				$searchvalarr = explode(" ", $searchval);
				//$replarr = array();

				// $replarr[] = '<strong class="altColor">'.strip_tags($searcc).'</strong>';	
				//}
				foreach ($fieldarr as $fieldName) {

					$strdis = strtolower($rstinfo[$fieldName]);
					foreach ($searchvalarr as $searcc) {
						if (strpos($strdis, $searcc) !== false) {
							$strdis = str_replace($searcc, '<strong class="altColor">' . strip_tags($searcc) . '</strong>', $strdis);
							break;
						}
					}
					$rw[] = $strdis;
				}
				//$rw[] =  $status;
				$rw["logo"] =  "*print";
				$rw["info"] =  "View/Print";
				$rw["Action"] =  "Exams.Approval.View('rstudstudy=" . $rstinfo['StudyID'] . "&rstudfac=" . $rstinfo['FacID'] . "&rstuddept=" . $rstinfo['DeptID'] . "&rstudprog=" . $rstinfo['ProgID'] . "&rstudlvl=" . $rstinfo['Lvl'] . "&semest=" . $rstinfo['Sem'] . "&sestb=" . $rstinfo['Ses'] . "&rcourse=" . $rstinfo['CourseID'] . "')";
				//$dump[] = array($rstinfo['SesName'],$rstinfo['StudyName'],$rstinfo['FacName'],$rstinfo['DeptName'],$rstinfo['ProgName'],$rstinfo['LvlName'],$rstinfo['Semester'],$rstinfo['CourseName'],$rstinfo['RSID'],$status,"logo"=>"*eye","info"=>"View/Print","Action"=>"Exams.Approval.View('rstudstudy=".$rstinfo['StudyID']."&rstudfac=".$rstinfo['FacID']."&rstuddept=".$rstinfo['DeptID']."&rstudprog=".$rstinfo['ProgID']."&rstudlvl=".$rstinfo['Lvl']."&semest=".$rstinfo['Sem']."&sestb=".$rstinfo['Ses']."&rcourse=".$rstinfo['CourseID']."')");
				$dump[] = $rw;
			}
		}
	}
	if (count($dump) > 0) {
		$header = array(
			"*Sesap" => "SESSION",
			"*StudyIDap" => "STUDY TYPE",
			"*Facap" => "FACULTY",
			"*Deptap" => "DEPARTMENT",
			"*ProgIDap" => "PROGRAMME",
			"*Lvlap" => "LEVEL",
			"*Semap" => strtoupper($sch['SemLabel']),
			"*Coursesap" => "COURSE",
			"*Rsid" => "RSID",
			"*Rstedit" => array("LOCK", "YES|NO"),
			"*Rstappr" => array("APPROVED", "YES|NO")
		);
		SpreadSheet("rowselect=false,style=width:calc(100% - 16px);margin:auto;margin-top:6px;margin-bottom:6px,id=rstapprssb,multiselect=false,cellfocus=,cellblur=,cellkeypress=,dynamiccolumn=false,dynamicrow=false,minrow=-1,readonly=Sesap;StudyIDap;Facap;Deptap;ProgIDap;Lvlap;Semap;Coursesap;Rsid,rowdelete=false,trimtext=<strong class=\"altColor\">;</strong>;<strong class=\"altcolor\">", $header, $dump);
		Hidden("paramrstapp", "UID=$UID&limit=$limit&val=$searchvalp&filter=$filter");
	} else {
		Info("EMPTY SET", "No Result Found", "trash", "altColor");
	}
}
//function to get all course less than the sent level in a particular Prog
function GetCourses($ProgID = 0, $MaxLvl = 20, $MaxSem = 2, $SesID = 0, $lower = true)
{

	$rtn = array();
	$ProgID = $ProgID > 0 ? "DeptID = $ProgID" : "1=1";
	$current = array();
	$old = array();
	global $dbo;
	if ($SesID == 0) {
		$ses = CurrentSes();
		$SesID = $curses['SesID'];
	}
	if ($lower) {
		$course = $dbo->RunQuery("SELECT * FROM course_tb WHERE (Lvl < $MaxLvl OR (Lvl = $MaxLvl AND Sem <= $MaxSem)) AND $ProgID AND StartSesID <= $SesID AND (EndSesID >= $SesID OR EndSesID = 0)");
	} else {
		$course = $dbo->RunQuery("SELECT * FROM course_tb WHERE Lvl = $MaxLvl  AND Sem = $MaxSem AND $ProgID AND StartSesID <= $SesID AND (EndSesID >= $SesID OR EndSesID = 0)");
	}

	//return "SELECT * FROM course_tb WHERE (Lvl < $MaxLvl OR (Lvl = $MaxLvl AND Sem <= $MaxSem)) AND $ProgID AND StartSesID >= $SesID";
	//return "SELECT * FROM course_tb WHERE (Lvl < $MaxLvl OR (Lvl = $MaxLvl AND Sem <= $MaxSem)) AND $ProgI
	if (is_array($course)) { //if no error
		//return $course[1];
		//exit();
		if ($course[1] > 0) {
			while ($indcourse = $course[0]->fetch_array()) {
				if ($indcourse['Lvl'] == $MaxLvl && $indcourse['Sem'] == $MaxSem) { //added '&& (int)$indcourse['Former'] < 1' to also check if course is not old course else add to old array(created above) 22-5-17 #2
					if ((int)$indcourse['Former'] < 1) {
						$current[$indcourse['CourseID']] = $indcourse;
					} else {
						$old[$indcourse['CourseID']] = $indcourse;
					}
				}
				$rtn[$indcourse['CourseID']] = $indcourse;
			}
		}
	}
	$rtn['Current'] = $current;
	$rtn['Old'] = $old;
	return $rtn;
}

//function to get the immediate priv result 
function GetPrevResult($RegNo, $CurLvl, $CurSem)
{
	global $dbo;
	$RegNo = $dbo->SqlSafe($RegNo);
	$Rst = null;
	$Lvl = $CurLvl;
	$Sem = $CurSem;
	do {
		$prevLvlSem = GetPrevLvlSem($Lvl, $Sem); //get immediate prev lvl and sem
		if ($prevLvlSem['err'] != "") { //if not found stop loop
			break;
		}
		$Lvl = $prevLvlSem['level'];
		$Sem = $prevLvlSem['semester'];
		$Rst = $dbo->SelectFirstRow("result_tb", "", "RegNo = '$RegNo' AND Lvl = $Lvl AND Sem = $Sem ORDER BY ID DESC LIMIT 1");
	} while (!is_array($Rst));
	return $Rst;
}

//function to get the student current session 
function StudSes($RegNo = "", $Lvl = 1, $startSes = 0, $modeEntry = 0)
{
	global $dbo;
	$RegNo = $dbo->SqlSafe($RegNo);
	//return 1 . "";
	if ($startSes == 0 || $modeEntry == 0) {
		$studDet = $dbo->SelectFirstRow("studentinfo_tb", "StartSes, ModeOfEntry", "RegNo='$RegNo' OR JambNo = '$RegNo' LIMIT 1");
		if (is_array($studDet)) { //if student details exist
			$startSes = (int)$studDet[0];
			$modeEntry = GetMOEID($studDet[1]);
			//return $startSes . " = ".$modeEntry;
		} else { //invalid student 
			return 0;
		}
	}
	//($lvl - $studModeofEn) + $startses = $currSesID;

	$curses = ($Lvl - $modeEntry) + $startSes;
	$currSesN = CurrentSes();
	$currSesID = (int)$currSesN['SesID'];
	$curses = $curses > $currSesID ? $currSesID : $curses;
	return $curses < 1 ? "0" : $curses . "";
}

//function to log Payment (11/5/2017)
function LogPayment($PayDes, $Message, $Type)
{
	global $dbo;
	//get the payment in log if exist
	/*$paym = $dbo->SelectFirstRow("paymentlog_tb","","Description='".$dbo->SqlSafe($PayDes)."' AND Type='".$dbo->SqlSafe($Type)."'");
  if(is_array($paym)){//update counter and message

  }*/
	//echo $PayDes;
	if (trim($PayDes) == "") return false;

	$ins = $dbo->Insert("paymentlog_tb", array("Description" => $PayDes, "Message" => $Message, "Type" => $Type));

	if ($ins == "#") {
		return true;
	} else {
		return false;
	}
}

function OlevelExam($ID)
{
	global $dbo;
	$rec = $dbo->SelectFirstRow("olevelexamtype_tb", "", "ID = $ID");
	if (is_array($rec)) {
		return $rec['Name'];
	}
	return "";
}

function StudPatchDet($RegNo, $PayID = 0, $lvl = 0, $pre = "p")
{
	if ($pre == 'a') { //meaning all student bank
		//tempoary - use only p for now
		$pre = 'p';
	}
	global $dbo;
	$Patch = array();
	$RegNo = $dbo->SqlSafe($RegNo);
	if ((int)$lvl == 0) {
		//get student curren level
		$lvl = StudLevel($RegNo);
	}
	//get stud det
	//$studet = GetBasicInfo($RegNo, "studsch", "a");
	$query = "(SELECT st.SurName,st.FirstName,st.OtherNames,st.StartSes,st.StudyID,st.RegID,st.ModeOfEntry, fac.FacID, fac.FacName, dpt.DeptID, dpt.DeptName, pr.ProgID, pr.ProgName, cl.Name as ClassName, lvl.Name as LevelName FROM studentinfo_tb st, fac_tb fac, dept_tb dpt, programme_tb pr, studentclass_tb cl,schoollevel_tb lvl WHERE (st.JambNo = '{$RegNo}' OR st.RegNo = '{$RegNo}') AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND (cl.ID=st.ClassID || st.ClassID = 0) AND (lvl.StudyID=st.StudyID AND lvl.Level=$lvl) LIMIT 1) UNION (SELECT st.SurName,st.FirstName,st.OtherNames,st.StartSes,st.StudyID,st.RegID,st.ModeOfEntry, fac.FacID, fac.FacName, dpt.DeptID, dpt.DeptName, pr.ProgID, pr.ProgName, cl.Name as ClassName, lvl.Name as LevelName FROM {$pre}studentinfo_tb st, fac_tb fac, dept_tb dpt, programme_tb pr, studentclass_tb cl,schoollevel_tb lvl WHERE (st.JambNo = '{$RegNo}' OR st.RegNo = '{$RegNo}') AND st.ProgID = pr.ProgID AND pr.DeptID = dpt.DeptID AND dpt.FacID = fac.FacID AND (cl.ID=st.ClassID || st.ClassID = 0) AND (lvl.StudyID=st.StudyID AND lvl.Level=$lvl) LIMIT 1) LIMIT 1";

	//return $query;

	$studet = $dbo->RunQuery($query);
	if (is_array($studet)) {
		if ($studet[1] > 0) { //if record found
			$studet = $studet[0]->fetch_array();
		} else {
			//check if is a candidate, in case there is no academic details
			$studet = $dbo->SelectFirstRow("{$pre}studentinfo_tb", "", "RegNo='$RegNo' OR JambNo='$RegNo' Limit 1", MYSQLI_ASSOC);
			if (!is_array($studet)) { //if not exise
				$studet = [];
			}
		}
		if (count($studet) > 0) {
			$Patch['Name'] = $studet['SurName'] . " " . $studet['FirstName'] . " " . $studet['OtherNames'];
			$Patch['ProgID'] = (isset($studet['ProgID']) && (int)$studet['ProgID'] > 0) ? $studet['ProgID'] : 0;
			$Patch['ProgName'] = isset($studet['ProgName']) ? $studet['ProgName'] : "";
			$Patch['DeptID'] = isset($studet['DeptID']) ? $studet['DeptID'] : 0;
			$Patch['DeptName'] = isset($studet['DeptName']) ? $studet['DeptName'] : "";
			$Patch['FacID'] = isset($studet['FacID']) ? $studet['FacID'] : 0;
			$Patch['FacName'] = isset($studet['FacName']) ? $studet['FacName'] : "";
			$Patch['StartSes'] = (isset($studet['StartSes']) && (int)$studet['StartSes'] > 0) ? $studet['StartSes'] : 0;
			$Patch['ModeOfEntry'] = isset($studet['ModeOfEntry']) ? $studet['ModeOfEntry'] : 1;
			$Patch['StudyID'] = isset($studet['StudyID']) ? $studet['StudyID'] : 0;
			$Patch['RegID'] = (isset($studet['RegID']) && (int)$studet['RegID'] > 0) ? $studet['RegID'] : 1;
			$Patch['ClassName'] = (isset($studet['ClassName'])) ? $studet['ClassName'] : "-";
			$Patch['LevelName'] = (isset($studet['LevelName'])) ? $studet['LevelName'] : "-";
		}

		if ($PayID != 0) {
			$paydet = $dbo->SelectFirstRow('item_tb', '', "ID = $PayID");
			if (is_array($paydet)) {
				$Patch['PayName'] = $paydet['ItemName'];
			}
		}
		$PatchStr = json_encode($Patch);
		return $PatchStr;
	} else {
		return "";
	}
}


 /* ****************PAYMENT GATEWAY VERIFICATION LOGIC - Bank ****************** */
/*//function to confirm from etansact
function QueryEtransact($param)
{
	global $dbo;
	//convert param to data array
	$paramarr = $dbo->DataArray($param);
	$TransNum = $paramarr['Ref'];
	$PayID = $paramarr['PayID'];
	//url
	$urls = $paramarr['POSTURL'];
	$urlarr = $dbo->DataArray($urls, "`", "~");
	$url = isset($urlarr[$PayID]) ? $urlarr[$PayID] : isset($urlarr['-1']) ? $urlarr['-1'] : array_shift($urlarr);

	//terminal id
	$terms = $paramarr['TERMINALIDBANK'];
	$termarr = $dbo->DataArray($terms, "`", "~");
	$term = isset($termarr[$PayID]) ? $termarr[$PayID] : isset($termarr['-1']) ? $termarr['-1'] : array_shift($termarr);

	$fields = array(
		'TERMINAL_ID' => $term,
		'PAYEE_ID' => urlencode($TransNum),
		'RESPONSE_URL' => ''
	);

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

	//open connection
	$ch = curl_init();
	//echo $ch;
	//print_r($ch);
	//set the url, number of POST vars, POST data
	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);
	//curl_setopt_array($ch, array(CURLOPT_RETURNTRANSFER => 1));

	//execute post
	$rst = curl_exec($ch);
	$rst = rtrim($rst, "</html>");
	$rst = trim($rst);
	curl_close($ch);
	$etr = urldecode($rst);
	$data = UrlToArray($etr); //$etr = implode("~",$data);
	$data['BANK'] = 1;
	return $data;
	//    }else{
	// 	  return $rst;
	//    }
	//close connection
	//======================================================================================================

}


//Remita
function QueryRemita($param)
{

	//$orderId,$rrr=false
	global $dbo;
	global $phpf;
	$REMITAPARAM = $phpf->DataArray($param, "&", "=", "");
	extract($REMITAPARAM);

	if (isset($MERCHANTID)) {

		$concatString = $Ref . $APIKEY . $MERCHANTID; //RRR+api_key+merchantId
		$hash = hash('sha512', $concatString);
		$url 	= $CHECKSTATUSURL . '/' . $MERCHANTID  . '/' . $Ref . '/' . $hash . '/' . 'status.reg';

		//  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);
		$response['TRANS_AMOUNT'] = $Amt; //remita dont return amt, (so we set amt to ordered amt)
		$response['TRANS_DATE'] = date("Y-m-d");  //use order date because remiter dont return payment date

		$response_code = $response['status'];
		//return $response;
		$response['URL'] = $url;
		if (isset($response['RRR'])) {
			$rrr = $response['RRR'];
		}
		$response_message = $response['message'];
		$retArr = array();
		if ($response_code == '01' || $response_code == '00') { //if suceesfull
			//$response['SUCCESS'] = 1;

		} else {
			if ($response_code == '021') { //if bank branch option and payment still pending
				$response['BANK'] = 1;
			}
			$response['SUCCESS'] = -1;
		}

		return $response;
	}
	return array();
} */


/* ****************PAYMENT GATEWAY LOGIC ****************** */

//encode user suplied date format(D/M/Y) to Mysql format (Y-m-d)
//#MysqlDateEncode
function MysqlDateEncode($userdate)
{
	//if empty date sent
	if (trim($userdate) == "") return NULL;
	//check if range date specified
	$userdatearrs = explode("-", trim($userdate));
	//return $userdatearrs;
	$rtndates = [];
	foreach ($userdatearrs as $udate) {
		//replace user delimiters to mysql delimeter
		$udate = str_replace(array("/", "\\", " "), "-", trim($udate));
		//split the date
		$userdatearr = explode("-", $udate);
		if (count($userdatearr) < 3) {
			continue;
		} else {
			$rtndates[] = $userdatearr[2] . "-" . $userdatearr[1] . "-" . $userdatearr[0];
		}
		//return $userdatearr[2]."-".$userdatearr[1]."-".$userdatearr[0];
	}

	if (count($rtndates) < 1) return "";
	if (count($rtndates) == 1) return $rtndates[0];
	if (count($rtndates) > 1) return $rtndates;
}

//decode Mysql date format(Y-m-d) to user format (D/M/Y)
//#MysqlDateDecode
function MysqlDateDecode($mysqldate)
{
	//if empty date sent
	if (trim($mysqldate) == "" || trim($mysqldate) == "0000-00-00" || is_null($mysqldate)) return "";
	//split the date
	$mysqldatearr = explode("-", $mysqldate);
	if (count($mysqldatearr) < 3) return "";
	$rempartarr = explode(" ", trim($mysqldatearr[2]));
	return $rempartarr[0] . "/" . $mysqldatearr[1] . "/" . $mysqldatearr[0];
}

//get the Reciving Bank
function GetCollectBank($PayID)
{
	global $dbo;
	$collectbnk = $dbo->SelectFirstRow("item_tb", "CollectBank", "ID=" . $PayID);
	if (is_array($collectbnk)) {
		return $collectbnk['CollectBank'];
	}
	return "";
}



//function to get the max credit unit
function GetMaxCH($progID = 0, $lvl = 0, $sem = 0)
{
	//return 34;
	global $dbo;
	//get the StudyID, FacID and DeptID
	$StudyID = 0;
	$FacID = 0;
	$DeptID = 0;
	if ($progID > 0) {
		$otherdet = $dbo->RunQuery("SELECT f.StudyID, f.FacID, d.DeptID FROM fac_tb f, dept_tb d, programme_tb p WHERE p.ProgID = $progID AND p.DeptID = d.DeptID AND d.FacID = f.FacID LIMIT 1");
		if (is_array($otherdet) && $otherdet[1] > 0) {
			$otherdet = $otherdet[0]->fetch_array();
			$StudyID = $otherdet['StudyID'];
			$FacID = $otherdet['FacID'];
			$DeptID = $otherdet['DeptID'];
		}
	}

	$q = "
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = $FacID AND DeptID=$DeptID AND ProgID = $progID AND Lvl = $lvl AND Sem = $sem)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = $FacID AND DeptID=$DeptID AND ProgID = $progID AND Lvl = $lvl AND Sem = 0)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = $FacID AND DeptID=$DeptID AND ProgID = $progID AND Lvl = 0 AND Sem = $sem)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = $FacID AND DeptID=$DeptID AND ProgID = $progID AND Lvl = 0 AND Sem = 0)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = $FacID AND DeptID=$DeptID AND ProgID = 0 AND Lvl = $lvl AND Sem = $sem)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = $FacID AND DeptID=$DeptID AND ProgID = 0 AND Lvl = $lvl AND Sem = 0)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = $FacID AND DeptID=$DeptID AND ProgID = 0 AND Lvl = 0 AND Sem = $sem)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = $FacID AND DeptID=$DeptID AND ProgID = 0 AND Lvl = 0 AND Sem = 0)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = $FacID AND DeptID=0 AND ProgID = 0 AND Lvl = $lvl AND Sem = $sem)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = $FacID AND DeptID=0 AND ProgID = 0 AND Lvl = $lvl AND Sem = 0)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = $FacID AND DeptID=0 AND ProgID = 0 AND Lvl = 0 AND Sem = $sem)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = $FacID AND DeptID=0 AND ProgID = 0 AND Lvl = 0 AND Sem = 0)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = 0 AND DeptID=0 AND ProgID = 0 AND Lvl = $lvl AND Sem = $sem)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = 0 AND DeptID=0 AND ProgID = 0 AND Lvl = $lvl AND Sem = 0)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = 0 AND DeptID=0 AND ProgID = 0 AND Lvl = 0 AND Sem = $sem)
UNION
(SELECT MaxCH FROM maxch_tb WHERE StudyID = $StudyID AND FacID = 0 AND DeptID=0 AND ProgID = 0 AND Lvl = 0 AND Sem = 0)
UNION
(SELECT TotalCH as MaxCH FROM programme_tb WHERE ProgID = $progID)
LIMIT 1
";

	//return $q;
	//get the most close totalch
	$maxchobj = $dbo->RunQuery($q);
	$MaxCH = 24;
	if (is_array($maxchobj) && $maxchobj[1] > 0) {
		$MaxCHrec = $maxchobj[0]->fetch_array();
		$MaxCH = $MaxCHrec['MaxCH'];
	}

	return $MaxCH . "";
}


function GetStudentResultPosition($rsult, $studDet = [], $byclass = false)
{
	global $dbo;
	if (count($studDet) == 0) {
		$studDet = $dbo->SelectFirstRow("studentinfo_tb", "ProgID,ClassID,StartSes", "RegNo='{$rsult['RegNo']}' OR JambNo='{$rsult['RegNo']}' LIMIT 1", MYSQLI_ASSOC);
	}
	$classcond = "";
	if ($byclass && isset($studDet['ClassID'])) {
		$classcond = " AND S.ClassID=" . $studDet['ClassID'];
	} else {
		$classcond = " AND S.ProgID = {$studDet['ProgID']}";
	}
	if (isset($studDet['StartSes'])) {
		$classcond .= " AND S.StartSes=" . $studDet['StartSes'];
	}


	//$dbo->DisableFullGroupByMode();
	$maxGroupID = $dbo->RunQuery("SELECT MAX(R.GroupID) as MaxGroupID, COUNT(R.ID) as TotalResult FROM `result_tb` R, studentinfo_tb S WHERE R.Lvl = {$rsult['Lvl']} AND R.Sem = {$rsult['Sem']} AND R.SesID = {$rsult['SesID']} AND (R.RegNo = S.RegNo OR R.RegNo = S.JambNo) $classcond GROUP BY R.RegNo");
	$TotRst = 0;
	if (is_array($maxGroupID) && $maxGroupID[1] > 0) {
		//$TotRst = (int)$maxGroupID[1];
		$maxGroupID = $maxGroupID[0]->fetch_assoc();

		$maxGroupID = $maxGroupID['MaxGroupID'];
	} else {
		$maxGroupID = 1;
	}
	//get the student position
	/*  $query = "SELECT * FROM (
		 SELECT  (@pos := @pos+1) pos, R.OTS, R.OAS, S.ProgID, R.ID, R.TGP, R.RegNo FROM `result_tb` R, studentinfo_tb S INNER JOIN (SELECT @pos := 0) p WHERE R.Lvl = {$rsult['Lvl']} AND R.Sem = {$rsult['Sem']} AND R.SesID = {$rsult['SesID']} AND (R.RegNo = S.RegNo OR R.RegNo = S.JambNo)  $classcond AND R.GroupID = $maxGroupID ORDER BY R.OTS DESC, R.OAS DESC,R.TGP DESC
		 ) as t WHERE t.ID = {$rsult['ID']} LIMIT 1"; */
	do {
		$queryinner = "SELECT  R.OTS, R.OAS, S.ProgID, R.ID, R.TGP, R.RegNo FROM `result_tb` R, studentinfo_tb S INNER JOIN (SELECT @pos := 0) p WHERE R.Lvl = {$rsult['Lvl']} AND R.Sem = {$rsult['Sem']} AND R.SesID = {$rsult['SesID']} AND (R.RegNo = S.RegNo OR R.RegNo = S.JambNo) $classcond AND R.GroupID = $maxGroupID";

		$query = "SELECT * FROM (SELECT (@pos := @pos+1) as pos, t.* FROM (
			$queryinner ORDER BY R.OTS DESC, R.OAS DESC,R.TGP DESC
			) as t) as a WHERE a.ID = {$rsult['ID']} LIMIT 1";
		//Error(0," - ".$query);
		//return $query;
		$posrst = $dbo->RunQuery($query);
		$maxGroupID--;
	} while ((!is_array($posrst) || $posrst[1] < 1) && $maxGroupID > 0); //not the best method to get the valid results

	if (is_array($posrst) && $posrst[1] > 0) {
		$posrst = $posrst[0]->fetch_assoc();
		$totrcd = $dbo->SelectFirstRow("(" . $queryinner . ") as ttb", "COUNT(*) as TOT");
		if (is_array($totrcd)) $TotRst = (int)$totrcd['TOT'];
		return Ordinal($posrst['pos']) . ($TotRst > 0 ? " / $TotRst" : "");
	}
	return "";
}


function Ordinal($number)
{
	$ends = array('th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th');
	if ((($number % 100) >= 11) && (($number % 100) <= 13))
		return $number . 'th';
	else
		return $number . $ends[$number % 10];
}



function GetStudentOverallClassResultDetails($rsult, $studDet = [], $byclass = false)
{
	global $dbo;
	if (count($studDet) == 0) {
		$studDet = $dbo->SelectFirstRow("studentinfo_tb", "ProgID,ClassID,StartSes", "RegNo='{$rsult['RegNo']}' OR JambNo='{$rsult['RegNo']}' LIMIT 1", MYSQLI_ASSOC);
	}

	$classcond = "";
	if ($byclass && isset($studDet['ClassID'])) {
		$classcond = " AND S.ClassID=" . $studDet['ClassID'];
	} else {
		$classcond = " AND S.ProgID = {$studDet['ProgID']}";
	}

	if (isset($studDet['StartSes'])) {
		$classcond .= " AND S.StartSes=" . $studDet['StartSes'];
	}

	$maxGroupID = $dbo->RunQuery("SELECT MAX(R.GroupID) as MaxGroupID, COUNT(R.ID) as TotalResult  FROM `result_tb` R, studentinfo_tb S WHERE R.Lvl = {$rsult['Lvl']} AND R.Sem = {$rsult['Sem']} AND R.SesID = {$rsult['SesID']} AND (R.RegNo = S.RegNo OR R.RegNo = S.JambNo) $classcond GROUP BY R.RegNo");
	$TotRst = 0;
	if (is_array($maxGroupID) && $maxGroupID[1] > 0) {
		$TotRst = (int)$maxGroupID[1];
		$maxGroupID = $maxGroupID[0]->fetch_assoc();

		$maxGroupID = $maxGroupID['MaxGroupID'];
	} else {
		$maxGroupID = 1;
	}

	//get the student position
	$query = "SELECT  COUNT(R.OTS) as NoRst, SUM(R.OTS) as OTS, SUM(R.OAS) as OAS FROM `result_tb` R, studentinfo_tb S WHERE R.Lvl = {$rsult['Lvl']} AND R.Sem = {$rsult['Sem']} AND R.SesID = {$rsult['SesID']} AND (R.RegNo = S.RegNo OR R.RegNo = S.JambNo)  $classcond AND R.GroupID = $maxGroupID ";
	//Error(0," - ".$query);
	$posrst = $dbo->RunQuery($query);
	if (is_array($posrst) && $posrst[1] > 0) {
		$posrst = $posrst[0]->fetch_assoc();
		return [$posrst['NoRst'], $posrst['OTS'], $posrst['OAS']];
	}
	return "";
}

//function to get a student class details
function GetStudentClassResultsAllCourse($rsult, $studDet = [], $byclass = false)
{
	global $dbo;
	if (count($studDet) == 0) {
		$studDet = $dbo->SelectFirstRow("studentinfo_tb", "ProgID,ClassID", "RegNo='{$rsult['RegNo']}' OR JambNo='{$rsult['RegNo']}' LIMIT 1", MYSQLI_ASSOC);
	}

	$classcond = "";
	if ($byclass && isset($studDet['ClassID'])) {
		$classcond = " AND S.ClassID=" . $studDet['ClassID'];
	} else {
		$classcond = " AND S.ProgID = {$studDet['ProgID']}";
	}
	if (isset($studDet['StartSes'])) {
		$classcond .= " AND S.StartSes=" . $studDet['StartSes'];
	}

	$maxGroupID = $dbo->RunQuery("SELECT MAX(R.GroupID) as MaxGroupID, COUNT(R.ID) as TotalResult  FROM `result_tb` R, studentinfo_tb S WHERE R.Lvl = {$rsult['Lvl']} AND R.Sem = {$rsult['Sem']} AND R.SesID = {$rsult['SesID']} AND (R.RegNo = S.RegNo OR R.RegNo = S.JambNo) $classcond GROUP BY R.RegNo");
	$TotRst = 0;
	if (is_array($maxGroupID) && $maxGroupID[1] > 0) {
		$TotRst = (int)$maxGroupID[1];
		$maxGroupID = $maxGroupID[0]->fetch_assoc();

		$maxGroupID = $maxGroupID['MaxGroupID'];
	} else {
		$maxGroupID = 1;
	}

	//get the student position
	$query = "SELECT R.RstInfo,R.RegNo  FROM `result_tb` R, studentinfo_tb S WHERE R.Lvl = {$rsult['Lvl']} AND R.Sem = {$rsult['Sem']} AND R.SesID = {$rsult['SesID']} AND (R.RegNo = S.RegNo OR R.RegNo = S.JambNo)  $classcond AND R.GroupID = $maxGroupID ";

	$rtnval = [];
	//Error(0," - ".$query);
	$posrstq = $dbo->RunQuery($query);

	if (is_array($posrstq) && $posrstq[1] > 0) {
		while ($posrst = $posrstq[0]->fetch_assoc()) {
			$rstInfo = $posrst['RstInfo'];
			$RegNo = $posrst['RegNo'];

			$rstinfoobj = json_decode($rstInfo, true);

			foreach ($rstinfoobj as $CourseID => $RstDet) {
				if (!isset($rtnval[$CourseID])) $rtnval[$CourseID] = [];
				if (!isset($rtnval[$CourseID]["TOT"])) $rtnval[$CourseID]["TOT"] = [];

				$rtnval[$CourseID]["TOT"][trim($RegNo)] = (float)$RstDet['Total'];
			}
		}
		//return $rtnval;
		//return [$posrst['NoRst'],$posrst['OTS'],$posrst['OAS']];
	}
	return $rtnval;
}

function StudentPositionBySubjectinClassReal($regno, $courseID, $rstarr, $binfo, $byClass = false)
{

	$AllClassStudTotScoreByCourse = GetStudentClassResultsAllCourse($rstarr, $binfo, $byClass);
	return StudentPositionBySubjectinClass($regno, $courseID, $AllClassStudTotScoreByCourse);
}

function StudentPositionBySubjectinClass($regno, $courseID, $AllClassStudTotScoreByCourse)
{

	$AllStud = $AllClassStudTotScoreByCourse[$courseID];
	$totall = [];
	$CAVG = 0;
	if (isset($AllStud['TOT'])) {
		$totall = $AllStud['TOT'];
		//sort all student total score
		arsort($totall);

		//get the student pos (ind)
		$regnos = array_keys($totall);
		$subjpos = array_search(trim($regno), $regnos);
		$subjposord = "";
		if ($subjpos > -1) {
			$subjposord = Ordinal($subjpos + 1);
		}

		//get the total of all student
		$cousetot = array_sum($totall);
		$cousrecnt = count($totall);
		//get the average
		if ($cousetot > 0) $CAVG = round($cousetot / $cousrecnt, 2);
	}
	return ["POS" => $subjposord, "TOT" => $cousetot, "COUNT" => $cousrecnt, "AVG" => $CAVG];
}

function GetStudLvlSemDetails($RegNo)
{
	global $dbo;
	//HasLogin($Param);

	$studDet = $dbo->SelectFirstRow("studentinfo_tb", "", "RegNo='" . $dbo->SqlSafe($RegNo) . "' OR JambNo='" . $dbo->SqlSafe($RegNo) . "'");
	if (!is_array($studDet)) return "Invalid Student";

	//get the last course registration
	$lstcreg = $dbo->SelectFirstRow("coursereg_tb", "", "RegNo='" . $dbo->SqlSafe($RegNo) . "' ORDER BY SesID DESC, Lvl DESC, Sem DESC", MYSQLI_ASSOC);
	//Error(8,json_encode($lstcreg));
	$maxsem = 2;
	//get the maximum semester number
	$semma = $dbo->SelectFirstRow("semester_tb", "count(ID)", "Enable = 1");

	if (is_array($semma)) {
		$maxsem = (int)$semma[0];
	}

	$lastLevel = 1;
	$lastSem = 1;
	if (is_array($lstcreg)) {

		//last det
		$lastLevel = $lstcreg['Lvl'];
		$lastSem = (int)$lstcreg['Sem'];
		/*    if(!isset($Param['Current']) || $Param['Current'] != TRUE){ //get next
   
            if($lastSem >= $maxsem){
                $lastLevel++;
                $lastSem = 1;
            }else{
                $lastSem++;
            }
        } */
	} else {
		//get the degree starting 


		$OtherDet = $studDet['OtherDet'];
		if (trim($OtherDet) != "") {
			$OtherDet = json_decode($OtherDet, true);
			if (isset($OtherDet['Degree'])) {
				//get the degree details
				$degdet = $dbo->SelectFirstRow("school_degrees_tb", "", "ID=" . $OtherDet['Degree']);
				if (is_array($degdet)) {
					$lastLevel = $degdet["StartLevel"];
				}
			}
		}
	}
	//get the student current Level details
	$leveldet = $dbo->SelectFirstRow("schoollevel_tb", "*,coalesce(IF(Descr='',Name,Descr),Name) as LevelName, ID as LID", "Level=$lastLevel AND StudyID=" . $studDet['StudyID'], MYSQLI_ASSOC);
	if (!is_array($leveldet)) return "Getting Level Details Failed";
	//get the student semester det
	$semdet = $dbo->SelectFirstRow("semester_tb", "*, coalesce(IF(Descr='',Sem,Descr),Sem) as SemesterName, IF(Num=0,ID,Num) as SemID", "(Num > 0 && Num=$lastSem) || ID=$lastSem", MYSQLI_ASSOC);
	if (!is_array($semdet)) return "Getting Semester Details Failed";;
	//(Num > 0 && Num={$Param['SemesterID']}) || ID={$Param['SemesterID']}
	return array_merge($leveldet, $semdet);
}

if (!function_exists('file_mime_type')) {
	//get file type
	function file_mime_type($file, $encoding = true)
	{
		$mime = false;

		if (function_exists('finfo_file')) {
			$finfo = finfo_open(FILEINFO_MIME);
			$mime = finfo_file($finfo, $file);
			finfo_close($finfo);
		} else if (substr(PHP_OS, 0, 3) == 'WIN') {
			$mime = mime_content_type($file);
		} else {
			$file = escapeshellarg($file);
			$cmd = "file -iL $file";

			exec($cmd, $output, $r);

			if ($r == 0) {
				$mime = substr($output[0], strpos($output[0], ': ') + 2);
			}
		}

		if (!$mime) {
			return false;
		}

		if ($encoding) {
			return $mime;
		}

		return substr($mime, 0, strpos($mime, '; '));
	}
}

// 5/11/2020 - TAG: Function to get the student module settings
function StudentSettings()
{
	global $dbo;
	$schpay = $dbo->SelectFirstRow("studentset_tb", "*", "1=1 LIMIT 1", MYSQLI_ASSOC);
	return $schpay;
}

//function to get the calculated level by startses and progid
function GetLevel($StartSes, $ProgID, $StudyID)
{
	$studlvl = LevelStartSes((int)$StartSes);

	$yearofSt = YearOfStudy($ProgID);

	if (((int)$studlvl - $yearofSt) > 0) {
		$spilstr = ExtraLevelString();
		$LvlName = strtoupper($spilstr) . " " . ((int)$studlvl - $yearofSt);
	} else {
		$LvlName = LevelName($studlvl, $StudyID);
	}
	return ["LevelID" => $studlvl, "LevelName" => $LvlName];
}

//get the heigest sem num

if (!function_exists("HighestSemester")) {
	function HighestSemester()
	{
		global $dbo;
		//get highest semester
		$highsem = 0;
		$higestsem = $dbo->SelectFirstRow("semester_tb", "ID,IF(Num=0,ID,Num) as Num", "Enable = 1 ORDER BY Num DESC, ID DESC LIMIT 1");
		if (!is_array($higestsem)) {
			/* $higestsem['Num'] = $higestsem['Num'] == 0?$higestsem['ID']:$higestsem['Num'];
	}else{ */
			$higestsem = ["ID" => 2, "Num" => 2, "Sem" => "Second", "Descr" => "Second Semester"];
		}
		return $higestsem;
	}
}

//function tto get student class by id
function GetStudentClassByID($classID = 0)
{
	global $dbo;
	$default = ["ID" => 0, "Name" => "--", "Descr" => "UNASSIGNED", "ProgID" => 0, "Capacity" => 0, "HeadID" => "", "HeadTitle" => ""];
	if ((int)$classID == 0) return $default;
	$classdet = $dbo->SelectFirstRow("studentclass_tb", "", "ID=" . $classID);
	if (!is_array($classdet)) return $default;
	return $classdet;
}

//Get student ProgId return 0 if student not exist
function GetStudentProgIDForPay($RegNo)
{
	global $dbo;
	//get the student progID
	$progID = $dbo->SelectFirstRow("studentinfo_tb", "ProgID", "RegNo='" . $dbo->SqlSafe($RegNo) . "' OR JambNo='" . $dbo->SqlSafe($RegNo) . "'", MYSQLI_ASSOC);

	$progID = !is_array($progID) ? 0 : $progID['ProgID'];
	return $progID;
}

//internal remove new liens
function PlainText($str)
{
	// Convert microsoft special characters
	$search = array(
		"‘",
		"’",
		"”",
		"“",
		"–",
		"—",
		"…"
	);
	$replace = array(
		"'",
		"'",
		'"',
		'"',
		"-",
		"-",
		"&#8230;"
	);

	//foreach($replace as $k => $v)
	//  {
	$str = str_replace($search, $replace, $str);
	//  }

	// Remove any non-ascii character
	$str = preg_replace('/[^\x20-\x7E]*/', '', $str);

	return $str;
	//return preg_replace('/[^a-zA-Z0-9_ -]/s',' ',$str);
}


function GetStudStudyID($RegNo)
{
	if (trim($RegNo) == "") return 0;
	global $dbo;
	$StudStudy = $dbo->RunQuery("(SELECT StudyID FROM studentinfo_tb WHERE (RegNo='" . $dbo->SqlSafe($RegNo) . "' OR JambNo='" . $dbo->SqlSafe($RegNo) . "') LIMIT 1) UNION (SELECT StudyID FROM pstudentinfo_tb WHERE (RegNo='" . $dbo->SqlSafe($RegNo) . "' OR JambNo='" . $dbo->SqlSafe($RegNo) . "') LIMIT 1) LIMIT 1");
	if (is_array($StudStudy) && $StudStudy[1] > 0) {
		$studid = $StudStudy[0]->fetch_array();
		return $studid['StudyID'];
	}
	return 0;
}

//function Get Student Class Name
function StudClass($RegNo)
{
	$def = ["ID" => 0, "Name" => "-", "Descr" => "", "ProgID" => 0, "Capacity" => 0, "HeadID" => 0, "HaedTitle" => ""];
	if (trim($RegNo) == "") return $def;
	global $dbo;
	//get the student classid
	$classdet = $dbo->RunQuery("(SELECT cl.* FROM studentclass_tb cl, studentinfo_tb st WHERE (st.RegNo='" . $dbo->SqlSafe($RegNo) . "' OR st.JambNo='" . $dbo->SqlSafe($RegNo) . "') AND st.ClassID = cl.ID LIMIT 1) UNION (SELECT cl.* FROM studentclass_tb cl, pstudentinfo_tb st WHERE (st.RegNo='" . $dbo->SqlSafe($RegNo) . "' OR st.JambNo='" . $dbo->SqlSafe($RegNo) . "') AND st.ClassID = cl.ID LIMIT 1) LIMIT 1");
	if (is_array($classdet) && $classdet[1] > 0) {
		$classrec = $classdet[0]->fetch_assoc();
		return $classrec;
	}
	return $def;
}

//form resultinfo array for DropDownLine
function ResultInfoDropDownLine()
{
	global $dbo;
	//get all the exam settings
	$allexamset = $dbo->Select("resultinfo_tb");
	$settinarr = [1 => "Main Settings"];
	$grdstrc = [];
	if (is_array($allexamset) && $allexamset[1] > 0) {
		$settinarr = [];
		$selectedsteID = 1;
		$setselect = isset($_POST['RstInfoID']) ? (int)$_POST['RstInfoID'] : 1;
		while ($indexamset = $allexamset[0]->fetch_assoc()) {

			if (count($grdstrc) < 1 || (int)$indexamset['ID'] == $setselect) {
				$grdstrc = $indexamset;
				$selectedsteID = $indexamset['ID'];
			}
			$settinarr[$indexamset['ID']] = $indexamset['SettingName'];
		}
	}
}

function GetLevelNameI($lastLevel,$Study = 5,$RegNo=""){
    global $dbo;
    $years = $RegNo==""?5:StudYearOfStudy($RegNo); //get the years of study
    $leveldet = null;
    if($years >= $lastLevel){
       $leveldet = $dbo->SelectFirstRow("schoollevel_tb", "*,coalesce(IF(Descr='',Name,Descr),Name) as LevelName, ID as LID,Level as LevelID", "Level=$lastLevel AND StudyID=" . $Study, MYSQLI_ASSOC); 
    }
    if (!is_array($leveldet)) {
        $spill = $lastLevel - $years;
        if ($spill > 0) {
            $exyearst = ExtraLevelString();
            $leveldet = ["ID" => 0, "Level" => $lastLevel, "Name" => $exyearst . " " . $spill, "SchoolTypeID" => 1, "StudyID" => $Study, "Descr" => $exyearst . " " . $spill, "LevelName" => $exyearst . " " . $spill, "LID" => 0, "LevelID" => $lastLevel];
        } else {
            Error(30);
        }
    }
    return $leveldet;
}

?>
