<?php

//error_reporting(0);
function Error($message,$title=""){
	global $pdf;
	if(trim($title) != ""){
		$title = "Result Sheet";
	}
	$pdf->Banner(strtoupper($title),array("LogoSize"=>"80px*80px","WaterMark"=>"Abbr"));
	$pdf->HTML();
echo $message;
	$pdf->_HTML();
$pdf->Finish();
	exit();
}

function FormatScore($score,$max){
	$score = (float)$score;
	$max = (float)$max;
	if($max > 3){
		$groupval = $max / 3;
		$group1 = $groupval;
		$group2 = 2 * $groupval;
		$group3 = 3 * $groupval;
		if($score < $group1){
			return '<span style="color:rgb(255,20,20)">'.$score.'</span>';
		}

		if($score >= $group1 && $score <= $group2){
			return '<span style="color:rgb(0,0,0)">'.$score.'</span>';
		}

		if($score > $group2){
			return '<span style="color:rgb(0,110,0)">'.$score.'</span>';
		}
	}
	return $score;
}

function PositionColor($score,$max){
	$score = (float)$score;
	$max = (float)$max;
	if($max > 3){
		$groupval = $max / 3;
		$group1 = $groupval;
		$group2 = 2 * $groupval;
		$group3 = 3 * $groupval;
		if($score < $group1){
			return 'rgb(0,110,0)';
		}

		if($score >= $group1 && $score <= $group2){
			return 'rgb(0,0,0)';
		}

		if($score > $group2){
			return 'rgb(255,20,20)';
		}
	}
	return 'rgb(0,0,0)';
}

function DynamicComment($score,$max){
	$score = (float)$score;
	$max = (float)$max;
	/* if($max > 3){
		$groupval = $max / 3;
		$group1 = $groupval;
		$group2 = 2 * $groupval;
		$group3 = 3 * $groupval;
		if($score < $group1){
			return 'BAD RESULT, TRY MORE LATER!';
		}

		if($score >= $group1 && $score <= $group2){
			return 'GOOD RESULT, PUT MORE EFFORT!';
		}

		if($score > $group2){
			return 'EXCELENT RESULT, YOU ARE A SUPER STAR!';
		}
	}
	return 'GOOD RESULT, PUT MORE EFFORT!'; */
	if($score > 70){
		return 'EXCELLENT PERFORMANCE';
	}else if($score >= 50 && $score <= 69){
		return 'GOOD RESULT';
	}else if($score >= 45 && $score <= 49){
		return 'FAIR ATTEMPT';
	}else if($score >= 40 && $score <= 44){
		return 'POOR RESULT';
	}else{
		return 'VERY POOR RESULT';
	}

}
$sch = $dbo->SelectFirstRow("school_tb");
//Error("RST001: We Encounter an Internal Problem, Loading your Result. Kindly Report this Error Message to the ICT Team");


