<?php
//require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
//require("../../../../general/getinfo.php");
 
 function Error($title,$text = ""){
    echo '<div class="defaultTabText">';
    echo '<div style="color:red"';echo '<i class="fa fa-exclamation-triangle fa-3x"></i>';echo '</div>';
    echo '<div>';echo $title;echo '</div>';  
    echo '<div>';echo $text;echo '</div>';  
    echo '</div>';
  
  }
  //check priv
  AllowUser("RSheet");
LoadFile("basic","../../../../");

extract($_POST);
//"StudyID="+_('tstudstudy').TextContent()+"&ProgID="+_('tstudprog').TextContent()+"&LevelID="+_('tstudlvl').TextContent()+"&SemID="+_('tsemest').TextContent()+"&SesID="+_('tsestb').TextContent();
if(!isset($StudyID)){ 
  exit("No Result Found");
}
if((int)$StudyID < 1){
    //get based on prog
    $sudobj = $dbo->SelectFirstRow("study_tb s, programme_tb p, dept_tb d, fac_tb f","s.ID","p.ProgID = $ProgID AND p.DeptID = d.DeptID AND d.FacID = f.FacID AND f.StudyID = s.ID");
    if(is_array($sudobj))$StudyID = $sudobj['ID'];
}
//if no study, get by progID

//exit("$ProgID,$LevelID,$SemID");
//get all expected courses 
$allcourses = GetCourses($ProgID,$LevelID,$SemID);
//echo $allcourses;
//exit();
//exit("10");
//check from result approval tb to get the result info used
$rstapprdet = $dbo->SelectFirstRow("resultapprove_tb","","ProgID=".$ProgID." AND Ses=".$SesID." AND Lvl=".$LevelID." AND Sem=".$SemID." LIMIT 1");

  $rstinfoid = is_array($rstapprdet)?$rstapprdet['RstInfoID']:"1";

//get grading details
$grdstr = $dbo -> SelectFirstRow("resultinfo_tb","","ID = $rstinfoid");
$portaldisplay = $grdstr['PortalResultDisplay'];
          $grdstr = is_array($grdstr)?$grdstr[1]:"";
          $schgrdstr = GetGradeDetAll();
   $portaldisplay = trim($portaldisplay) == ""?[]:json_decode($portaldisplay,true);
//$rst = $dbo->Select("result_tb r, studentinfo_tb s","r.*","(r.RegNo = s.RegNo OR r.RegNo = s.JambNo) AND r.Lvl = $LevelID AND r.Sem = $SemID AND r.SesID = $SesID AND s.ProgID = $ProgID ORDER BY r.RegNo");
//$rst = $dbo->RunQuery("SELECT r.* FROM result_tb r WHERE r.Lvl = $LevelID AND r.Sem = $SemID AND r.SesID = $SesID AND s.ProgID = $ProgID ORDER BY r.RegNo ASC, GroupID DESC");
$rst = $dbo->RunQuery("SELECT r.*, CONCAT(s.Surname, ' ',s.Firstname,' ',s.Othernames) as StudName, s.StartSes FROM coursereg_tb c LEFT JOIN result_tb r ON (c.RegNo = r.RegNo AND c.Lvl = r.Lvl AND c.Sem = r.Sem AND c.SesID = r.SesID) INNER JOIN studentinfo_tb s ON (r.RegNo = s.RegNo OR r.RegNo = s.JambNo) WHERE r.Lvl = $LevelID AND r.Sem = $SemID AND r.SesID = $SesID AND s.ProgID = $ProgID AND s.ClassID = $ClassID ORDER BY OTS DESC, GroupID DESC, r.RegNo ASC");
//echo "SELECT r.* FROM coursereg_tb c LEFT JOIN result_tb r ON c.RegNo = r.RegNo LEFT JOIN studentinfo_tb s ON (r.RegNo = s.RegNo OR r.RegNo = s.JambNo) WHERE r.Lvl = $LevelID AND r.Sem = $SemID AND r.SesID = $SesID AND s.ProgID = $ProgID ORDER BY r.RegNo ASC, GroupID DESC";
//{"GPA":-1,"CGPA":-1,"TOT":1,"AVG":1,"POS":1,"COP":1}
$arraysdis = [
  "GPA"=>["*TCH"=>"TCH","*TGP"=>"TGP","*GPA"=>"GPA"],
  "CGPA"=>["*CCH"=>"CCH","*CGP"=>"CGP","*CGPA"=>"CGPA"],
  "TOT"=>["*TOT"=>"TOT"],
  "AVG"=>["*AVG"=>"AVG"],
  "AVGClass"=>["*AVGClass"=>"CLASS AVG"],
  "POS"=>["*POS"=>"POS"],
  "POSClass"=>["*POSClass"=>"CLASS POS"],
  "COP"=>["*COP"=>"COP"]
];
$header=array("*RegNo"=>"REG. NO.","*StudName"=>"NAME","*RST"=>"RESULT");
foreach($portaldisplay as $distype=>$enable){
  if((int)$enable == 1 && isset($arraysdis[$distype])){
    $header = array_merge($header,$arraysdis[$distype]);
  }
}
/* if($LevelID == 1 && $SemID == 1){ //if first Result
  $header=array("*RegNo"=>"REG. NO.","*RST"=>"RESULT","*TCH"=>"TCH","*TGP"=>"TGP","*GPA"=>"GPA");
}else{
$header=array("*RegNo"=>"REG. NO.","*RST"=>"RESULT","*TCH"=>"TCH","*TGP"=>"TGP","*GPA"=>"GPA","*CCH"=>"CCH","*CGP"=>"CGP","*CGPA"=>"CGPA");
} */

