<?php
ini_set("memory_limit","-1");
$baseurl = "../../../";
/* require_once($baseurl."epconfig/TaquaLB/Ajax/CGI/PHP/config.php");
LoadFile("pdfprint",$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";

function LevelinSes($Ses, $StartSes, $MOE){
    $moe = $MOE;
		$moe = GetMOEID($moe);
		$startSes = (int)$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;

}

$pdf = new PDFPrinter();
$pdf->SetBasePath($configdir."Files/");



function ErrorBox($title="")
{
    global $pdf;
    $pdf->Dump($title);
    $pdf->Finish();
    exit;
}

extract($_GET);

if(!isset($RegNo)){
    ErrorBox("Invalid Student: No Student Selected. Search and Select a Student to Generate Result Ledger");
}

//get the student details
$studDet = GetBasicInfo($RegNo);
if(!is_array($studDet)){
    ErrorBox("Invalid Student: Reading Student Record Failed");
}

$YOS = (int)$studDet['YearOfStudy'];
if($YOS < 1){
    ErrorBox("Invalid Year of Study Setup");
}
    $StartSes = $studDet['StartSes'];
    $MOE = $studDet['ModeOfEntry'];

    //get sessions
    $studSessions = $dbo->Select("session_tb","","SesID >= $StartSes ORDER BY SesID LIMIT $YOS");
    if(!is_array($studSessions)){
        ErrorBox("Reading Student Academic Session Failed");
    }
    $ValidAccdSessions = [];
    $maxStudSes = 0;
    while($indStudSes = $studSessions[0]->fetch_assoc()){
        $ValidAccdSessions[$indStudSes['SesID'].""] = $indStudSes;
        $maxStudSes = $indStudSes['SesID'];
    }

    //get all student result'
    $AllRst = $dbo->Select("result_tb r, session_tb s","r.*,s.SesName","r.RegNo='".$dbo->SqlSafe($RegNo)."' AND r.SesID = s.SesID ORDER BY r.SesID, r.Lvl, r.Sem, r.GroupID DESC");
    if(!is_array($AllRst)){
        ErrorBox("Operation Failed: Fetching Student Result Failed");
    }

    if($AllRst[1] < 1){
        ErrorBox("Operation Failed: Fetching Student Result Failed");
    }

    $rstArray = [];
    $LevelNameCache = [];
    $SemesterCache = [];
    $spilloverSes = [];
    $maxRstBySem = [];
            while($indrst = $AllRst[0]->fetch_assoc()){
                $lookupkey = $indrst['SesID'].$indrst['Sem'];
                if(isset($rstArray[$indrst['SesID']][$indrst['Sem']]))continue;
                if($indrst['SesID'] > $maxStudSes){
                    $spilloverSes[$indrst['SesID'].""] = ["SesName"=>$indrst['SesName']];
                }
                if(!isset($LevelNameCache[$indrst['Lvl']])){
                    $LevelNameCache[$indrst['Lvl']] = LevelName($indrst['Lvl'], $studDet['StudyID']);
                }
                if(!isset($SemesterCache[$indrst['Sem']])){
                    $SemesterCache[$indrst['Sem']] = SemesterName($indrst['Sem']);
                }
                
                /* Table("style=width:calc(100% - 0px);margin:20px auto;text-align:left,id=totalrpt,multiselect=false,data-type=table");
                THeader(["{$LvlName} ({$SemName} SEMESTER {$indrst['SesName']})"],"style=font-weight:bolder;text-align:center; font-size:1.2em; text-transform:uppercase,cspan=d1:4");
                THeader(["COURSE CODE", "CH", "SCORE/GRADE", "GP"],"style=text-align:left"); */
                
                $studrst =  $indrst['Rst'];
                $RstInfo =  json_decode($indrst['RstInfo'],true);
                $ResultScores= [];
               if(trim($studrst) != ""){
                   $studrstarr = explode("&",$studrst);
                   if(count($studrstarr) > 0){
                       //initialize display rst variable 
                       
                       foreach($studrstarr as $studindrst){
                           $studindrstArr = explode("=",$studindrst);
                           if(count($studindrstArr) > 1){
                               $courseID = $studindrstArr[0];
                               $indstudrst = $studindrstArr[1];
                               //get ca and exam
                               $indrstArr = explode("|",$indstudrst);
                               if(strpos($indrstArr[0],",") === false){ //if old
                                 $indrstArr[0] = $indrstArr[0].",".$indrstArr[1];
                               }
                                //check if course det exist
                                if(isset($RstInfo[$courseID])){
                                    $courseDet = $RstInfo[$courseID];
                                }else{
                                    $courseDet = isset($allcourses[$courseID])?$allcourses[$courseID]:CourseDetails($courseID);
                                }
                               // $tot = (int)$indrstArr[0] + (int)$indrstArr[1];
                               $tot = array_sum(explode(",",$indrstArr[0]));
                               if(count($indrstArr) > 2){
                                 $pass = (int)$indrstArr[5];
                                 $grdval = $indrstArr[3];
                                 $grdlvl = (int)$indrstArr[2];
                                 $grdPoint = (int)$indrstArr[7];

                               }else{
                                   
                                  $grds = GetGrade($tot,$grdstr,$schgrdstr);
                                  $pass = (int)$grds["PASS"];
                                  $grdval = $grds["Grade"];
                                  $grdlvl = (int)$grds["Level"];
                                  $grdPoint = $grdlvl * $courseDet['CH'];
                               }
       
                              
                               

                               $ResultScores[$courseID] = ["Total"=>$tot, "Pass"=>$pass, "Grade"=>$grdval, "GradeLevel"=>$grdlvl, "CourseDetails"=>$courseDet, "GradePoint"=>$grdPoint];
                            //   THeader(["COURSE CODE", "CH", "SCORE/GRADE", "GP"],"style=text-align:left");
                               /* TRecord([$courseDet['CourseCode'], $courseDet['CH'],$tot." ".$grdval, $grdlvl ],"data-id=studrstledger,style=text-transform:uppercase"); */
                             // $TCH += (int)$courseDet['CH'];
                              //$TGP += $grdlvl * (int)$courseDet['CH'];
                              
                           }
                       }
                   }
               }
               /* $GPA = number_format($indrst['GPA'],2);
               $CGPA = number_format($indrst['CGPA'],2);
               TRecord(["TCH", $indrst['TCH'],"TGP", $indrst['TGP']],"style=text-transform:uppercase;font-weight:bolder");
            //    TRecord([],"style=text-transform:uppercase;font-weight:bolder,cspan=d2:3");
               TRecord(["GPA", $GPA, "CGPA", $CGPA],"style=text-transform:uppercase;font-weight:bolder");
               unset($indrst['Rst']);
               unset($indrst['RstInfo']); */
               $indrst['LevelName'] = $LevelNameCache[$indrst['Lvl']];
               $indrst['Semester'] = $SemesterCache[$indrst['Sem']];
               $indrst['Result'] = $ResultScores;
               if(!isset($maxRstBySem[$indrst['Sem']]) || $maxRstBySem[$indrst['Sem']] < count($ResultScores))$maxRstBySem[$indrst['Sem']] = count($ResultScores);
               $rstArray[$indrst['SesID']][$indrst['Sem']] = $indrst;
                /* _Table(); */
            }

            if(count($rstArray) < 1){
                ErrorBox("No Result Found");
            }

            //total sessions
            $totalRstSess = count($ValidAccdSessions) + count($spilloverSes);
            $totalPossibleCells = $totalRstSess * 4;
            $threeTopCellSize = floor($totalPossibleCells / 3);
            $CenterTopCellSize = $totalPossibleCells - ($threeTopCellSize * 2);

            // $rstType= '';
            $topdet = '<div style="width:100%;margin-top:10px">

        <div style="width:33.3%;float:left;text-align:left;text-transform:uppercase">
          <b>FACULTY:</b> '.$studDet['Fac'].' <br/>
          <b>DEPARTMENT:</b> '.$studDet['Dept'].' <br />
          <b>PROGRAMME:</b> '.$studDet['Prog'].'
        </div>

        <div style="width:33.3%;float:left;text-align:center;font-weight:bold;text-decoration:underline">
          STUDENT RESULT LEDGER
          <div style="margin-top:10px">'.$rstType.'</div>
        </div>

        <div style="width:33.3%;float:right;text-align:right">
        &nbsp;
      </div>
   <div style="clear:both"></div>
  </div> ';
  $pdf->Header("MAIN CAMPUS/OBIO AKPA CAMPUS",array("LogoSize"=>"25px*25px","Style"=>"font-size:0.9em","WaterMark"=>"Abbr"),null,$topdet,array("Address"));

  $pdf->HTML();