//get the result id
if(!isset($_GET['RID']) || (int)$_GET['RID'] < 1)Error("Invalid Result Parameter");
$RID = 
$GPA = "";
$CGPA = "";
$rsthtml = "";
$SesName = "";

	 $rsult = $dbo->RunQuery("select * from result_tb where ID= {$_GET['RID']} LIMIT 1");
	 if(!is_array($rsult))Error("RST001: We Encounter an Internal Problem, Loading your Result. Kindly Report this Error Message to the ICT Team");

	$RstInfoID = 1;
   
	// if(is_array($rsult)){
		 if($rsult[1] > 0){
			$rstarr = $rsult[0]->fetch_array();
			$RstInfoID = $rstarr['RstInfoID'];
			$regno = $rstarr['RegNo'];
			$sqlRegNo = $dbo->SqlSave($regno);
		  $lvl = (int)$rstarr['Lvl'];
		  $sem = (int)$rstarr['Sem'];
		  $sesID = (int)$rstarr['SesID'];
		  
			$binfo = GetBasicInfo($regno);
			//$pdf->Banner(strtoupper("ggg"),array("LogoSize"=>"80px*80px","WaterMark"=>"Abbr"));	
			//$pdf->HTML();
			 $AllClassStudTotScoreByCourse = GetStudentClassResultsAllCourse($rstarr,$binfo,true);
			//echo 'ggg';
			//	$pdf->_HTML();
			//$pdf->Finish();
			//exit();
			if(!is_array($binfo))Error("Reading Student details Failed - ".$regno);
			if(trim($rstarr['RstInfo']) == "" || is_null($rstarr['RstInfo'])){
				//$binfo = $dbo->SelectFirstRow("studentinfo_tb","","RegNo='".$dbo->SqlSafe($rsult['RegNo'])."' OR JambNo='".$dbo->SqlSafe($rsult['RegNo'])."' LIMIT 1",MYSQLI_ASSOC);
          
				$SemCourses = GetCourses($binfo['ProgID'],$lvl, $sem,0,false);
			}
			 
			 //get grading details
		$rstset = $dbo -> SelectFirstRow("resultinfo_tb","","ID = (select GrdStrucID from school_tb limit 1)");
		$classPassStr = $rstset['ClassOfPass'];
		//$classPassDetAll = GetClassPassDetAll();
		//$schgrdstr = GetGradeDetAll();
          $grdstr = is_array($rstset)?$rstset[1]:"";
          $schgrdstr = GetGradeDetAll($RstInfoID);
		  
		  $results = $rstarr['Rst'];
			$SesName = SessionName($rstarr['SesID']);
			$SemName = SemesterDescription($rstarr['Sem']);
			$yearofSt = StudYearOfStudy($regno,"");
			if(((int)$lvl - $yearofSt) > 0){
				$spilstr = ExtraLevelString();
				$LvlName = strtoupper($spilstr)." ".((int)$lvl - $yearofSt);
			}else{
				$LvlName = LevelName($lvl,$binfo['StudyID']);
			}
			$ClassDet = GetStudentClassByID($binfo['ClassID']);
			$ClassName = $ClassDet["Name"];
			$Gender = $binfo['Gen']; //gender
		  $CCH = $rstarr['CCH'];
		  $CGP = $rstarr['CGP'];
		  $OTS = $rstarr['OTS'];
		  $OAS = $rstarr['OAS'];
		  //$OtherRstdefault = [];
		  $OtherRst = $rstarr['OtherResult'];
		  if(!is_null($OtherRst) && trim($OtherRst) != ""){
			  $OtherRst = json_decode($OtherRst,true);
			  if(!$OtherRst)$OtherRst =[];
		  }else{
			  $OtherRst = [];
		  }
/* [{"GN":"PSYCHOMOTOR","ATTR":"Honesty, Obedience, Punctuality, Self Control, Sociality, Skill","REMARK":"FAIR, GOOD, VERY GOOD, EXCELENT","DEF":"GOOD","ENABLE":1},{"GN":"AFFECTIVENESS","ATTR":"Sports, Handling of Tools, Communication Skills, Painting & Drawing, Politness","REMARK":"FAIR, GOOD, VERY GOOD, EXCELENT","DEF":"GOOD","ENABLE":1}] */
		  if(count($OtherRst) == 0 && !empty($rstset['ResultAttr'])){ //if not found set the default

			$ResultAttrobj = json_decode($rstset['ResultAttr'],true);
			if($ResultAttrobj){
				foreach($ResultAttrobj as $indrst){
					if((int)$indrst['ENABLE'] != 1)continue;
					$attr = $indrst['ATTR'];
					$attrarr = explode(",",$attr);
					$OtherRst[strtolower(str_replace(" ","_",$indrst['GN']))] = [];
					foreach($attrarr as $k=>$inattr){
						$OtherRst[strtolower(str_replace(" ","_",$indrst['GN']))][strtolower(str_replace(" ","_",trim($inattr)))] = [$k,trim($inattr),$indrst['GN'],$indrst['DEF']];
					}
				}
			}
/* {"psychomotor":{"honesty":["3","Honesty","PSYCHOMOTOR","EXCELENT"],"obedience":["1","Obedience","PSYCHOMOTOR","GOOD"],"punctuality":["2","Punctuality","PSYCHOMOTOR","VERY GOOD"],"self_control":["2","Self Control","PSYCHOMOTOR","VERY GOOD"],"sociality":["0","Sociality","PSYCHOMOTOR","FAIR"],"skill":["2","Skill","PSYCHOMOTOR","VERY GOOD"]},"affectiveness":{"sports":["2","Sports","AFFECTIVENESS","VERY GOOD"],"handling_of_tools":["3","Handling of Tools","AFFECTIVENESS","EXCELENT"],"communication_skills":["1","Communication Skills","AFFECTIVENESS","GOOD"],"painting_&_drawing":["2","Painting & Drawing","AFFECTIVENESS","VERY GOOD"],"politness":["0","Politness","AFFECTIVENESS","FAIR"]}} */
          
		  }

		  $TComment = !is_null($rstarr['TComment'])?$rstarr['TComment']:"";
		  $HTComment = !is_null($rstarr['HTComment'])?$rstarr['HTComment']:"";

		  $datetime1 = new DateTime();
$datetime2 = new DateTime($binfo['DOB']);
$interval = $datetime1->diff($datetime2);
$age = $interval->format('%y years, %m months');
		  if(trim($results) != ""){
			  //break into individual result
			  $indrst = explode("&",$results);
			  if(count($indrst) == 0){
				  Error("RST003: Looks like you have no Result Yet or Result not yet Available."); 
				 // $pdf->Finish();
                 //exit();
			  }
//$pdf->HTML();
$maxobtainmk = [];
 $rsthtml = '<table style="background-color:#FFF;font-size:0.8em;margin:auto;text-transform:uppercase">
     <thead style="background-color:#FFF">
       <tr style="text-wrap: normal; overflow:hidden;background-color:#FFF">
          
		  <th  style="background-color:#FFF" width=""></th>';
		  $maxobtainmk[] = '<th  style="background-color:#FFF" width="">MAX. OBTAINABLE</th>';
$totmaxscors= 100;
		  //get the score structure
		  //$RstInfoID = 1;
		  $scorestruc = $dbo->Select("scorestruc_tb","","RstInfoID=".$RstInfoID);
		  $scorstrarr = [
			  ["ID"=>1,"Title"=>"CA","MaxScore"=>30],
			  ["ID"=>2,"Title"=>"EXAM","MaxScore"=>70]
		  ];
		  if(is_array($scorestruc) && $scorestruc[1] > 0 ){
			$scorstrarr = [];
			$totmaxscors = 0;
             while($indscorestr = $scorestruc[0]->fetch_assoc()){
				$scorstrarr[] = $indscorestr;
				$rsthtml .= '<th  style="background-color:#FFF" width="">'.$indscorestr['Title'].'</th>';
				$totmaxscors += (float)$indscorestr['MaxScore'];
				$maxobtainmk[] = '<th  style="background-color:#FFF" width="">'.$indscorestr['MaxScore'].'</th>';
			 }
		  }else{
			  $rsthtml .= '<th  style="background-color:#FFF" width="">CA</th>
			  <th  style="background-color:#FFF" width="">EXAM</th>';
		  }
		  $maxobtainmk[] = '<th  style="background-color:#FFF" width="">'.$totmaxscors.'</th><th  style="background-color:#FFF" width=""></th>
		  <th  style="background-color:#FFF"></th>
		  <th  style="background-color:#FFF" width="">'.$totmaxscors.'</th>
		  <th  style="background-color:#FFF" width=""></th>';

          $rsthtml .= '<th  style="background-color:#FFF" width="">TOTAL</th>
		  <th  style="background-color:#FFF" width="">GRADE</th>
		  <th  style="background-color:#FFF">REMARK</th>
		  <th  style="background-color:#FFF" width="">SUBJ AVG</th>
		  <th  style="background-color:#FFF" width="">SUBJ POS</th>
		  
	   <tr>
	   <tr>';
	   $rsthtml .= implode("",$maxobtainmk);
	   $rsthtml .= '</tr>
       </thead>';

//$pdf->_HTML();
$tch = 0;
			 $tgp = 0;
			 $cnt = 1;
			 $cntnuco = 0;
			 $totallnuco = 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) == 2){
						  $courseID = $resultdet[0];
						  $courserstdet = StudentPositionBySubjectinClass($regno,$courseID,$AllClassStudTotScoreByCourse);
						  $CAVG = $courserstdet['AVG'];
						  $subjposord = $courserstdet['POS'];
						 /*  $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);
						  } */
						  $rawscr = $resultdet[1];
						  $IndRstArr = explode("|",$rawscr);
						$Scores = $IndRstArr[0];
						$MaxScores = $IndRstArr[1];
						$Point = $IndRstArr[2];
						$Grade = $IndRstArr[3];
						$GradeDescr = $IndRstArr[4];
						$passed = $IndRstArr[5]; //1-PASS, 0-FAILED
						$CH = $IndRstArr[6];
						$GradePoint = $IndRstArr[7];
						$MaxScoresArr = [];
						//check if <v4 structure
						$commexist = strpos($Scores,",");
						if($commexist !== FALSE){ //=>v4
							//get ind scores
							$ScoresArr = explode(",",$Scores);
							$MaxScoresArr = explode(",",$MaxScores);
						}else{
							$ScoresArr = [$Scores,$MaxScores];//CA and Exam
						}

						if(count($scorstrarr) > count($ScoresArr)){
                          array_unshift($ScoresArr,0);
                          array_unshift($MaxScoresArr,0);
						}

						if(count($scorstrarr) < count($ScoresArr)){
							$tempScor = [];
							for($sc=0;$sc < count($ScoresArr); $sc++){
                               if($sc < count($scorstrarr)){ //if $sc col exist in $scorstrarr, i.e has slot
								$tempScor[$sc] = $ScoresArr[$sc];
							   }else{
								$tempScor[count($tempScor) - 1] += $ScoresArr[$sc];
							   }
							}
							$ScoresArr = $tempScor;
						}

						$tot = array_sum($ScoresArr);
						if($tot <= 0)continue;
						
						$rstatus = (int)$passed <= 0?"FAILED":"PASSED";
						if(trim($rstarr['RstInfo']) == "" || is_null($rstarr['RstInfo'])){
						//   $courseDet = isset($SemCourses[$courseID])?$SemCourses[$courseID]:CourseDetails($courseID);
						//NUCO walkaround
						//*************************** */
						if(!isset($SemCourses[$courseID])){
							continue; 
						}
						//***************************** */

						  $courseDet = isset($SemCourses[$courseID])?$SemCourses[$courseID]:CourseDetails($courseID);
						}else{
							$RstDet = json_decode($rstarr['RstInfo'],true);
							$courseDet = $RstDet[$courseID];
						}
						  if(is_array($courseDet)){
							  $Cd = trim($courseDet['CourseCode']);
							  $tit = strtoupper($courseDet['Title']);
							  $CH = $courseDet['CH'];
							  
							//$tot = $CA + $Exm;
								//get grade 
							//$grds = GetGrade($tot,$grdstr,$schgrdstr);
								//$pass = (int)$grds["PASS"];
							//$grdval = $grds["Grade"];
							//$tch += (int)$CH;
							//$tgp += (int)$CH * (int)$grds["Level"];background-color:rgb(255,150,150)
							$rwstyle = $tot > ($totmaxscors / 2)?"color:rgb(0,110,0)":"";
							$rwstyle = (int)$passed <= 0?"color:rgb(255,20,20)":$rwstyle;
							$chkappr = $dbo->SelectFirstRow("resultapprove_tb","","Ses= $sesID AND CourseID=$courseID");
							if((!is_array($chkappr) || $chkappr['Status'] == "FALSE") && (int)$rstset['ViewOnApprove'] > 0){
								$dett = !is_array($chkappr)?"APPROVAL ERROR":"NOT YET APPROVED";
								//$rwstyle = "background-color:rgb(255,180,180)";
							}
							$rsthtml .= '<tr ><td style="'.$rwstyle.'">'.trim(str_replace(" ","&nbsp;",PlainText($tit))).'</td>';
							$totallnuco += $tot;
							$cntnuco ++;
           // if(!is_array($chkappr))Error(45," (".$CDet['Title']." - ".$CDet['CourseCode'].")");
            if((!is_array($chkappr) || $chkappr['Status'] == "FALSE") && (int)$rstset['ViewOnApprove'] > 0){
			   //$dett = !is_array($chkappr)?"APPROVAL ERROR":"NOT YET APPROVED";
			 /*   foreach($ScoresArr as $Sc){
				$rsthtml .= '<td style="text-align:center">--</td>';
			} */
			$rsthtml .= '<td style="text-align:center;color:rgb(255,20,20)" colspan="'.(count($ScoresArr) + 5).'"><b>'.$dett.'</b></td></tr>';
			// $rsthtml .= '<td style="text-align:center" colspan="'.(count($ScoresArr) + 5).'">--</td><td style="text-align:center">--</td><td>'.$dett.'</td><td style="text-align:center">--</td><td>--</td></tr>';
			}else{
                           foreach($ScoresArr as $ind=>$Sc){
							   $Sc = FormatScore($Sc, $MaxScoresArr[$ind]);
								$rsthtml .= '<td style="text-align:center;">'.$Sc.'</td>';
							}
							$rsthtml .= '<td style="text-align:center;'.$rwstyle.'">'.$tot.'</td><td style="text-align:center;'.$rwstyle.'">'.strtoupper($Grade).'</td><td style="'.$rwstyle.'">'.strtoupper($GradeDescr).'</td><td style="text-align:center;'.$rwstyle.'">'.$CAVG.'</td><td style="'.$rwstyle.'">'.$subjposord.'</td></tr>';
			}
							
							$cnt++;
							//$arrval2[] = array(array("title={$tit}"),array(str_replace(" ","&nbsp;",$Cd),str_replace(" ","&nbsp;",$tit),"[{$CA}]","[{$Exm}]",$tot,$grdval)); $CAVG
						  }
					  }
					  /*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 = strtoupper($courseDet['Title']);
							  $CH = $courseDet['CH'];
							  $tot = $CA + $Exm;
							  $grd = GetGrade($tot);
							 // $grdd = $grd. "-" .GetPoint($grd);
							$arrval2[] = array(array("title={$tit}"),array(str_replace(" ","&nbsp;",$Cd),str_replace(" ","&nbsp;",$tit),"[{$CA}]","[{$Exm}]",$tot,$grd));  
						  }
					  }*/
				  }
			  }
