<?php
error_reporting(0);
ini_set("memory_limit","-1");
$baseurl = "../../../";
$subDir = urldecode($_REQUEST['SubDir']);
$configdir = "../../../../../".$subDir;
require_once("../../../general/config.php");
require("../../../general/getinfo.php");
require_once "../../../general/TaquaLB/Elements/Elements.php";
require_once $configdir.$dbo->Config['Require']."PDF/mpdf60/mpdf.php";
require_once "../../../general/TaquaLB/Elements/Script/pdf.php";
/*require_once("../../../epconfig/TaquaLB/Elements/Elements.php");
require("../../../epconfig/GenScript/PHP/getinfo.php");
include("../../../epconfig/TaquaLB/Ajax/CGI/PHP/PDF/mpdf60/mpdf.php");
require("../../../epconfig/TaquaLB/Elements/Script/pdf.php");*/

$pdf = new PDFPrinter();
$pdf->SetBasePath($configdir."Files/");
//require_once("../../../epconfig/TaquaLB/Ajax/CGI/PHP/PDF/mpdf.php");
 extract($_GET);
//print_r($_GET);
//( [rstudstudy] => 5 [rstudfac] => 1 [rstuddept] => 3 [rstudprog] => 3 [rstudlvl] => 1 [semest] => 1 [sestb] => 1 [rcourse] => 1 )
$rstappr = $dbo->SelectFirstRow("resultapprove_tb","","ProgID=$rstudprog AND Ses=$sestb AND Lvl=$rstudlvl AND Sem=$semest AND CourseID=$rcourse AND StudyID=$rstudstudy");

if(!isset($RstInfoID))$RstInfoID=1;

$grdstr = $dbo -> SelectFirstRow("resultinfo_tb","","ID = ".$RstInfoID);
          $grdstr = is_array($grdstr)?$grdstr[1]:"";
          $schgrdstr = GetGradeDetAll();

$oldcourseid = 0;
$coursesarr = [$rcourse];
//get the old copy of this course if exist
$oldcourse = $dbo->SelectFirstRow("course_tb","","Former=".$rcourse);
if(is_array($oldcourse)){ //if old course exist
  $oldcourseid = (int)$oldcourse['CourseID'];
  $coursesarr[] = $oldcourseid;
}

   $dets = $dbo->SelectFirstRow("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","c.CourseID = $rcourse 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 = $sestb AND ((sem.Num > 0 && sem.Num = c.Sem) || sem.ID = c.Sem) AND s.ID = c.StudyID");
   if($oldcourseid > 0){
    $oldcCode = $oldcourse['CourseCode'];
    $oldcCH = (int)$oldcourse['CH'];
    $oldtitle = $oldcourse['Title'];
    if(trim(strtolower($oldcCode)) != trim(strtolower($dets['CourseCode']))){
      $dets['CourseCode'] = $dets['CourseCode']." / ".$oldcCode;
    }
  
    if(trim(strtolower($oldtitle)) != trim(strtolower($dets['Title']))){
      $dets['Title'] = $dets['Title']." / ".$oldtitle;
    }
  
    if((int)$oldcCH != (int)$dets['CH']){
      $dets['CH'] = $dets['CH']."/".$oldcCH;
    }
    /* $dets['CourseCode'] = $dets['CourseCode']." / ".$oldcourse['CourseCode'];
    $dets['Title'] = $dets['Title']." / ".$oldcourse['Title'];
    $dets['CH'] = $dets['CH']."/".$oldcourse['CH']; */
   }
   $rstdet = "Result Sheet";
   $aprrtxt = "UNAPPROVED";
   if(!is_array($dets)){//|| !is_array($rstappr)
	   //PrintHeader($rstdet);
     $pdf->Banner($rstdet);
     
     $pdf->Dump("<div style=\"text-align:center; font-size:2.0em; margin-top:40px\">INVALID RESULT</div>");
	   $pdf->Finish();
     exit();
   }else{
    $scorearrdb = [];
     $disID = "";
     if(is_array($rstappr)){
        $disID = "(".$rstappr["ID"].")";
        $aprrtxt = $rstappr["Status"] == "TRUE"?"APPROVED":$aprrtxt;
        //Get the Structure
        if(!is_null($rstappr['ScoreStruc'])){
          $scorearrdb = json_decode($rstappr['ScoreStruc'],true);
        }
     }
     if(count($scorearrdb) == 0){ //if no score structure asign to the result
      //$RstInfoID = 1;
      $scorestrcs = $dbo->Select("scorestruc_tb","","RstInfoID=".$RstInfoID);
      $scorearrdb = ["ASSESSMENT","EXAM"];
      //$cnter = 1;
      if(is_array($scorestrcs) && $scorestrcs[1] > 0){
        $scorearrdb = [];
         while($scr = $scorestrcs[0]->fetch_assoc()){
          $scorearrdb[] = $scr['Title'];
         // $maxScorarr["SC".$cnter] = $scr['MaxScore'];
          //$cnter++;
         }
      }
     }

     $titledis = "";
      $intitwidth = round(30/count($scorearrdb));
      foreach($scorearrdb as $ScoreTitle){
        $titledis .= "<th style=\"width:{$intitwidth}%\">$ScoreTitle</th>";      
      }


	   $rstdet .= $disID." <br />".$dets['Title']." (".$dets['CourseCode'].")";
	  $pdf->Banner($rstdet,array("LogoSize"=>"100px*100px","Style"=>"font-size:0.9em"));
    $pdf->FooterNote($rstdet,$pdf->Signataries(array("Course Lecturer","HOD")));
    $pdf->WaterMarkText($aprrtxt,0.08);
    $pdf->HTML();
    // print_r($_REQUEST);
   }
  $rstdis = ""; //hold the entire result markup
   $totrst = 0;
   $passrst = 0;
   $failrst = 0;
   $invalidrst = 0;
   $edited = 0;
   $query = "";
   foreach($coursesarr as $indcourseid){
    $query .= $query != ""?" UNION ":"";
    $query .= "SELECT c.RegNo,r.Rst,s.SurName, s.FirstName, s.OtherNames,r.ID as RstID,r.GroupID,s.StartSes,'$indcourseid' as CourseID FROM coursereg_tb c LEFT JOIN studentinfo_tb s ON c.RegNo = s.RegNo OR c.RegNo = s.JambNo LEFT JOIN result_tb r ON (c.RegNo = r.RegNo AND r.Lvl=c.Lvl AND c.Sem = r.Sem AND c.SesID = r.SesID) WHERE (c.CoursesID LIKE '{$indcourseid}~%' OR c.CoursesID LIKE '%~{$indcourseid}'  OR c.CoursesID LIKE '%~{$indcourseid}~%') AND c.SesID = {$sestb} AND c.Sem = {$semest} AND (s.ClassID=0 || s.ClassID=$classid)";
   }
    
    $query .=" ORDER BY StartSes DESC, RegNo ASC, GroupID DESC"; 
    