?>

<table  style="width:100%;text-align:center;margin-top:5px">
 <thead>
    <tr>
        <th style="text-align:left; text-transform:uppercase" colspan="<?=$threeTopCellSize?>">
    MATRICULATION NO: <?=$RegNo?>
    </th>
        <th style="text-align:left; text-transform:uppercase" colspan="<?=$CenterTopCellSize?>">
        NAME: <?=$studDet['Name']?>
    </th>
        <th style="text-align:left; text-transform:uppercase" colspan="<?=$threeTopCellSize?>">
        SEX: <?=$studDet['Gen']?>
    </th>
    </tr>
    </thead>
 <tbody>
    <?php
$Totals = [];
    //get all posible semesters
   $sems = $dbo->Select("semester_tb","","Enable=1 ORDER BY Num, ID");
   while($indsem = $sems[0]->fetch_assoc()){
$Sem  = (int)$indsem['Num'] > 0?(int)$indsem['Num']:(int)$indsem['ID'];

?>
    <tr>
        <?php
        $tdheader = '';
        
        $Rows = array_fill(0, $$maxRstBySem[$Sem] + 3, '');
     foreach(($ValidAccdSessions+$spilloverSes) as $SesID => $sesDet ){
        $LvlID = LevelinSes($SesID, $StartSes, $MOE);
        $LName = isset($LevelNameCache[$LvlID])?$LevelNameCache[$LvlID]:LevelName($LvlID,$studDet['StudyID']);
        $SName = isset($SemesterCache[$Sem])?$SemesterCache[$Sem]:SemesterName($Sem);
        $SOrd = Ordinal($Sem);
        //check if result exist for the session and semester
        if(isset($rstArray[$SesID][$Sem]['Result']) && count($rstArray[$SesID][$Sem]['Result'])>0){
            $totRstSeen = 0;
            foreach($rstArray[$SesID][$Sem]['Result'] as $CourseID=>$Rst){
                $Rows[$totRstSeen] .= '<td>'.$Rst['CourseDetails']['CourseCode'].'</td>'.'<td>'.$Rst['CourseDetails']['CH'].'</td>'.'<td>'.$Rst['Total'].' '.$Rst['Grade'].'</td>'.'<td>'.$Rst['GradePoint'].'</td>';
                $totRstSeen++;
            }
            while($totRstSeen < $maxRstBySem[$Sem]){
                $Rows[$totRstSeen] .= str_repeat('<td></td>',4);
                $totRstSeen++;
            }
            $Rows[$totRstSeen] .= '<td style="font-weight:bold;text-align:left">TCH</td><td style="font-weight:bold;text-align:left" colspan="3">'.$rstArray[$SesID][$Sem]['TCH'].'</td>';
            $Rows[$totRstSeen + 1] .= '<td style="font-weight:bold;text-align:left">TGP</td><td style="font-weight:bold;text-align:left" colspan="3">'.$rstArray[$SesID][$Sem]['TGP'].'</td>';
            $Rows[$totRstSeen + 2] .= '<td style="font-weight:bold;text-align:left">GPA</td><td style="font-weight:bold;text-align:left" colspan="3">'.$rstArray[$SesID][$Sem]['GPA'].'</td>';
            $Totals[$SesID]['TCH'] += (int)$rstArray[$SesID][$Sem]['TCH'];
            $Totals[$SesID]['TGP'] += (int)$rstArray[$SesID][$Sem]['TGP'];


        }else{
            $totRstSeen = 0;
            while($totRstSeen < $maxRstBySem[$Sem] + 3 ){
                $Rows[$totRstSeen] .= str_repeat('<td></td>',4);
                $totRstSeen++;
            }
            
        }
      ?>
<th colspan="4"><?=$LName . " (".$SOrd." SEMESTER ".$sesDet['SesName'].")"?></th>
       <?php
    $tdheader .= '<th>COURSE CODE</th>
    <th>CH</th>
    <th>SCORE/GRADE</th>
    <th>GP</th>';
     }

        ?>
    </tr>
    <tr>
    <?= $tdheader?>
    </tr>
 
<?php
 foreach($Rows as $row){
    ?>
 <tr><?=$row?></tr>
    <?php
 }
}
?>
<tr><td colspan="<?=$totalPossibleCells?>">&nbsp;</td><th style="font-weight: bold;">CUMULATIVE</th></tr>
<?php
$TRows = ['','',''];
$TRowsV = [0,0] ;