$rsthtml .="</table>";
$GPA = $rstarr['GPA'];
/* $usecgpa = $GPA;
	 if($lvl == 1 && $sem == 1){
		 $CGPA = "";
	 }else{
	$CGPA = $CCH > 0?number_format($CGP/$CCH,2):"0.00";
	$usecgpa = $CGPA;
	 } */
$CGPA = $rstarr['CGPA'];
$nucoavge = $totallnuco / $cnt;

	// $classPassdet = GetClassPass($usecgpa,$classPassStr);
    $classOfPass = $rstarr['COP'];
		  }else{
			  Error("RST004:Result not yet Available.");
		  }
		 }else{
			 Error("RST002:Result not yet Available.");
		 }
	 /* }else{
		 $rsthtml = "RST001: We Encounter an Internal Problem, Loading your Result. Kindly Report this Error Message to the ICT Team";
	 } */

	 //get the school structure
	 $schStruc = json_decode($sch['SchStrucContr'],true);

	 //get the total max score
	 /* $totmaxscore = $dbo->SelectFirstRow("scorestruc_tb","SUM(MaxScore) as MaxScore");
	 $totmaxscore = !is_array($totmaxscore)?100:$totmaxscore['MaxScore']; */
	 $totmaxrstscore = ($cnt - 1) * $totmaxscors;
	 
	 //generate pdf
	 $pdf->Banner(strtoupper($SemName. " Result"),array("LogoSize"=>"80px*80px","WaterMark"=>"Abbr"));