//echo $query;
  $rst = $dbo->RunQuery($query);

          // Hidden("gradeStruc",GetGrade(-1,$grdstr,$schgrdstr));
 // echo $query;
 $studreg = true; //hold if details from course reg or directly from result
  if(is_array($rst)){
      if($rst[1] < 1){
        foreach($coursesarr as $indcourseid){
          $nruery .= $nruery != ""?" UNION ":"";
           $nruery .= "SELECT *,ID as RstID,'$indcourseid' as CourseID  FROM result_tb WHERE Sem=$semest AND SesID=$sestb AND (Rst LIKE '%&{$indcourseid}=%' OR Rst LIKE '{$indcourseid}=%')";

        }
           $nruery .= " ORDER BY RegNo ASC, GroupID DESC"; //Lvl=$rstudlvl AND

           $rst = $dbo->RunQuery($nruery);
           $studreg = false;
      }
     // echo $rst[1];
      if($rst[1] > 0){
          $counter = 1;
          $lstReg = "";
          $lca = ""; $lex = "";
          $RstArr = array();
      $rstdis = "<table>";
      
		  //echo 
		  if($studreg){
            $rstdis .= "<thead><tr> <th style=\"width:5%\">SN</th><th style=\"width:15%\">Reg. No.</th><th style=\"width:25%\">Name</th>$titledis<th style=\"width:10%\">Total</th><th style=\"width:5%\">Grade</th><th style=\"width:10%\">Remark</th> </tr></thead>";
		  }else{
			  $rstdis .= "<thead><tr> <th style=\"width:10%\">SN</th><th style=\"width:35%\">Reg. No.</th>$titledis<th style=\"width:10%\">Total</th><th style=\"width:5%\">Grade</th><th style=\"width:10%\">Remark</th></tr></thead>";
		  }
      $rstfound = false;
      $RstIDs = [];
          while($reg = $rst[0]->fetch_array()){
              //$rwID = "0"; //default rwID(ResultID) which indicate no course result found for the current student
              $ca = ""; $ex = ""; $tot = ""; $grd="";$studrst = "";$pass = "";
              $Scores = array_fill(0, count($scorearrdb), "");
              $rwID = $reg['RstID']; //set the result ID, to be use to uniquelly identify the result during saving, cos if duplicate(updated result exist, the id will be the only identifying field)
             // $rwID = $reg['RstID'];
              if(in_array($rwID,$RstIDs))continue;
              if(!is_null($rwID) && (int)$rwID > 0)$RstIDs[] = $rwID;
             // $RstIDs[] = $rwID;
              if($studreg){
               $name = $reg[2]." ".$reg[3]." ".$reg[4];

              }
              $cid = $reg['CourseID'];
              $rcourse = $cid; //update the sent corse id to the student result course id for merged courses

              $grds="";
              if($reg["Rst"] != ""){
                  $rstarr = explode("&",$reg["Rst"]);
                  foreach($rstarr as $rststr){
                      $rstbr = explode("=",$rststr);
                      if($rstbr[0] == $rcourse){
                        $scorarr = explode("|",$rstbr[1]);
                        //$Scores = [];
                        $ca = $scorarr[0];
                        //check if structure is old
                        if(strpos($ca,",") === false){
                          $ca = $ca.",".$ex;
                        }
                        //$ex = $scorarr[1];
                        $Scores = explode(",",$ca);
                        $tot = array_sum($Scores);
                        $grds = GetGrade($tot,$grdstr,$schgrdstr);
						$pass = $grds["PASS"];
            $remark = (int)$pass == 1?"PASSED":"FAILED";
                       $grds = $grds["Grade"];
					   $rstfound = true;
                  
                       
                        break;
                      }
                  }
                  
              }
        $tr = "";
        //Re apropriate score field
        $reaprscrarr = $Scores;

        //if the derived scores are higher than the expexted
        if(count($Scores) > count($scorearrdb)){ 
          $reaprscrarr = array_values($scorearrdb); //preaper the resultant scores array by using the expected
          foreach($Scores as $ind=>$inscr){ //loop throu derived
            if(isset($reaprscrarr[$ind])){ //if the current score pos exit just set it
              $reaprscrarr[$ind] = $inscr;
            }else{ //if does not exit add it to the last pos
              $reaprscrarr[count($reaprscrarr) - 1] = (float)$reaprscrarr[count($reaprscrarr) - 1] + $inscr;
            }
            
          }
        }

        //if the derived scores are lesser than the expexted
        if(count($Scores) < count($scorearrdb)){ 
          //get the remaining pos
          $rem = count($scorearrdb) - count($Scores);
          //if no result found at all set fileds to "" else 0
          $reaprscrarr = count($Scores) > 0?array_merge($reaprscrarr,array_fill(0, $rem, 0)):array_merge($reaprscrarr,array_fill(0, $rem, ""));
        }

              if($studreg){
           // $dump[] = array($reg["RegNo"],$name,$ca,$ex,$tot,$grds,"ID"=>$rwID);
		   
		   $tr = "<tr class=\"???\"> <td >$counter</td><td>".$reg["RegNo"]."</td><td>".$name."</td><td>".implode("</td><td>",$reaprscrarr)."</td><td>".$tot."</td><td>".$grds."</td><td>".$remark."</td></tr>";
              }else{
               //$dump[] = array($reg["RegNo"],$ca,$ex,$tot,$grds,"ID"=>$rwID); 
			   $tr = "<tr  class=\"???\"> <td>$counter</td><td>".$reg["RegNo"]."</td><td>".implode("</td><td>",$reaprscrarr)."</td><td>".$tot."</td><td>".$grds."</td><td>".$remark."</td></tr>"; 
              }
			  if(trim($grds) == ""){
			  // $failrst++;
		   }
              if($lstReg == $reg["RegNo"]){ //if updated copy exist and ca/ex not the same
               //if($lca != $ca || $lex != $ex){
               if(!in_array($reg["RegNo"]."|".implode("|",$Scores),$RstArr)){
                 /* $dump[count($dump) - 1]["logo"] = "#history";
                  $dump[count($dump) - 1]["info"] = "Outdated Copy";
                  $dump[count($dump) - 1]["readonly"] = "true";*/
				  $tr = str_replace("???","err",$tr);
				  $edited++;
               }else{
                   //remove from array i.e - duplicate result 
                   //array_pop($dump);
				   $tr = "";
               }
              }
			  
              //check if a valid student
              $checkstud = $dbo->SelectFirstRow("studentinfo_tb","RegNo","RegNo='".$reg["RegNo"]."' OR JambNo='".$reg["RegNo"]."' LIMIT 1");
              
              if(!is_array($checkstud)){ //if student not exist
               $tr = str_replace("???","err inv",$tr);
               /* $dump[count($dump) - 1]["logo"] = "#exclamation-triangle";
                  $dump[count($dump) - 1]["info"] = "Invalid Student";
                  $dump[count($dump) - 1]["readonly"] = "true";*/
                  $invalidrst++;
              }
			  $tr = str_replace("???","",$tr);
			  if(trim($tr) != ""){
				   $passrst = (int)$pass == 1?$passrst + 1:$passrst;
				   $failrst = (int)$pass == 0?$failrst + 1:$failrst;
				  $totrst++;
				  $counter++;
			  }
			  $rstdis .= $tr;
             // if(!array())
              $lstReg = $reg["RegNo"];
              $RstArr[] = $reg["RegNo"]."|".implode("|",$Scores);
              $lca = $ca;
              $lex = $ex;
          }
         // $procgrde = GetGrade(-1,$grdstr,$schgrdstr); //return all grade structure with the grade symbole
         /*if($studreg){
          $header=array("*RegNo"=>"REGISTRATION NO.","*Name"=>"FULL NAME","*CA"=>"ASSESSMENT","*Exm"=>"EXAM","#Tot"=>"TOTAL","#Grd"=>"GRADE","Rmk"=>"REMARK");
          $readonly = $apprv?"RegNo;Name;Tot;Grd;CA;Exm":"RegNo;Name;Tot;Grd";
           $rowinsert = "false";
         }else{
           $header = array("*RegNo"=>"REGISTRATION NO.","*CA"=>"ASSESSMENT","*Exm"=>"EXAM","#Tot"=>"TOTAL","#Grd"=>"GRADE","Rmk"=>"REMARK");
           $readonly = $apprv?"RegNo;Tot;Grd;CA;Exm":"Tot;Grd";
           $rowinsert = $apprv?"false":"true";
         }*/
           $rstdis .= "</table>";
      }else{ //if no student register for the course and no result exist
        // $rstdis = "No Result Found";
        $rstdis = "<table>";
        $rstdis .= "<thead><tr> <th style=\"width:5%\">SN</th><th style=\"width:15%\">Reg. No.</th><th style=\"width:25%\">Name</th>$titledis<th style=\"width:10%\">Total</th><th style=\"width:5%\">Grade</th><th style=\"width:10%\">Remark</th> </tr></thead>";
       // print_r($_GET);
        $totrw = (int)$TotRow;
       // echo $TotRow;
        for($a=1;$a<=$totrw;$a++){
          $rstdis .= "<tr class=\"???\"> <td >$a</td><td>&nbsp;</td><td>&nbsp;</td>".str_repeat("<td>&nbsp;</td>",count($scorearrdb))."<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td> </tr>";
        }
        $rstdis .= "</table>";
      }
  }
  PrintInfoBox();
   PrintBox(2);
    PrintInfoTitle("Details");
    PrintInfo("Session",$dets['SesName']);
	PrintInfo("Faculty",$dets['FacName']);
	PrintInfo("Department",$dets['ProgName']);
	PrintInfo("Level",$dets['Level']);
	PrintInfo("Semester",$dets['Semester']);
	PrintInfo("Credit Unit",$dets['CH']);
  _PrintBox();
  PrintBox(2);
  PrintInfoTitle("Statistics");
  $totrst = $totrst == 0?"":$totrst;
    PrintInfo("Total",$totrst);
	PrintInfo("Passed",($rstfound)?$passrst:"");
	PrintInfo("Failed",($rstfound)?$failrst:"");
	PrintInfo("Invalid",$invalidrst);
	PrintInfo("Edited",$edited);
	$pers = 0;
	if($totrst > 0){
	$pers = round(($passrst/$totrst)*100);
	}
	PrintInfo("Percentage",($rstfound)?$pers . "% | ".(100 - $pers)."%":"");
	//PrintInfo("Credit Unit",$dets['CH']);
  _PrintBox();
   _PrintInfoBox();
 echo $rstdis;
 //echo $query;
  
/*echo '
<div style="width:95%; margin:auto;margin-top:100px;">
<div style="width:200px;float:left;border-top:#000 solid thin;padding-top:5px;text-align:center;font-style:italic;font-size:1.1em">HOD</div>
<div style="width:200px;float:right;border-top:#000 solid thin;padding-top:5px;text-align:center;font-style:italic;font-size:1.1em">Course Lecturer</div>
</div>';  */
    // $qrpath = isset($qrpath)?$qrpath:"../../../portal/Admin/qrcoderedirect.php?id=".urlencode(_CURURL_);SlipFooter($school['Abbr'],$qrpath,"RESULT SHEET - ".$dets['CourseCode']);

   $pdf->_HTML();
  $pdf->Finish();
?>