$dump = array();	    
if(is_array($rst)){
    if($rst[1] > 0){
        $cnt = 1;
        $seenReg = array();
      while($indrst = $rst[0]->fetch_array()){
         // echo $cnt." => ".implode(" ; ",$indrst)."<br />";
         $studrst =  $indrst['Rst'];
         $StudName = $indrst['StudName'];
         $RstInfo =  json_decode($indrst['RstInfo'],true);
         $CCH = (int)$indrst['CCH'];
         $CGP = (int)$indrst['CGP'];
         $TOT = (int)$indrst['OTS'];
         $AVG = (float)$indrst['OAS'];
         $COP = $indrst['COP'];
         $TCH = $indrst['TCH'];$TGP = $indrst['TGP'];$RstHtml="No Result";
        if(trim($studrst) != ""){
            $studrstarr = explode("&",$studrst);
            if(count($studrstarr) > 0){
                //initialize display rst variable 
                $RstHtml="";
                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];
                        }
                        // $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];
                        }else{
                            
                           $grds = GetGrade($tot,$grdstr,$schgrdstr);
						   $pass = (int)$grds["PASS"];
                           $grdval = $grds["Grade"];
                           $grdlvl = (int)$grds["Level"];
                        }

                        //check if course det exist
                        if(isset($RstInfo[$courseID])){
                            $courseDet = $RstInfo[$courseID];
                        }else{
                            $courseDet = isset($allcourses[$courseID])?$allcourses[$courseID]:CourseDetails($courseID);
                        }
                        
                       
                       $succ = $pass == 0?"dangerre":"successse";
                       $RstHtml .= '<strong class="Labels '.$succ.'">'.$courseDet['CourseCode']." (".$tot.$grdval.")  </strong>";
                      // $TCH += (int)$courseDet['CH'];
                       //$TGP += $grdlvl * (int)$courseDet['CH'];
                       
                    }
                }
            }
        }
        $GPA = number_format($indrst['GPA'],2);
        $CGPA = number_format($indrst['CGPA'],2);
        /* $arraysdis = [
  "GPA"=>["*TCH"=>"TCH","*TGP"=>"TGP","*GPA"=>"GPA"],
  "CGPA"=>["*CCH"=>"CCH","*CGP"=>"CGP","*CGPA"=>"CGPA"],
  "TOT"=>["*TOT"=>"TOT"],
  "AVG"=>["*AVG"=>"AVG"],
  "POS"=>["*POS"=>"POS"],
  "COP"=>["*COP"=>"COP"]
]; */
$dumbstruc = $header;
if(isset($dumbstruc['*RegNo']))$dumbstruc['*RegNo']=$indrst['RegNo'];
if(isset($dumbstruc['*StudName']))$dumbstruc['*StudName']=$indrst['StudName'];
if(isset($dumbstruc['*RST']))$dumbstruc['*RST']=$RstHtml;
if(isset($dumbstruc['*TCH']))$dumbstruc['*TCH']=$TCH;
if(isset($dumbstruc['*TGP']))$dumbstruc['*TGP']=$TGP;
if(isset($dumbstruc['*GPA']))$dumbstruc['*GPA']="<b>".$GPA."</b>";
if(isset($dumbstruc['*CCH']))$dumbstruc['*CCH']=$CCH;
if(isset($dumbstruc['*CGP']))$dumbstruc['*CGP']=$CGP;
if(isset($dumbstruc['*CGPA']))$dumbstruc['*CGPA']="<b>".$CGPA."</b>";
if(isset($dumbstruc['*TOT']))$dumbstruc['*TOT']="<b>".$TOT."</b>";
if(isset($dumbstruc['*AVG']))$dumbstruc['*AVG']="<b>".$AVG."</b>";