$pdf->Panel();
  $pdf->InfoBox(1,"font-size:0.8em");
	$pdf->InfoTitle("BASIC DETAILS");
	$pdf->Info("NAME:","<b>".strtoupper($binfo['Name'])."</b>");
	$pdf->Info("REG:","<b>".$regno."</b>");
	$pdf->Info("GENDER:",$Gender);
	$pdf->Info("AGE:",$age);
	$pdf->Info("-",'-');
  $pdf->_InfoBox();

  $pdf->InfoBox(1,"font-size:0.8em");
  $pdf->InfoTitle("CLASS DETAILS");
  if($schStruc['StudyID']['SilentMode'] == false){$pdf->Info(strtoupper($schStruc['StudyID']['Name']).":",$binfo['StudyName'],"40%","50%");}
  if($schStruc['FacID']['SilentMode'] == false){$pdf->Info(strtoupper($schStruc['FacID']['Name']).":",$binfo['Fac'],"40%","50%");}
  if($schStruc['DeptID']['SilentMode'] == false){$pdf->Info(strtoupper($schStruc['DeptID']['Name']).":",$binfo['Dept'],"40%","50%");}
  if($schStruc['ProgID']['SilentMode'] == false){$pdf->Info(strtoupper($schStruc['ProgID']['Name']).":",$binfo['Prog'],"40%","50%");}
  $pdf->Info("CLASS:","<b>".$LvlName." ($ClassName)</b>","40%","50%");
  $pdf->Info("SESSION:",$SesName,"40%","50%");
  $pdf->_InfoBox();

  $pdf->InfoBox(1,"font-size:0.8em");
  $pdf->InfoTitle("RESULT SUMMARY");
  //$color = (float)$OTS > ($totmaxrstscore / 2)?"color:rgb(0,110,0)":"";
  
  $pdf->Info("TOTAL:",'<b style="">'.FormatScore($totallnuco,$totmaxrstscore)."</b> / ".$totmaxrstscore,"40%","50%");
  
  //$pdf->Info("CLASS AVG.:","<b>".round($classrstdet[2]/$classrstdet[0],2)."</b>","40%","50%");
