<?php
//sleep(1000);
//LE - 22-5-17 #2
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
require("../../../../general/getinfo.php");
$sch = GetSchool();
function Error($title,$text){
    Box("class=defaultTabText");
    Box("style=color:red");Icon("exclamation-triangle fa-3x");_Box();
    Box();echo $title;_Box();  
    Box();echo $text;_Box();  
  _Box();
  
  }
AllowUser("RUpload");
/******************************************** */
//exit();

/******************************************** */
//require("../../../../epconfig/GenScript/PHP/getinfo.php");//hold basic functions to perform some common database operations or request
//get the score fields
$POST = array();
$POSTTXT = array();
$detarr = array("sestb","rstudstudy","rstudfac","rstuddept","rstudprog","rstudlvl","semest","rcourse","classid","RstInfoID","LoadType");
foreach($detarr as $key){
    $pst = $_POST[$key];
     $expst = explode(":",$pst);
    $POST[$key] = $expst[0];
    $POSTTXT[$key] = rawurldecode($expst[1]);
}
$POSTTXT['semlabel'] = $sch['SemLabel'];
extract($POST);
//exit(json_encode($POST));

//exit($RstInfoID);
$scorestrcs = $dbo->Select("scorestruc_tb","","RstInfoID=".$RstInfoID);
$scorearr = ["*SC1"=>"ASSESSMENT","*SC2"=>"EXAM"];
$maxScorarr = ["SC1"=>30.0,"SC2"=>70.0];
$cnter = 1;
if(is_array($scorestrcs) && $scorestrcs[1] > 0){
   while($scr = $scorestrcs[0]->fetch_assoc()){
    $scorearr["*SC".$cnter] = $scr['Title'];
    $maxScorarr["SC".$cnter] = $scr['MaxScore'];
    $cnter++;
   }
}



//variable to determine if exceed max operation done
$MaxReverse = false;

if($_POST['empty']){  //if empty records
     $header=array_merge(array("*RegNo"=>"REGISTRATION NO."),$scorearr,array("#Tot"=>"TOTAL","#Grd"=>"GRADE","Rmk"=>"REMARK"));
     Box("class=ep-animate-opacity");
      SpreadSheet("rowselect=false,style=width:calc(100% - 12px);margin:auto;margin-top:6px;margin-bottom:6px,id=sprstupload,multiselect=false,cellfocus=,cellblur=Exams.ResultUpload.OnBlur,cellkeypress=Exams.ResultUpload.CellKeyPress,readonly=Tot;Grd,dynamiccolumn=true,dynamicrow=true,minrow=-1,dependables=CA:Grd~Tot;Exm:Grd~Tot,rowdelete=false",$header);
      _Box();
        exit(); 
}

