<?php

//error_reporting(0);
function Error($message){
	global $pdf;
	$pdf->HTML();
echo $message;
	$pdf->_HTML();
$pdf->Finish();
	exit();
}
/* include("../../../TaquaLB/Ajax/CGI/PHP/config.php"); //the configuration object (connection parameters)
include("../../PHP/getinfo.php");//hold basic functions to perform some common database operations or request*/
 //the caller or script that include it should also include the config and getinfo
 
/* if(isset($_GET['Regno'])){
	$regno = $_GET['Regno'];
	//$lvl = (int)$_GET['lvl'];
	$sem = $_GET['Sem'];
	$binfo = GetBasicInfo($regno);
	//$lvlarr = StudLevelSpill($regno);
	$lvl = $_GET['Lvl'];
	$yearofSt = StudYearOfStudy($regno,"");
		if(((int)$lvl - $yearofSt) > 0){
			$spilstr = ExtraLevelString();
			$LvlName = strtoupper($spilstr)." ".((int)$lvl - $yearofSt);
		}else{
			$LvlName = LevelName($lvl,$binfo['StudyID']);
		}
	
}else{

} */
$sch = $dbo->SelectFirstRow("school_tb");
//Error("RST001: We Encounter an Internal Problem, Loading your Result. Kindly Report this Error Message to the ICT Team");
$pdf->Banner(strtoupper("Result Sheet"),array("LogoSize"=>"80px*80px","WaterMark"=>"Abbr"));

//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");
	
   
	// if(is_array($rsult)){
		 if($rsult[1] > 0){
			$rstarr = $rsult[0]->fetch_array();
			$regno = $rstarr['RegNo'];
			$sqlRegNo = $dbo->SqlSave($regno);
		  $lvl = (int)$rstarr['Lvl'];
		  $sem = (int)$rstarr['Sem'];
		  $sesID = (int)$rstarr['SesID'];
			$binfo = GetBasicInfo($regno);
			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);
			}
			 
			 //get grading details
		$rstset = $dbo -> SelectFirstRow("resultinfo_tb","","ID = ".$rstarr['RstInfoID']);
		$classPassStr = $rstset['ClassOfPass'];
		//$classPassDetAll = GetClassPassDetAll();
		//$schgrdstr = GetGradeDetAll();
          $grdstr = is_array($rstset)?$rstset[1]:"";
          $schgrdstr = GetGradeDetAll($rstarr['RstInfoID']);
		  
		  $results = $rstarr['Rst'];
			$SesName = SessionName($rstarr['SesID']);
			$SemName = SemesterName($rstarr['Sem']);
			$yearofSt = StudYearOfStudy($regno,"");
			if(((int)$lvl - $yearofSt) > 0){
				$spilstr = ExtraLevelString();
				$LvlName = strtoupper($spilstr)." ".((int)$lvl - $yearofSt);
			}else{
				$LvlName = LevelName($lvl,$binfo['StudyID']);
			}
		  $CCH = $rstarr['CCH'];
		  $CGP = $rstarr['CGP'];
		  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();
$totcol = 3;
$theadrw = '<tr style="text-wrap: normal; overflow:hidden;">
<th width="">S/N</th>
<th width="">CODE</th>
<th width="">TITLE</th>';

//get the score structure
$RstInfoID = $rstarr['RstInfoID'];
$scorestruc = $dbo->Select("scorestruc_tb","","RstInfoID=".$RstInfoID);
$scorstrarr = [
	["ID"=>1,"Title"=>"CA"],
	["ID"=>2,"Title"=>"EXAM"]
];
if(is_array($scorestruc) && $scorestruc[1] > 0 ){
  $scorstrarr = [];
   while($indscorestr = $scorestruc[0]->fetch_assoc()){
	  $scorstrarr[] = $indscorestr;
	  $rsthtml .= '<th width="">'.$indscorestr['Title'].'</th>';
   }
   $totcol = $totcol + $scorestruc[1];
}else{
	$rsthtml .= '<th width="">CA</th>
	<th width="">EXAM</th>';
	$totcol = $totcol + 2;
}
$totcol = $totcol + 1;
$rsthtml .= '<th width="">TOTAL</th>
<th>1st Term\'s Scores</th>
<th>2nd Term\'s Scores</th>
<th>3rd Term\'s Scores</th>
<th width="">GRADE</th>
<th>REMARK</th>
<tr>';
 $rsthtml = '<table>
     <thead>
       <tr>
	   <td colspan="'.$totcol.'">3rd Term</td>
	   <td colspan="5">Annual Result</td>
	   </tr>
       </thead>';