//   $pdf->Info("AVERAGE:",$OAS,"40%","50%");
  if(!is_null($rstset['PortalResultDisplay'])){
	//$pdf->Info("Dis :",$rstset['PortalResultDisplay']);
	$PortalResultDisplay = json_decode($rstset['PortalResultDisplay'],true);
	
	function FormatPos($pos){
		$varr = explode("/",$pos);
		if(count($varr) > 1){
			$fnum = (int)trim($varr[0]);
			$snum = (int)trim($varr[1]);
			$pc = PositionColor($fnum,$snum);
			return '<b style="color:'.$pc.'">'.trim($varr[0]).'</b> / '.trim($varr[1]);
		}
		return $pos;
	}

	
	//check if position is visible
	$rstarr['POS'] = "--";
	if($PortalResultDisplay['POS'] == 1){
		$rstarr['POS'] = GetStudentResultPosition($rstarr,$binfo);
		
		$rstarr['POS'] = FormatPos($rstarr['POS']);
	}
	if($PortalResultDisplay['POSClass'] == 1){
		$rstarr['POSClass'] = GetStudentResultPosition($rstarr,$binfo,true);
		$rstarr['POSClass'] = FormatPos($rstarr['POSClass']);
	}

	if($PortalResultDisplay['AVG'] == 1){
		$rstarr['OAS'] = round($totallnuco/$cntnuco,2) ;
	}

	if($PortalResultDisplay['AVGClass'] == 1){
		$classrstdet = GetStudentOverallClassResultDetails($rstarr,$binfo,true);
  $classavg =round($classrstdet[1]/$classrstdet[0]/$cntnuco,2);
  $rstarr['AVGClass'] = $classavg ;
	}
	$DescrArr = ["GPA"=>["GPA","GPA"],"CGPA"=>["CGPA","CGPA"],"AVG"=>["AVERAGE","OAS"],"AVGClass"=>["CLASS AVERAGE","AVGClass"],"POS"=>["LEVEL POSITION","POS"],"POSClass"=>["CLASS POSITION","POSClass"],"COP"=>["COP","COP"]];
	foreach($PortalResultDisplay as $Dis=>$stat){
		if(!isset($DescrArr[$Dis]))continue;
		if($stat != 0){
			if($stat == 1){
				$v = $rstarr[$DescrArr[$Dis][1]];
				$pdf->Info($DescrArr[$Dis][0].":",$v,"40%","50%");
			   //$DisRest[] = ["Title"=>$DescrArr[$Dis][0],"Value"=>$rsult[$DescrArr[$Dis][1]]]; 
			}else{
				$pdf->Info($DescrArr[$Dis][0].":","--","40%","50%");
			}
		}
	}
}
  /* $regCourse = array("First","Second","Third"); 
  if($SemName == ""){
	  $pdf->Info($sch['SemLabel'].":",$regCourse[((int)$sem - 1)]);
  }else{
	  $pdf->Info($sch['SemLabel'].":",$SemName);
  } */
  $pdf->_InfoBox();