//["sestb","rstudstudy","rstudfac","rstuddept","rstudprog","rstudlvl","semest","rcourse"]
if(isset($sestb)){ //if result details send
  // print_r($_POST);
  $dump = array(); //hold all data to be loaded in spreadsheet
 // $filtertb = isset($filtertb)?(int)$filtertb:1; //get the filter value 22-5-17 #1

 //Get the approval status
 //************************************************* */
  $queryapprv = "SELECT * FROM resultapprove_tb WHERE ProgID = $rstudprog AND Ses = $sestb AND Lvl = $rstudlvl AND Sem = $semest AND CourseID = $rcourse AND StudyID = $rstudstudy LIMIT 1";
  $apprst = $dbo->RunQuery($queryapprv);
  $apprv = false;//hold the result approval status 
  $editable = true; //indicate if result will be editable
  if(is_array($apprst)){
    
      if($apprst[1] > 0){
          $apprstrw = $apprst[0]->fetch_array();
          //echo $apprstrw['ID'];
          if($apprstrw['Status'] == "TRUE"){
              $apprv = true;
          }
          if($apprstrw['Editable'] == "FALSE"){
            $editable = false;
        }
        /* 
        //Use the structure save in approval
        if(!is_null($apprstrw['ScoreStruc'])){
          $scorearr = $maxScorarr = [];
          $scorearrdb = json_decode($apprstrw['ScoreStruc'],true);
          if(!is_null($apprstrw['ScoreStrucMax'])){
            $maxScorarrdb = json_decode($apprstrw['ScoreStrucMax'],true);
          }
          $aacnt = 1;
          foreach($scorearrdb as $sind => $ScoreT){
            $scorearr["*SC".$aacnt] = $ScoreT;
            $maxScorarr["SC".$aacnt] = isset($maxScorarrdb[$sind])?$maxScorarrdb[$sind]:0;
            $aacnt++;
          }
        } */
        
      }
  }
//************************************************* */




  //if to load from import operation
  //************************************************* */
  $importdata = [];
if(((isset($_POST['import']) && (int)$_POST['import'] == 1) || isset($_POST['sdatastr'])) && $apprv == false && $editable == true){
  
//if data sent to be redisplayed
if(isset($_POST['sdatastr'])){
  $dataReload = $dbo->DataArray($_POST['sdatastr']);
 /*  print_r($dataReload);
  print_r($_POST['rstScoreStruc']);
  print_r($_POST['rstScoreStrucID']);
  print_r($_POST['rstScoreStrucMax']);
  print_r($_POST['discol']); */
  /* Array ( [SheetID] => sprstupload [MaxDataRow] => 2 [1_ID] => 0 [1_readonly] => false [1_disable] => false [1_deleted] => false [1_position] => 1 [1_1] => 95131173DG [1_2] => JOHN DOE CHRIS [1_8] => 3279 [2_ID] => 0 [2_readonly] => false [2_disable] => false [2_deleted] => false [2_position] => 2 [2_1] => AK2019/L12/BOT/002 [2_2] => Adegoke John bunmi [2_8] => 3279 [1_3] => 12 [1_7] => F [1_6] => 43 [1_4] => 11 [1_5] => 21 [2_3] => 11 [2_7] => F [2_6] => 43 [2_4] => 21 [2_5] => 11 ) 
  ["TEST","EXAMINATION","PRACTICAL"]
  ["SC1","SC2","SC3"]
  ["40.00","60.00","20.00"]
  RegNo=1&Name=2&SC1=3&SC2=4&SC3=5&Tot=6&Grd=7&RstRegCID=8 */
  $discolarr = $dbo->DataArray($_POST['discol']);
  $scoreIds = json_decode($_POST['rstScoreStrucID'],true);
  //exit();
  $totcols = (int)$_POST['scl'];
 /*  Array ( [registration no.] => Array ( [0] => TEST [1] => EXAMINATION [2] => PRACTICAL ) [95131173dg] => Array ( [0] => 12 [1] => 31 [2] => 12 ) [ak2019/l12/bot/002] => Array ( [0] => 11 [1] => 21 [2] => 11 ) ) */
  //if($totcols > 0){
    $recs = (int)$dataReload['MaxDataRow'];
    if($recs > 0){
      $importdata["RegNo"] = json_decode($_POST['rstScoreStruc'],true);
      //get the 
     for($rw=1; $rw<= $recs;$rw++){
       $RegNo = $dataReload[$rw."_".$discolarr['RegNo']];
       $scoress = [];
       $allnotseen = true;
       foreach($scoreIds as $inScID){
         if(isset($dataReload[$rw."_".$discolarr[$inScID]]) && trim($dataReload[$rw."_".$discolarr[$inScID]]) != ""){
          $scoress[] = $dataReload[$rw."_".$discolarr[$inScID]];
          $allnotseen = false;
         }else{
          $scoress[] = "";
         }
       }
       if(!$allnotseen){
        $importdata[strtolower($RegNo)] = $scoress;
       }
       
     }
    }
     
    //exit(json_encode($importdata));

 // }
}else{
  require_once($configdir.urldecode($_POST['Require'])."Excel/CLASSES/PHPExcel.php");
  include "../Gen/loadexcel.php";
  $colregno = $_POST['colregno'];
  $scorarr = [];
  $totScStr = (int)$_POST['TotSC'];
  for($scrn = 1;$scrn <= $totScStr;$scrn++ ){
   $scorarr[] = $_POST['SCE'.$scrn];
  }
      /* $colca = $_POST['colca'];
      $colexam = $_POST['colexam']; */
      
     $excellarray = ExcelToArray("sprstupload_file",$colregno,$scorarr);
    // print_r($excellarray);
    // exit;
     //exit($excellarray);
  if(is_array($excellarray)){
      $importdata = $excellarray;
  }
}


}
//************************************************* */

$oldcourseid = 0;
$coursesarr = [$rcourse];
Hidden("courseids",$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;
}

//Load Result of all Registered Student
//************************************************* */
$query = "";
foreach($coursesarr as $indcourseid){
  $query .= $query != ""?" UNION ":"";
  //query to get all registered student for the course
  $query .= "SELECT c.RegNo,r.Rst,s.SurName, s.FirstName, s.OtherNames, r.ID as RstID,r.GroupID,r.RstInfo,'$indcourseid' as CourseID,s.StartSes 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 c.Sem = r.Sem AND c.Lvl = r.Lvl 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 = $classid";
  if((int)$LoadType == 2){ //if Main Student Only
    $query .= " AND c.Lvl = ".$rstudlvl;
  }else if((int)$LoadType == 3){
    $query .= " AND c.Lvl != ".$rstudlvl;
  }
}



  $query .= " ORDER BY StartSes DESC, RegNo ASC, GroupID DESC";//c.Lvl = {$rstudlvl} AND
//echo $query;
//exit($query);
  $rst = $dbo->RunQuery($query);

  //preapare the spreadsheet header
  $header=array_merge(array("*RegNo"=>"REGISTRATION NO."),$scorearr,array("#Tot"=>"TOTAL","#Grd"=>"GRADE","-RstRegCID"=>"CourseID"));//,"Rmk"=>"REMARK"
  $readonly = "Tot;Grd";
  $rowinsert = "true";

  //Get the school result setting
  $grdstr = $dbo -> SelectFirstRow("resultinfo_tb","","ID = $RstInfoID");
          $grdstr = is_array($grdstr)?$grdstr[1]:"";

          //Get All the Grading
          $schgrdstr = GetGradeDetAll($RstInfoID);

          //Get the Grade base on the score (Score = -1 get for all range of score)
          //keep the grading structure (formated) in an hidden element for easy access on spreadsheet
          Box("id=gradeStruc,style=display:none");
          echo GetGrade(-1,$grdstr,$schgrdstr,$RstInfoID);
          _Box();

          
 // echo $query;
 $studreg = true; //hold if details from course reg or directly from result
  if(is_array($rst)){
       //if no student found based on course registration, get student from result_tb
      if($rst[1] < 1 && (int)$classid < 1){
        $nruery = "";
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}=%')";
if((int)$LoadType == 2){ //if Main Student Only
  $nruery .= " AND Lvl = ".$rstudlvl;
}else if((int)$LoadType == 3){
  $nruery .= " AND Lvl != ".$rstudlvl;
}
}
           

           $nruery .= " ORDER BY RegNo ASC, GroupID DESC";
           $rst = $dbo->RunQuery($nruery);
           $studreg = false;
      }
     // if student found
      if($rst[1] > 0){
          
          $lstReg = "";
          $lca = ""; $lex = "";
          $RstArr = array();
          $RstIDs = array();
          //Loop through all student and form the result data for each student
          while($reg = $rst[0]->fetch_array()){
              //22-5-17 #2 check student class by filter to dertemin which set of student to load - stoped
              /*if($filtertb > 1){ //if the filter is not all
               //get student level
              // $currentstudLvl = StudLevel($reg["RegNo"]);
              // $rstudlvl
                if($filtertb == 2){
                    
                }
              }*/
              $rwID = $reg['RstID'];
              if(!is_null($rwID) && in_array($rwID,$RstIDs))continue;
              if(!is_null($rwID))$RstIDs[] = $rwID;
              $rwID = "0"; //default rwID(ResultID) which indicate no course result found for the current student
              $ca = ""; $ex = ""; $tot = ""; $grd="";$studrst = "";
              if($studreg){ //if student details gotten via coursereg and studentinfo tb
                //concatinate the names
               $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="";
//hold array of individual score
$arrscor = [];
              //If student result is from uploaded excell file and it exist
              if(count($importdata) > 0 && isset($importdata[strtolower(trim($reg["RegNo"]))])){
                 $rstimp = $importdata[strtolower(trim($reg["RegNo"]))]; //get the student result ca and exam
                 /* $ca = (float)$rstimp[0]; //ca
                        $ex = (float)$rstimp[1]; //exam
                        $tot = $ca + $ex; //total */
                        $tot = 0;
                        $impsccnt = 1;
                        foreach($rstimp as $impscor){
                          if(isset($maxScorarr["SC".$impsccnt]) && (float)$impscor > (float)$maxScorarr["SC".$impsccnt]){
                            $impscor=$maxScorarr["SC".$impsccnt];
                            $MaxReverse = true;
                          }
                          $tot += (float)$impscor;
                          $arrscor[] = (float)$impscor;
                          $impsccnt++;
                        }
                        $grds = GetGrade($tot,$grdstr,$schgrdstr,$RstInfoID); //get the grade based on total score
                       $grds = $grds["Grade"]; //Get the score grade string
                       $rwID = $reg['RstID']; //the student rslt ID from result tb, if exist
              }elseif($reg["Rst"] != ""){ //if not from exel file and student has result
                //break down the result string to get the loaded course result
                  $rstarr = explode("&",$reg["Rst"]);
                  //exit(json_decode($reg['RstInfo'],true));
                  $rstinfo = (is_null($reg['RstInfo']) || trim($reg['RstInfo']) == "" || trim($reg['RstInfo']) == "[]")?[]:json_decode($reg['RstInfo'],true);
                  
                  
                  foreach($rstarr as $rststr){
                    //result structure new
                    //CourseID=ca|Exam|GrdPoint|Grade|GrDescr|Pass(0 or 1)
                      $rstbr = explode("=",$rststr);
                      //check if the current student result is the selected course
                      if((int)$rstbr[0] == (int)$rcourse){
                        //get the ca and exam
                        $scorarr = explode("|",$rstbr[1]);
                        
                        $ca = $scorarr[0];//ca or scores (>v3)
                        $ex = $scorarr[1]; //exam
                        //check if new score type
                        $arrscor = explode(",",$ca);
                        if(count($arrscor) > 1){//scores (>v3)
                          $tot = array_sum($arrscor);
                        }else{
                          $tot = $ca + $ex; //total
                          $arrscor = [$ca,$ex];
                        }
                        
                        $rstgrd = isset($rstinfo[$rcourse]['GradeStruc'])?$rstinfo[$rcourse]['GradeStruc']:"";
                        if(trim($rstgrd) == ""){ //if grading details not exist
                          //get the grade
                          $grds = GetGrade($tot,$grdstr,$schgrdstr,$RstInfoID); 
                          
                        }else{
                          //exit($rstgrd);
                          $grds = GetGradeFromString($tot,$rstgrd);
                          //$grds = $scorarr[3];
                        }
                        $grds = $grds["Grade"];
                        //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)
                        break;
                      }
                  }
                  
              }
              //$scorearr
              //Re apropriate score field
              $reaprscrarr = $arrscor;

              //if the derived scores are higher than the expexted
              if(count($arrscor) > count($scorearr)){ 
                $reaprscrarr = array_values($scorearr); //preaper the resultant scores array by using the expected
                foreach($arrscor 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($arrscor) < count($scorearr)){ 
                //get the remaining pos
                $rem = count($scorearr) - count($arrscor);
                //if no result found at all set fileds to "" else 0
                $reaprscrarr = count($arrscor) > 0?array_merge($reaprscrarr,array_fill(0, $rem, 0)):array_merge($reaprscrarr,array_fill(0, $rem, ""));
              }

              if($studreg){//if student details gotten via coursereg and studentinfo tb
            $dump[] = array_merge(array($reg["RegNo"],$name),$reaprscrarr,array($tot,$grds,$cid,"ID"=>$rwID));
              }else{ //if directely from result, student name not identified
               $dump[] = array_merge(array($reg["RegNo"]),$reaprscrarr,array($tot,$grds,$cid,"ID"=>$rwID));   
              }

              //Check if Updated Copy (if the last loaded student is same as the current student)
              if($lstReg == $reg["RegNo"]){ //if updated copy exist and ca/ex not the same
               //if($lca != $ca || $lex != $ex){
                 //check if the old score is not the current one (display as updated result)
                 //$RstArr - hold array of student result in this format - "RegNo"."|".$ca."|".$ex (use as lookup if student result is a duplicate)
               if(!in_array($reg["RegNo"]."|".implode("|",$reaprscrarr),$RstArr)){
                  $dump[count($dump) - 1]["logo"] = "#history";
                  $dump[count($dump) - 1]["info"] = "Outdated Copy";
                  $dump[count($dump) - 1]["disable"] = "true";
                  //#########################
                  //if not to display outdated result - still need to work on it being dynamic
                  //array_pop($dump);
                  //##############################
               }else{ //if duplcate
                   //remove from array i.e - duplicate result 
                   array_pop($dump);
               }
              }

              //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
              
                $dump[count($dump) - 1]["logo"] = "#exclamation-triangle";
                  $dump[count($dump) - 1]["info"] = "Invalid Student";
                  $dump[count($dump) - 1]["disable"] = "true";
              }
             // if(!array())
              $lstReg = $reg["RegNo"]; //keep the regno as last loaded, to be use to check next student if updated result
              $RstArr[] = $reg["RegNo"]."|".implode("|",$reaprscrarr); //keep the student result to check duplicate result for the next student
              $lca = $ca; 
              $lex = $ex;
          }

          //form the fieldid array
          $scoorfields = [];
          foreach($scorearr as $fild=>$farr){
            $scoorfields[] = ltrim($fild,"*");
          }

         // Form the spreadsheet Header
         if($studreg){//if student details gotten via coursereg and studentinfo tb
          //$header=array_merge(array("*RegNo"=>"REGISTRATION NO.",$scorearr,array("#Tot"=>"TOTAL","#Grd"=>"GRADE","-RstRegCID"=>"CourseID"));
          $header=array_merge(array("*RegNo"=>"REGISTRATION NO.","*Name"=>"FULL NAME"),$scorearr,array("#Tot"=>"TOTAL","#Grd"=>"GRADE","-RstRegCID"=>"CourseID"));//,"Rmk"=>"REMARK"
          //if result already approved disable entering and row insert
          $readonly = ($apprv || $editable == false)?"RegNo;Name;Tot;Grd;".implode(";",$scoorfields):"RegNo;Name;Tot;Grd";
           $rowinsert = "false";
         }else{
           $header = array_merge(array("*RegNo"=>"REGISTRATION NO."),$scorearr,array("#Tot"=>"TOTAL","*Grd"=>"GRADE","-RstRegCID"=>"CourseID"));//,"Rmk"=>"REMARK"
           //if result already approved disable entering and row insert
           $readonly = ($apprv || $editable == false)?"RegNo;Tot;Grd;".implode(";",$scoorfields):"Tot;Grd";
//note - for result from result_tb only row insert is enabled if not approved
           $rowinsert = ($apprv || $editable == false)?"false":"true";
         }
           
      }else{ //if no student register for the course and no result exist
         $header = array_merge(array("*RegNo"=>"REGISTRATION NO."),$scorearr,array("*Tot"=>"TOTAL","*Grd"=>"GRADE","-RstRegCID"=>"CourseID"));//,"Rmk"=>"REMARK"
           $readonly = ($apprv || $editable == false)?"RegNo;Tot;Grd;".implode(";",$scoorfields):"Tot;Grd";
           $rowinsert = ($apprv || $editable == false)?"false":"true"; 
      }
  }
 
  //Display the Spreadsheet
  Box("class=ep-animate-opacity,id=rstshinner");
  $dependable = implode(":Grd~Tot;",$scoorfields).":Grd~Tot";
  if($MaxReverse){
    Note();echo "Note: All score exceeding the Maximum Alocated Score(MAS) are reset to the Maximum Value";_Note();
    Line();
  }
      SpreadSheet("rowselect=false,style=width:calc(100% - 12px);margin:auto;margin-top:0px;font-size:0.85em;margin-bottom:6px,id=sprstupload,multiselect=false,cellfocus=,cellblur=Exams.ResultUpload.OnBlur,cellkeypress=Exams.ResultUpload.CellKeyPress,disable=$readonly,dynamiccolumn=false,dynamicrow=$rowinsert,minrow=-1,dependables=$dependable,rowfilter=true,filtertitle=FILTER RESULT SHEET,filterstyle=width:calc(100% - 12px);margin:auto,rowdelete=false",$header,$dump);
      
        //"rstudstudy","rstudfac","rstuddept","rstudprog","rstudlvl","semest","rcourse"