foreach(($ValidAccdSessions+$spilloverSes) as $SesID => $sesDet ){
    
    $TRows[0] .= '<td style="font-weight:bold;text-align:left">&sum;TCH</td><td style="font-weight:bold;text-align:left" colspan="3">'.(isset($Totals[$SesID]['TCH'])?$Totals[$SesID]['TCH']:'').'</td>';
    $TRowsV[0] += isset($Totals[$SesID]['TCH'])?$Totals[$SesID]['TCH']:0;
    $TRows[1] .= '<td style="font-weight:bold;text-align:left">&sum;TGP</td><td style="font-weight:bold;text-align:left" colspan="3">'.(isset($Totals[$SesID]['TGP'])?$Totals[$SesID]['TGP']:'').'</td>';
    $TRowsV[1] += isset($Totals[$SesID]['TGP'])?$Totals[$SesID]['TGP']:0;
    $TRows[2] .= '<td style="font-weight:bold;text-align:left">GPA</td><td style="font-weight:bold;text-align:left" colspan="3">'.(isset($Totals[$SesID]['TGP']) && isset($Totals[$SesID]['TCH'])?($Totals[$SesID]['TCH']>0?number_format($Totals[$SesID]['TGP']/$Totals[$SesID]['TCH'],2):'0.00'):'').'</td>';

    /* $TRows[0] .= '<td style="font-weight:bold;text-align:left">TCH</td><td style="font-weight:bold;text-align:left" colspan="3">'.'ff'.'</td>';
    $TRows[1] .= '<td style="font-weight:bold;text-align:left">TGP</td><td style="font-weight:bold;text-align:left" colspan="3">'.'ddd'.'</td>';
    $TRows[2] .= '<td style="font-weight:bold;text-align:left">GPA</td><td style="font-weight:bold;text-align:left" colspan="3">'.'fff'.'</td>'; */
}