//passport
    $pdf->InfoBox(1,"font-size:0.8em");
    $pdf->InfoTitle("PASSPORT PHOTOGRAPH");
	$pdf->Dump("<div style=\"margin:auto;margin-top:2px;margin-bottom:5px;width:70px;height:70px\">");
	$passpp = str_replace("../epconfig","",trim($binfo['Passport']));
	$passpp = explode("?",$passpp);
	$passpp = $passpp[0];
	//if(strpos($passpp,'../epconfig'))
	if(file_exists(rtrim($pdf->BaseConfigPath,"/")."/".ltrim($passpp,"/"))){
$pdf->Image(rtrim($pdf->BaseConfigPath,"/")."/".ltrim($passpp,"/"),"width:100%;height:100%;text-align:center");
	}else{
		$pdf->Image("../images/App/Images/userbig.jpg","width:100%;height:100%;text-align:center");
	}
     
	 //$pdf->Image($pdf->BaseConfigPath.str_replace("../epconfig","",trim($binfo['Passport'])),"width:100%;height:100%;text-align:center");
	 //$pdf->Dump(rtrim($pdf->BaseConfigPath,"/")."/".ltrim($passpp,"/"));
     $pdf->Dump("</div>");
    $pdf->_InfoBox();
$pdf->_Panel();