if(isset($dumbstruc['*AVGClass'])){
  $classrstdet = GetStudentOverallClassResultDetails($indrst,["ProgID"=>$ProgID,"ClassID"=>$ClassID],true);
  $dumbstruc['*AVGClass']=round($classrstdet[2]/$classrstdet[0],2);
}
if(isset($dumbstruc['*POS']))$dumbstruc['*POS']="<b>".GetStudentResultPosition($indrst,["ProgID"=>$ProgID,"StartSes"=>$indrst['StartSes']])."</b>";
if(isset($dumbstruc['*POSClass']))$dumbstruc['*POSClass']="<b>".GetStudentResultPosition($indrst,["ProgID"=>$ProgID,"ClassID"=>$ClassID,"StartSes"=>$indrst['StartSes']],true)."</b>";
if(isset($dumbstruc['*COP']))$dumbstruc['*COP']="<b>".$COP."</b>";
$indump = array_values($dumbstruc);
        if(in_array($indrst['RegNo'],$seenReg)){
            /*
            $dump[count($dump) - 1]["logo"] = "#history";
                  $dump[count($dump) - 1]["info"] = "Outdated Copy";
                  $dump[count($dump) - 1]["disable"] = "true";
            */
          /* if($LevelID == 1 && $SemID == 1){ 
           $dump[] = array($indrst['RegNo'],$RstHtml,$TCH,$TGP,"<b>".$GPA."</b>","logo"=>"#history","info"=>"Outdated Copy","disable"=>"true");
          }else{
          $dump[] = array($indrst['RegNo'],$RstHtml,$TCH,$TGP,"<b>".$GPA."</b>",$CCH,$CGP,"<b>".$CGPA."</b>","logo"=>"#history","info"=>"Outdated Copy","disable"=>"true");
          } */
          $dump[] = array_merge($indump,["logo"=>"#history","info"=>"Outdated Copy","disable"=>"true"]);
        }else{
         /* if($LevelID == 1 && $SemID == 1){ 
          $dump[] = array($indrst['RegNo'],$RstHtml,$TCH,$TGP,"<b>".$GPA."</b>");
         }else{
          $dump[] = array($indrst['RegNo'],$RstHtml,$TCH,$TGP,"<b>".$GPA."</b>",$CCH,$CGP,"<b>".$CGPA."</b>");
         } */
         $dump[] = array_merge($indump,["readonly"=>"true","logo"=>"*ellipsis-h","info"=>"More","Action"=>"Exams.ResultReport.LoadOptions(".$indrst['ID'].",'".addslashes($indrst['StudName'])."')"]);
          $seenReg[] = $indrst['RegNo']; //add to seen regno
        }
          $cnt++;
      }
    }
}
Box("class=ep-animate-opacity");

SpreadSheet("rowselect=false,style=width:calc(100% - 12px);margin:auto;margin-top:0px;margin-bottom:6px,id=sprstrpt,multiselect=false,readonly=RegNo;TCH;TGP;GPA;CCH;CGP;CGPA;RST,dynamiccolumn=false,dynamicrow=false,minrow=-1,rowfilter=true,filtertitle=FILTER RESULT SHEET,filterstyle=width:calc(100% - 12px);margin:auto,rowdelete=false,trimtext=<strong class\=\"Labels successse\">;</strong>;<strong class\=\"Labels dangerre\">;<b>;</b>",$header,$dump);
_Box();
$sch = GetSchool("SemLabel");
$semlabel = trim($sch['SemLabel']);
$rstinfoa = $dbo->RunQuery("SELECT f.FacName, d.DeptName, p.ProgName, p.YearOfStudy,s.SesName,sm.Sem, c.Name as ClassName FROM fac_tb f, dept_tb d, programme_tb p, session_tb s, semester_tb sm, studentclass_tb c WHERE f.FacID = d.FacID AND d.DeptID = p.DeptID AND s.SesID = $SesID AND ((sm.Num > 0 && sm.Num = $SemID) || (sm.ID = $SemID && sm.Num = 0)) AND p.ProgID = $ProgID AND p.ProgID = c.ProgID AND c.ID = $ClassID LIMIT 1");
$info = "RESULT SHEET";
if(is_array($rstinfoa)){
  if($rstinfoa[1] > 0){
      $rsstii = $rstinfoa[0]->fetch_array();
      $LevelName = LevelName($LevelID, $StudyID);
      $info .= " - ".$rsstii['SesName']." | ".$rsstii['ProgName']." | ".$LevelName." (".$rsstii['ClassName'].") | ".$rsstii['Sem']. " ".$semlabel ;
  }
}
Hidden("rstinfobs",$info);
?>