//Display Result Details Bellow
   echo '<div style="margin-left:20px;color:#CCC;font-weight:bold">'.strtoupper($POSTTXT['sestb']." | ".$POSTTXT['rstudstudy']." | ".$POSTTXT['rstudfac']." | ".$POSTTXT['rstudprog']." | ".$POSTTXT['rstudlvl']." | ".$POSTTXT['semest']." ".$sch['SemLabel']).'</div>';

   //echo the import file type
   echo '<input type="file" id="sprstupload_file" name="sprstupload_file" onchange="Exams.ResultUpload.PerformImport(this)" style="position:absolute;display:none" accept=".xls,.xlsx" />';

   
_Box();
//keep parameters in hidden elemts
   Hidden("dispdet",$dbo->DataString($POSTTXT));
   Hidden("dispdetid",$dbo->DataString($POST));
   Hidden("dispdetappr",$apprv);
   //put the result score structure in an hidden div to be used in main.js
   echo '<div style="display:none" id="rstScoreStruc">'.json_encode(array_values($scorearr)).'</div>';
   echo '<div style="display:none" id="rstScoreStrucMax">'.json_encode(array_values($maxScorarr)).'</div>';
   echo '<div style="display:none" id="rstScoreStrucID">'.json_encode($scoorfields).'</div>';
   echo '<div style="display:none" id="rstType">'.$LoadType.'</div>';
     //Hidden("dispdet",implode(";",$POSTTXT));$maxScorarr
}

?>