$pdf->Panel();
$pdf->InfoBox(4,"text-transform:uppercase");
  $pdf->InfoTitle("COGNITIVE (PERFORMANCE IN SUBJECTS)");
  $DisRest = [];
 $pdf->_InfoBox();
$pdf->Dump($rsthtml);
$pdf->_Panel();
/* [{"GN":"PSYCHOMOTOR","ATTR":"Honesty, Obedience, Punctuality, Self Control, Sociality, Skill","REMARK":"FAIR, GOOD, VERY GOOD, EXCELENT","DEF":"GOOD","ENABLE":1},{"GN":"AFFECTIVENESS","ATTR":"Sports, Handling of Tools, Communication Skills, Painting & Drawing, Politness","REMARK":"FAIR, GOOD, VERY GOOD, EXCELENT","DEF":"GOOD","ENABLE":1}] */
$pdf->Panel();
foreach($OtherRst as $okey=>$ORst){
	
 $pdf->InfoBox(4,"text-transform:uppercase;font-size:0.8em");
  $pdf->InfoTitle(str_replace("_"," ",$okey));
  //$DisRest = '';
 $heads = $bodys = '';
  foreach($ORst as $mrst){
	  if(!isset($mrst[1]))continue;
    $heads .= '<th  style="background-color:#FFF">'.$mrst[1].'</th>';
    $bodys .= '<td  style="background-color:#FFF;text-align:center">'.$mrst[3].'</td>';
  }
    $heads = '<thead><tr>'.$heads.'</tr></thead>';
  $bodys = '<tbody><tr>'.$bodys.'</tr></body>';
   $DisRest = '<table style="background-color:#FFF;margin:auto;width:100%;font-size:0.8em">'.$heads.$bodys.'</table>';
  $pdf->Dump($DisRest); 
 $pdf->_InfoBox();


}
$pdf->_Panel();


// Teachers comment
$pdf->Panel();
$pdf->InfoBox(1.3,"text-transform:uppercase;font-size:0.8em");
  $pdf->InfoTitle("TEACHERS COMMENT / SIGN");
  $pdf->Dump("<div style=\"margin:5px;width:100%;min-height:70px\">");
  $pdf->Dump($TComment);
  $pdf->Dump("</div>");
  
  //get the class staff sig
  $classStaff = $dbo->SelectFirstRow("studentclass_tb cl, staff_tb st","Sig","cl.ID=".$binfo['ClassID']." AND cl.HeadID = st.UserID LIMIT 1");
  if(is_array($classStaff)){
	  $pdf->Dump("<div style=\"margin:auto;margin-top:2px;margin-bottom:5px;width:60%;height:30px\">");
	  $passpp = str_replace(array("Files/","files/"),"",trim($classStaff['Sig']));
	$passpp = explode("?",$passpp);
	$passpp = $passpp[0];
	//if(strpos($passpp,'../epconfig'))
	if(file_exists(rtrim($pdf->BaseConfigPath,"/")."/".ltrim($passpp,"/"))){
$pdf->Image(rtrim($pdf->BaseConfigPath,"/")."/".ltrim($passpp,"/"),"height:100%;text-align:center");
	}else{
		//$pdf->Dump(rtrim($pdf->BaseConfigPath,"/")."/".ltrim($passpp,"/"));
		//$pdf->Image("../images/App/Images/userbig.jpg","width:100%;height:100%;text-align:center");
	}
//   $pdf->Image("../images/App/Images/userbig.jpg","width:100%;height:100%;text-align:center");
  $pdf->Dump("</div>");
  }
  