//$pdf->_HTML();
$tch = 0;
			 $tgp = 0;
			 $cnt = 1;
			  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];
						  $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);
						$rstatus = (int)$passed <= 0?"FAILED":"PASSED";
						if(trim($rstarr['RstInfo']) == "" || is_null($rstarr['RstInfo'])){
						  $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"];
							$rsthtml .= "<tr><td>".$cnt."</td><td>".str_replace(" ","&nbsp;",$Cd)."</td><td>".str_replace(" ","&nbsp;",$tit)."</td>";
							$chkappr = $dbo->SelectFirstRow("resultapprove_tb","","Ses= $sesID AND CourseID=$courseID");
           // 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 APPROVED";
			   foreach($ScoresArr as $Sc){
				$rsthtml .= "<td>--</td>";
			}
			$rsthtml .= "<td>--</td><td>--</td><td>--</td><td>--</td><td>--</td><td>$dett</td></tr>";
			}else{
                           foreach($ScoresArr as $Sc){
								$rsthtml .= "<td>".$Sc."</td>";
							}
							$rsthtml .= "<td>".$tot."</td><td>--</td><td>--</td><td>--</td><td>".$Grade."</td><td>".$rstatus."</td></tr>";
			}
							
							$cnt++;
							//$arrval2[] = array(array("title={$tit}"),array(str_replace(" ","&nbsp;",$Cd),str_replace(" ","&nbsp;",$tit),"[{$CA}]","[{$Exm}]",$tot,$grdval)); 
						  }
					  }
					  /*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'];

	// $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";
	 } */

	 //generate pdf
	 
$pdf->Panel();
  $pdf->InfoBox(2.5,"text-transform:uppercase");
    $pdf->InfoTitle("BASIC DETAILS");
	$pdf->Info("Reg. Number:",$regno);
	$pdf->Info("Name:",$binfo['Name']);
	$pdf->Info("Faculty/School:",$binfo['Fac']);
	$pdf->Info("Department:",$binfo['Dept']);
	$pdf->Info("Programme:",$binfo['Prog']);
	$pdf->Info("Session:",$SesName);
	$pdf->Info("Level:",$LvlName);
	$regCourse = array("First","Second","Third"); 
	if($SemName == ""){
		$pdf->Info($sch['SemLabel'].":",$regCourse[((int)$sem - 1)]);
	}else{
		$pdf->Info($sch['SemLabel'].":",$SemName);
	}
	$pdf->Info("Print Date:",date("d, F Y"));
	
	
  $pdf->_InfoBox();
//passport
    $pdf->InfoBox(1.5);
    $pdf->InfoTitle("PASSPORT PHOTOGRAPH");
	$pdf->Dump("<div style=\"margin:auto;margin-top:2px;margin-bottom:5px;width:180px;height:180px\">");
	$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("RESULT DETAILS");
  $DisRest = [];
  
  if(!is_null($rstset['PortalResultDisplay'])){
	//$pdf->Info("Dis :",$rstset['PortalResultDisplay']);
	$PortalResultDisplay = json_decode($rstset['PortalResultDisplay'],true);
	//check if position is visible
	$rstarr['POS'] = "--";
	if($PortalResultDisplay['POS'] == 1){
		/* if(!isset($studDet)){
		   $studDet = $dbo->SelectFirstRow("studentinfo_tb","","RegNo='{$Param['LoginName']}' OR JambNo='{$Param['LoginName']}' LIMIT 1",MYSQLI_ASSOC);
		} */
		//get the student position
		
		$rstarr['POS'] = GetStudentResultPosition($rstarr,$binfo);
	}
	$DescrArr = ["GPA"=>["Grade Point Average(GPA)","GPA"],"CGPA"=>["Cum. Grade Point Average(CGPA)","CGPA"],"TOT"=>["Total Score","OTS"],"AVG"=>["Average Score","OAS"],"POS"=>["Class Position","POS"],"COP"=>["Overall Grade","COP"]];
	foreach($PortalResultDisplay as $Dis=>$stat){
		if($stat != 0){
			if($stat == 1){
				$pdf->Info($DescrArr[$Dis][0].":",$rstarr[$DescrArr[$Dis][1]]);
			   //$DisRest[] = ["Title"=>$DescrArr[$Dis][0],"Value"=>$rsult[$DescrArr[$Dis][1]]]; 
			}else{
				$pdf->Info($DescrArr[$Dis][0].":","--");
			}
		}
	}
}
  
	/* $pdf->Info("Grade Point Average:",$GPA);
	if($CGPA != ""){
     $pdf->Info("Cum. Grade Point Average:",$CGPA);
	}
	$pdf->Info("Class of Pass:",$classOfPass); */
 $pdf->_InfoBox();
$pdf->_Panel();
$pdf->Dump($rsthtml);
if(trim($rstset['Grading']) != ""){
	$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>
		 ';
		 $grdstg = explode("&",$rstset['Grading']);
		 if(count($grdstg) > 0){
			 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 = $schgrdstr[$GradID]['Grade'];
						 $REM = $schgrdstr[$GradID]['Desc'];
						 $rstdettb .= "<tr><td>$Range</td><td>$POINT</td><td>$GRADE</td><td>$REM</td></tr>";

					 }
				 }
			 }
		 }
$rstdettb .= '</tbody></table></div><div style="clear:both"></div></div>';
$pdf->Dump($rstdettb);
}

		  


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