$TRows[0] .= '<td style="font-weight:bold;text-align:left">TCH: '.$TRowsV[0].'</td>';
$TRows[1] .= '<td style="font-weight:bold;text-align:left">TGP: '.$TRowsV[1].'</td>';
$TRows[2] .= '<td style="font-weight:bold;text-align:left">CGPA: '.($TRowsV[0]>0?number_format($TRowsV[1]/$TRowsV[0],2):0.00).'</td>';

foreach($TRows as $trow){
    ?>
<tr><?=$trow?></tr>
    <?php
}
?>
 </tbody>
</table>

<?php
  $pdf->_HTML();

  $sigarr = ["HEAD OF DEPARTMENT","DEAN","CHAIRMAN, SERVC"];
  if(isset($ReportID)){
    //check if already signed
    //StudyID=5&ProgID=23&LevelID=1&SemID=1&SesID=8&ReportID=2
    $sigparam = $dbo->DataString(json_decode($sigparam,true));
    $sigs = $dbo->SelectFirstRow("reportsig_tb","","Param='".$sigparam."'");
  if(!is_array($sigs))$sigs = $dbo->SelectFirstRow("report_tb","","ID=".$ReportID);
     if(is_array($sigs)){
      $sigarr = $sigs['Signatories'];
     }
  }
  //$pdf->Dump($sigarr);
  //$pdf->Finish();
    $pdf->FooterNote("LEDGER ( ".strtoupper($RegNo)." )",$pdf->Signataries($sigarr,"font-size:1.2em",false),array("Developer"));
    $pdf->Finish();
    exit();


?>