$pdf->_InfoBox();
if(trim($rstset['Grading']) != ""){
$pdf->InfoBox(1.3,"text-transform:uppercase;font-size:0.8em");
  $pdf->InfoTitle("GRADING");
  $grdstg = explode("&",$rstset['Grading']);
  if(count($grdstg) > 0){
	$rstdettb = '<table style="background-color:#FFF;margin:auto;width:100%;font-size:0.7em;text-transform:uppercase">';
	  foreach($grdstg as $indgrd){
		  $indgrarr = explode("=",$indgrd);
		  if(count($indgrarr) > 0){
			  $Range = str_replace(array("<",">"),array("Below ","Above "),$indgrarr[0]);
			  $GradID = $indgrarr[1];
			  if(isset($schgrdstr[$GradID])){
				  $POINT = $schgrdstr[$GradID]['Level'];
				  $GRADE = strtoupper($schgrdstr[$GradID]['Grade']);
				  $REM = strtoupper($schgrdstr[$GradID]['Desc']);
				  $rstdettb .= "<tr><td>$Range</td><td>$GRADE</td><td>$REM</td></tr>";

			  }
		  }
	  }
	  $rstdettb .= '</table>';
	  $pdf->Dump($rstdettb);
  }
$pdf->_InfoBox();
}

$pdf->InfoBox(1.3,"text-transform:uppercase;font-size:0.8em");
  $pdf->InfoTitle(strtoupper($binfo['StudyHeadTitle'])."'S COMMENT / SIGN");
  $pdf->Dump("<div style=\"margin:5px;width:100%;min-height:70px\">");
  $pdf->Dump(DynamicComment($OAS,$totmaxrstscore));
//   $pdf->Dump(DynamicComment($OTS,$totmaxrstscore));
  $pdf->Dump("</div>");
  //get the class staff sig
  $classStaff = $dbo->SelectFirstRow("school_grp_tb sc, staff_tb st, study_tb std","st.Sig","std.StudySchID = sc.SchGrpID AND std.ID=".$binfo['StudyID']." AND sc.SchGrpHeadUserID = st.UserID LIMIT 1");//StudySchID
  if(is_array($classStaff)){
	  $pdf->Dump("<div style=\"margin:auto;margin-top:2px;margin-bottom:5px;width:60%;height:30px\">");
	  $passpp = str_replace(array("Files/","files/"),"",trim($classStaff['Sig']));
	$passpp = explode("?",$passpp);
	$passpp = $passpp[0];
	//if(strpos($passpp,'../epconfig'))
	if(file_exists(rtrim($pdf->BaseConfigPath,"/")."/".ltrim($passpp,"/"))){
$pdf->Image(rtrim($pdf->BaseConfigPath,"/")."/".ltrim($passpp,"/"),"height:100%;text-align:center");
	}else{
		//$pdf->Dump(rtrim($pdf->BaseConfigPath,"/")."/".ltrim($passpp,"/"));
		//$pdf->Image("../images/App/Images/userbig.jpg","width:100%;height:100%;text-align:center");
	}
//   $pdf->Image("../images/App/Images/userbig.jpg","width:100%;height:100%;text-align:center");
  $pdf->Dump("</div>");
  }
$pdf->_InfoBox();

$pdf->_Panel();



	/* $rstdettb = '<div style="width:100%;margin-top:0px">
	<div style="width:300px;float:right;">
	<table style="">
	<thead>
	<tr style="text-wrap: normal; overflow:hidden;">
	<th colspan="4">GRADE STRUCTURE</th>
	</tr>
	  <tr style="text-wrap: normal; overflow:hidden;">
		 <th width="">RANGE</th>
		 <th width="">POINT</th>
		 <th width="">GRADE</th>
		 <th width="">REMARK</th> 
		</tr>
</thead>
<tbody>
		 ';
		
$rstdettb .= '</tbody></table></div><div style="clear:both"></div></div>';
$pdf->Dump($rstdettb);
} */

		  


$pdf->FooterNote("Result Sheet - ".$regno);
$pdf->Finish();
?>
