<?php
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
require("../../../../general/getinfo.php");
AllowUser("rstfix");
//require("../../../../epconfig/GenScript/PHP/getinfo.php");
//check if to get valid student only
if(isset($_POST['GetRegNos'])){
    $RegNos = trim($_POST['GetRegNos']);
    $userdept = trim($_POST['UserDet']);
    if($RegNos == "")exit("#"); //no valid reg no supplid
    //convert to object
    $RegNos = json_decode($RegNos,true);
    //check if it is to be loaded
    if(isset($RegNos['StudyID'])){
        $field = "GROUP_CONCAT((IF(TRIM(s.RegNo) = '',s.JambNo,s.RegNo)) SEPARATOR ',') as RegNos";
        $fields = "s.id,s.RegNo";
        $tbs = "studentinfo_tb s";
        //{"SesID":0,"StudyID":0,"FacID":0,"DeptID":0,"ProgID":0,"LvlID":0}
        $studq = ((int)$RegNos['StudyID'] > 0)? "IF(TRIM(s.RegNo) = '',s.JambNo,s.RegNo) != '' AND s.StudyID = ".$RegNos['StudyID']:"IF(TRIM(s.RegNo) = '',s.JambNo,s.RegNo) != ''";
        
        if((int)$RegNos['ProgID'] > 0){
            $studq .= " AND s.ProgID = ".$RegNos['ProgID'];
        }else{
             if((int)$RegNos['DeptID'] > 0){
                    $studq .= " AND s.ProgID = p.ProgID AND d.DeptID = p.DeptID AND d.DeptID = ".$RegNos['DeptID'];
                    $tbs .= ",programme_tb p, dept_tb d";
                }else if((int)$RegNos['FacID'] > 0){
                    $studq .= " AND s.ProgID = p.ProgID AND d.DeptID = p.DeptID AND d.FacID = f.FacID AND f.FacID = ".$RegNos['FacID'];
                    $tbs .= ",programme_tb p, dept_tb d, fac_tb f";
                }
               // $facq = ((int)$RegNos['FacID'] > 0)? "StudyID = ".$RegNos['StudyID']:"StudyID != 0";
        }
        if((int)$RegNos['LvlID'] > 0){
            
            $CurSes = CurrentSes();
            $CurSes = $CurSes['SesID'];
            $studq .= " AND ($CurSes - s.StartSes + IF(TRIM(s.ModeOfEntry) = '',1,IF(s.ModeOfEntry = 'UTME',1,IF(s.ModeOfEntry = 'Direct-Entry',2,(0+s.ModeOfEntry)))))  = ".(int)$RegNos['LvlID'];
            //calculate the startses
        }
        //get the total number character of all student regno + number of regno (to takecare of the commas)
        $extimatedchars = $dbo->SelectFirstRow("studentinfo_tb","(sum(CHAR_LENGTH(if(trim(RegNo)='',JambNo,RegNo)))+count(id)) as len");
         $totalch = !is_array($extimatedchars)?5353674748:$extimatedchars['len'];
        $setmax = $dbo->RunQuery("SET SESSION group_concat_max_len=$totalch;");

        $query = "SELECT $field FROM $tbs WHERE s.RegLevel=6 AND $studq";
        $runquery = $dbo->RunQuery($query);
        if(!is_array($runquery)){
            exit("##"); //Internal Error
        }
$queryrst = $runquery[0]->fetch_assoc();
if(!is_null($queryrst['RegNos'])){
$RegNo = $queryrst['RegNos'];
$RegNoarr = explode(",",$RegNo);
$rtn = array("Total"=>count($RegNoarr),"RegNos"=>$RegNoarr,"TotalBad"=>0,"BadRegNos"=>array(),"Q"=>$query);
}else{
    $rtn = array("Total"=>0,"RegNos"=>array(),"TotalBad"=>0,"BadRegNos"=>array(),"Q"=>$query);  
}

//exit(json_encode($rtn));
      //exit($query);
    }else{
        //get valid students
        //$userdet = 
      if(count($RegNos) < 1)exit("#");
      $deptasignsql = "";
      if(trim($userdept) != ""){
        $deptasignsql = "AND (ProgID=".str_replace("~", " or ProgID=",$userdept).")";  
      }
      //exit($deptasignsql);
      $GoodStud = array(); $BadStud = array();
      $RegNos = array_unique($RegNos);
     // sort($RegNos);
      foreach($RegNos as $RegNo){
          if(trim($RegNo) == "")continue;
          //check if exist
          $chkreg = $dbo->SelectFirstRow("studentinfo_tb","id","(RegNo='$RegNo' OR (TRIM(RegNo)='' && JambNo='$RegNo')) $deptasignsql LIMIT 1");
          if(is_array($chkreg)){
            $GoodStud[] = $RegNo;
          }else{
            $BadStud[] = $RegNo;
          }
      }
      $rtn = array("Total"=>count($GoodStud),"RegNos"=>$GoodStud,"TotalBad"=>count($BadStud),"BadRegNos"=>$BadStud);
      
    }
    //get all result infos 
    $rstinfos = $dbo->Select("resultinfo_tb","ID,SettingName");
    if(is_array($rstinfos) && $rstinfos[1] > 0){
        
        $rstsetarr = [];
        while($indrstinfo = $rstinfos[0]->fetch_assoc()){
            $rstsetarr[$indrstinfo['ID']] = $indrstinfo['SettingName'];
        }
        
    }
 
echo json_encode($rtn)."@@##!!~~";
Line();
TextBoxGroup("font-size:0.9em;margin:auto");
TextBox("title=Result Setting,style=width:250px,id=RstInfoID,required=true,logo=cogs,selected=-1",$rstsetarr);
Note("style=width:240px;font-size:1em");
echo "Note, Fixer will use selected Result Setting while updating Student result";
_Note();
_TextBoxGroup();
exit();
}

//function to convert an array to datastring without escaping the values
function DataString2($darr){
$rst = "";
    foreach($darr as $k=>$v){
$rst .= $k."=".$v."&";
    }
    return rtrim($rst,"&");
}
//function to update repeat courses field - From RstSave.php
function UpdateRepeat($Rept,$grds,$processNumFailed = true){
    // return "aaaa";
    // global $grds;
    //$processNumFailed => CourseNotExistInRst Insert
     global $courseID;
     global $courseDet;
     global $Lvl;
     global  $Sem;
     global  $studyID;
     $ReptArr = explode('+',$Rept);
    
     if((int)$grds['PASS'] > 0){ //if passed
              //remmove in new reapet if exist;
              $NewRepeat = "";
              if(isset($ReptArr[1])){
               $NewRepeat = str_replace(":$courseID:","",$ReptArr[1]);
              }
              $Rept = $ReptArr[0]."+".$NewRepeat;
              
              }else{ //if failed
                $allowfail = (int)$courseDet['AllowFail']; // number of times a student can fail the course
                if($allowfail != 0){ //if student not allow to resit atall i.e number of fail is 0 dont insert in repeat
                 //add to new repeat
                 if(isset($ReptArr[1])){
                   
                   // echo "@NewRept=".$ReptArr[1]."@";
                     if(strpos($ReptArr[1],":$courseID:") === false || ($allowfail < 0 && $processNumFailed)){ //if not exist in repeat or student can fail the course (allow to resit) at any number of times and the course result is just inputed the first time
                       $ReptArr[1] .= ":$courseID:";
                     }else{//if exist in repaet
                      if($processNumFailed){ //if insert operation i.e result inserted newly check allowable number of fail
   
                       //check the number of times it exixt 
                       $numocc = substr_count($ReptArr[0],":$courseID:");
   
                       if($numocc >= ($allowfail - 1)){ //if student has reach number of alowable fail, remove all occurence from repeat 
                        $ReptArr[1] = str_replace(":$courseID:","",$ReptArr[1]);
   
                       }else{ //if not ecceded number of fails add it
                        $ReptArr[1] .= ":$courseID:";
                       }
                      }
                       
                     }
                 }else{ //if not exist add it
                   $ReptArr[1] = ":$courseID:";
                 }
                }
                $Rept = $ReptArr[0]."+".$ReptArr[1];
              }
              //print_r($grds);
       return $Rept;
   }

   //form courses
   function FormCell($B4CO,$CourseCodeArr){
       //$CourseCodeArr => Holds student registered course Codes, will be use to check for duplicate course code
    global $SemCourses;
    global $RegNo;global $studrst;
    $newB4CO = [];
    $newB4COCourseCode = [];
//$originalCourses = []
   // global ;
    $carryOverHTML = "";
    $B4CO = trim($B4CO);
    if($B4CO == ""){return "";}
$coarr = explode("+",$B4CO);
$B4CO = count($coarr) > 1?$coarr[1]:$B4CO;

$B4COArr = explode("::",trim($B4CO,":"));
               if(count($B4COArr) > 0){
                   $B4COArr = array_unique($B4COArr);
                   foreach($B4COArr as $indB4CO){
                       if(trim($indB4CO) == "")continue;
                       $courseDet = isset($SemCourses[$indB4CO])?$SemCourses[$indB4CO]:CourseDetails($indB4CO);

                       //checking duplicate for registered course code that still comes out in outstanding, thou, deferent course ID
                       if(isset($CourseCodeArr) && in_array(trim(strtolower($courseDet['CourseCode'])),$CourseCodeArr)){
                        Push("$RegNo Result (".$studrst['ID'].") => Registered Course Code Found in Outstanding - ({$courseDet['CourseCode']})","err");
                        Push("$RegNo Result (".$studrst['ID'].") => Registered Course Code Removed in Outstanding - ({$courseDet['CourseCode']})","ok");

                        continue; //if the course code is duplicated just ignore and move to the next course
                       }

                       //checking duplicate - if course code exist more than one in $B4CO, thou deferent course ID
                       if(isset($CourseCodeArr) &&  in_array(trim(strtolower($courseDet['CourseCode'])),$newB4COCourseCode)){
                        Push("$RegNo Result (".$studrst['ID'].") => Duplicated Course Code Found - ({$courseDet['CourseCode']})","err");
                        Push("$RegNo Result (".$studrst['ID'].") => Duplicated Course Code Ignored - ({$courseDet['CourseCode']})","ok");
                        continue;
                       }
                       $newB4CO[] = $indB4CO; //add course id to array, (valid, uniques courses)
                       $newB4COCourseCode[] = trim(strtolower($courseDet['CourseCode']));
                      $carryOverHTML .= str_replace(" ","&nbsp;",$courseDet['CourseCode']).", ";
                   }
                  $carryOverHTML = rtrim($carryOverHTML,", ");
               }
            $newB4CO = ":".implode("::",$newB4CO).":";
            $newcoursesids = count($coarr) > 1?$coarr[0]."+".$newB4CO:$newB4CO;
              // $carryOverHTML .= "";
               return [$carryOverHTML,$newcoursesids]; //return the formated course code and the new formed ids, if the duplicate course code lookup is supplied
   }
$res = "";
//$_POST['RegNo'] ='AK16/NAS/MTH/019';
$dump = '';
$errs = 0; $fix =0; $note = 0;$rsthtml='';
//function to write response
function Push($txt,$err = ''){
    global $dump; global $errs; global $fix; global $note; global $fixnow;
    $cnt = "";
    $logo = "terminal";
    if($err == "err"){
        $errs++;
      $cnt = "<strong>(Issue ".$errs.")</strong>";
      $logo = "ban";
    }else if($err == "ok"){
        $fix++;
      $cnt = "<strong>(Fix ".$fix.")</strong>";
      $logo = $fixnow?"check":"exclamation-triangle";
    }else if($err == "note"){
        $note++;
        $cnt = "<strong>(Note ".$note.")</strong>";
        $logo = "list-alt";
    }
    $dump .= '<div class="'.$err.'"><i style="opacity:0.5" class="fa fa-'.$logo.'"></i>&nbsp;&nbsp;&nbsp;'.$txt.' '.$cnt.'</div>';
}
Push("STARTING...");
//Get the student regno
if(!isset($_POST['RegNo']) || trim($_POST['RegNo']) == "")exit ('<div class="err">Invalid RegNo</div>');
$RegNo = $_POST['RegNo'];
$num = $_POST['Num'];//regno counter
$fixnow = (int)$_POST['Type'] == 1?true:false; //indicate if fix is to be done
$query = ""; //the fix query
//get the student details
$studDet = $dbo->SelectFirstRow("studentinfo_tb","","RegNo='".$RegNo."' OR JambNo='".$RegNo."'");
$studName = "Unknown";
if(!is_array($studDet)){
    Push('<div class="err">Invalid Student - Could not read Student Data</div>','note');
    //exit();
}else{
    $studName = $studDet['SurName']. " ".$studDet['FirstName']. " ".$studDet['OtherNames'];
    if(!isset($_POST['RstInfoID']) || (int)$_POST['RstInfoID'] < 1)exit ('<div class="err">Invalid Result Settings</div>');
    $RstInfoID = (int)$_POST['RstInfoID'];
//get grading structure
$grdstr = $dbo -> SelectFirstRow("resultinfo_tb","","ID = ".$RstInfoID);
if(!is_array($grdstr))exit ('<div class="err">Invalid Result Settings</div>');
$classPassStr = $grdstr['ClassOfPass'];
$grdstr = is_array($grdstr)?$grdstr[1]:"";
$schgrdstr = GetGradeDetAll($RstInfoID);
$classPassDetAll = GetClassPassDetAll($RstInfoID);
Push("Getting $RegNo Results ..");
$CCH =0; $CGP =0; $NumRst=0;
//get all results
$allrst = $dbo->Select("result_tb r, session_tb s, semester_tb sem","r.*,s.SesName,sem.Sem as SemName","r.RegNo='".$RegNo."' AND r.SesID = s.SesID AND ((sem.Num > 0 && r.Sem = sem.Num) || r.Sem = sem.ID) ORDER BY r.Lvl, r.Sem, r.GroupID");
if(is_array($allrst) && $allrst[1] > 0){
    $NumRst = $allrst[1];
 Push($allrst[1]." ".$RegNo." Result(s) Found","note");
 //proccess each result
 Push("Proccessing $RegNo Results ..");
 $cnt = 1;
 $CurCCH = 0; $CurCGP = 0; $curRepr = '';$Rept = ''; $curunregcourses = '';$unregcourses = '';
 while($studrst = $allrst[0]->fetch_assoc()){
    
     $LvlName = LevelName($studrst['Lvl'], $studDet['StudyID']);
     $CurCCH = $studrst['CCH'];
     $CurCGP = $studrst['CGP'];
     $CurBCH = $studrst['BCH'];
     $CurBGP = $studrst['BGP'];
     if((int)$studrst['GroupID'] < 2){ //if first group
        $newBCH = $CCH;
        $newBGP = $CGP;
     }else{
        $CCH = $newBCH;
        $CGP = $newBGP;
     }
     
     $curRepr = $studrst['Rept'];
     $curunregcourses = $studrst['Outst'];
     $copy = (int)$studrst['GroupID'] < 2?"":"(UPDATED ".((int)$studrst['GroupID'] - 1).")";
     //covert all repeat courses string to array format
     $curReprArr = explode("+",$curRepr);
     foreach($curReprArr as $ind => $rp){
if(trim($rp) == ""){
    $curReprArr[$ind] = [];
}else{
    $curReprArr[$ind] = explode("::",trim($rp,":"));
}

     }
     //proccessing repeat
if(trim($Rept) != ""){
    $ReptArr = explode("+",$Rept);
    $Rept = $ReptArr[1]."+".$ReptArr[1];
}

//proccess outstanding
if(trim($unregcourses) != ""){
    $unregcoursesArr = explode("+",$unregcourses);
    $unregcourses = $unregcoursesArr[1]."+".$unregcoursesArr[1];
}else{
    $unregcourses = "+";
}
    Push("$RegNo Result (".$studrst['ID'].") => LevelID: {$studrst['Lvl']}, SemID: {$studrst['Sem']}, GroupID: {$studrst['GroupID']}");
    //get student registered courses
    Push("$RegNo Result (".$studrst['ID'].") => Reading Student Registered Courses (Strict Mode) ...");
    $dtudregCourses = $dbo->SelectFirstRow("coursereg_tb","","RegNo='$RegNo' AND Lvl = {$studrst['Lvl']} AND Sem = {$studrst['Sem']} AND SesID = {$studrst['SesID']}");

    //Get all Semester Courses 
 $SemCourses = GetCourses($studDet['ProgID'],$studrst['Lvl'],$studrst['Sem']);
 $CoursesNow = $SemCourses['Current'];
 $OldCourses = $SemCourses['Old'];
    

//variable to hold registered courses
$regcourses = [];
    if(!is_array($dtudregCourses)){ //if course reg not found
        Push("$RegNo Result (".$studrst['ID'].") => Coures Registration Not Found in Strict Mode");
        Push("$RegNo Result (".$studrst['ID'].") => Reading Student Registered Courses (Relax Mode) ...");
        $dtudregCourses = $dbo->SelectFirstRow("coursereg_tb","","RegNo='$RegNo' AND Lvl = {$studrst['Lvl']} AND Sem = {$studrst['Sem']}");
        if(!is_array($dtudregCourses)){
            Push("$RegNo Result (".$studrst['ID'].") => Coures Registration Not Found in Relax Mode");
            Push("$RegNo Result (".$studrst['ID'].") => Result Courses will be asummed as Registered Courses","note");
            //$dtudregCourses = [];
        }else{
            Push("$RegNo Result (".$studrst['ID'].") => Coures Registration Found in Relax Mode");
            $regcourses = explode("~",$dtudregCourses['CoursesID']);
        }
    }else{
        Push("$RegNo Result (".$studrst['ID'].") => Coures Registration Found in Strict Mode");
        $regcourses = explode("~",$dtudregCourses['CoursesID']);
    }
    sort($regcourses);
//course registration session
//if(!is_array($dtudregCourses)) {
    $CSesID = !is_array($dtudregCourses)?$studrst['SesID']:$dtudregCourses['SesID'];
//}
//get expected registered courses
$expcourses = $dbo->RunQuery("SELECT GROUP_CONCAT(CourseID SEPARATOR '~') as ExpCourses FROM course_tb WHERE DeptID = {$studDet['ProgID']} AND Lvl = {$studrst['Lvl']} AND Sem={$studrst['Sem']} AND StudyID = {$studDet['StudyID']} AND StartSesID <= $CSesID AND (EndSesID >= $CSesID OR EndSesID = 0) AND CourseStatus = 0");

/* ######## ISSUE ######### */
//The expected Courses is not considering elective course (will park all as expected course)
/* ######## ISSUE ######### */

if(is_array($expcourses) && $expcourses[1] > 0){
    $expcourses = $expcourses[0]->fetch_assoc();
//Push("ExpCourses => ".$expcourses ['ExpCourses']);
    $expcourses = explode("~",$expcourses ['ExpCourses']);
}else{
   // Push("ExpCourses => "."SELECT GROUP_CONCAT(CourseID SEPARATOR '~') as ExpCourses FROM course_tb WHERE DeptID = {$studDet['ProgID']} AND Lvl = {$studrst['Lvl']} AND Sem={$studrst['Sem']} AND StudyID = {$studDet['StudyID']} AND StartSesID <= $CSesID");
   Push("$RegNo Result (".$studrst['ID'].") => Expected Registered Courses Not Found","note");
    $expcourses = [];
}

//sort the expcourse
sort($expcourses);

//get the course settings
//$csetting = COURSE();

//get unregistered courses
//$unregcourses = '';
$ElectiveGropArr = []; //hold the courses registered for a particular group
$ElectiveGropArrUnReg = []; //hold the courses not registered for a particular group
$unregcoseok = true;
if(count($expcourses) > 0 ){
   foreach($expcourses as $expCID){
       //get the course details
       $cdetElect = $dbo->SelectFirstRow("course_tb c, coursegroup_tb cg","c.*,cg.AllowFail","c.CourseID=$expCID AND c.GroupID = cg.ID LIMIT 1");
       $ElectGrp = 0;
       if(is_array($cdetElect)){ //if course details found
          //get the elective group
          $ElectGrp = (int)$cdetElect['Elective'];
          
       }
       if(!in_array($expCID,$regcourses)){
        if(strpos($curunregcourses,":$expCID:") === false){
            $unregcoseok = false;
        }
        //
        if($ElectGrp == 0){//if course is compulsary
            $unregcourses .= ":$expCID:";
        }else{ //if elective
           if($ElectGrp > 1){ //if course is not in none-or-above group, because none or above group will never be considered as outstanding if not registered
              //add to un reg elective group array
              $ElectiveGropArrUnReg[$ElectGrp][] = $expCID;
           }
        }
        
       }else{// if student register for the course
        //add to the elective group array
        if($ElectGrp > 1){ //if course is not in none-or-above group, because none or above group will never be considered as outstanding if not registered 
        $ElectiveGropArr[$ElectGrp][] = $expCID;
        }
       }
   }
   //process the elective group un reg
   //$maxElectGrp = $csetting['MaxElectiveGrp'];
    foreach($ElectiveGropArrUnReg as $GrpID=>$courses){
      //get the total registered courses in the group
      $totreg = isset($ElectiveGropArr[$GrpID])?count($ElectiveGropArr[$GrpID]):0;
      //get the total number of courses remaining to be registered in the group
      //1. Get the total expected in the group
      $GrpExp = $GrpID - 1;
      //2. subtract the tot reg from expect
      $Rem = $GrpExp - $totreg;
       if($Rem > 0){ // there are elective remaining
        if(count($courses) <= $Rem){ //if the unreg elective group courses are less than or equal to the total remaining, just use all unregistered elective courses
            $unregcourses .= ":".implode("::",$courses).":";
          }else{ // if the unreg elective courses is greater than the remaining, then pick the first number of remaining of the unregelective group array
            for($dd=0;$dd<$Rem;$dd++){
                $unregcourses .= ":".$courses[$dd].":";
            }

          }
        //loop through a
       }
    }
}

//remove registered courses from new outstanding
if(count($regcourses) > 0){
    $unregcoursesarr = explode("+",$unregcourses);
$newunregcourses = $unregcoursesarr[1];
    foreach($regcourses as $rgCID){
        $newunregcourses = str_replace(":$rgCID:","",$newunregcourses);
    }
    $unregcourses = $unregcoursesarr[0] ."+".$newunregcourses;
}
$coursesrst = "";
$coursesrstn = ""; //new
$NewRstDB = array(); //new
$CourseCodeArr = [];//hold the individual course code of the student result - for handling duplicate course code
$TCH =0; $TGP=0;$CurTCH =0; $CurTGP=0;$TCR = 0;
    //get all individual score in array
    $crstArr = $dbo->DataArray($studrst['Rst']);
    if(trim($studrst['Rst']) == "" || count($crstArr) < 1){ //if no result found 
        Push("$RegNo Result (".$studrst['ID'].") => No Result Found","err");
        $coursesrst = "No Result";
    }//else{//if result individual score
      //break down the individual result
      Push(" ******************* $RegNo Result (".$studrst['ID'].") => Recalculation *******************");
      $CIDArr = [];
//get all course student registered but not in result
       $rstkeys = array_keys($crstArr);
       $allkeys = array_unique(array_merge($regcourses,$rstkeys));
       $RstInfo = [];
       
       //foreach($crstArr as $CID => $Score){
        foreach($allkeys as $CID){
            $Score = isset($crstArr[$CID])?$crstArr[$CID]:null;
       //Push("$RegNo Result (".$studrst['ID'].") => Operation Aborted","err");
           //get the course details
            //$cdet = $dbo->SelectFirstRow("course_tb","","CourseID=".$CID);
            $cdet = $dbo->SelectFirstRow("course_tb c, coursegroup_tb cg","c.*,cg.AllowFail","c.CourseID=$CID AND c.GroupID = cg.ID LIMIT 1");
            if(!is_array($cdet)){
                Push("$RegNo Result (".$studrst['ID'].") => Reading Course Details ($CID) Failed","err");
                //Push("$RegNo Result (".$studrst['ID'].") => Operation Aborted","err");
                continue;
            }
            $CH = $cdet['CH'];
            $RstInfo[$CID] = ["CourseCode"=>$cdet['CourseCode'],"CourseStatus"=>$cdet['CourseStatus'],"Title"=>$cdet['Title'],"Lvl"=>$cdet['Lvl'],"DeptID"=>$cdet['DeptID'],"Sem"=>$cdet['Sem'],"CH"=>$cdet['CH'],"Elective"=>$cdet['Elective'],"StudyID"=>$cdet['StudyID'],"GroupID"=>$cdet['GroupID'],"StartSesID"=>$cdet['StartSesID'],"EndSesID"=>$cdet['EndSesID'],"AllowFail"=>$cdet['AllowFail']];

            //get Result approval det
            $apprst = $dbo->SelectFirstRow("resultapprove_tb","","ProgID = {$cdet['DeptID']} AND Ses = {$studrst['SesID']} AND Lvl = {$studrst['Lvl']} AND Sem = {$studrst['Sem']} AND CourseID = $CID LIMIT 1");
            $apprstatus = 'FALSE';
            if(!is_array($apprst)){
                Push("$RegNo Result (".$studrst['ID'].") => Course ($CID:{$cdet['CourseCode']}) Result Approval Details Not Found (Result not Uploaded)","note");
               //Add Approval details query
                //**************????*************** */
            }else{
                $apprstatus = $apprst['Status'];
            }
            $courseID = $CID;
            $courseDet = $cdet;
            $Lvl = $studrst['Lvl'];
            $Sem = $studrst['Sem'];
            $studyID = $cdet['StudyID']; //get the study ID from course details
            
            //check if student registered for the course
            if(!in_array("".$CID,$regcourses) && in_array("".$CID,$rstkeys)){
                Push("$RegNo Result (".$studrst['ID'].") => Course ($CID:{$cdet['CourseCode']}) Not Registered, but has Result","note");
            }

            

           //add to cidarray which will be used later to get unreg courses
           $CIDArr[] = $CID;
           if(!is_null($Score)){ //if result exist
             //calcuate total score
           $ScoreArr = explode("|",$Score);
           if(count($ScoreArr) < 1){ //if no score found reset to zero
            Push("$RegNo Result (".$studrst['ID'].") => Invalid Score For $CID:{$cdet['CourseCode']}","err");
            Push("$RegNo Result (".$studrst['ID'].") => $CID:{$cdet['CourseCode']} - Score Reset to CA:0, Exam:0, Total:0","ok");

            $ScoreArr[0] =0;
            $ScoreArr[1] =0;
           }else if(count($ScoreArr) == 1){ //if ca found but exam not found reset exam to zero
            Push("$RegNo Result (".$studrst['ID'].") => Invalid Exam Score For $CID:{$cdet['CourseCode']}","err");
            $ScoreArr[0] = (float)$ScoreArr[0];
            $ScoreArr[1] = 0;
            Push("$RegNo Result (".$studrst['ID'].") => $CID:{$cdet['CourseCode']} Exam Score Reset to CA:{$ScoreArr[0]}, Exam:0, Total:{$ScoreArr[0]}","ok");
           }else{
            $ScoreArr[0] = (float)$ScoreArr[0];
            $ScoreArr[1] = (float)$ScoreArr[1];
           }
            $tot = $ScoreArr[0] + $ScoreArr[1];
            //$RstInfo[$CID]["CA"] = $ScoreArr[0];
            //$RstInfo[$CID]["Exam"] = $ScoreArr[1];
           }else{
             $tot = -1;
             Push("$RegNo Result (".$studrst['ID'].") => Registered for $CID:{$cdet['CourseCode']} But No Result Found","err");
             //$RstInfo[$CID]["CA"] = "";
            //$RstInfo[$CID]["Exam"] = "";
           }
           
   
          //get grade point
          $grds = GetGrade($tot < 0?0:$tot,$grdstr,$schgrdstr);
          $CourseCodeArr[] = trim(strtolower($courseDet['CourseCode'])); // add the course code to the array, in order to check for duplicate in outstanding
          if($tot < 0){ //student register for course but no result
                $coursesrstn .= $courseDet['CourseCode']."(*0".$grds['Grade']."), ";

               /*  $NewRstDB[$CID] = "|";
                $grdPoint = (int)$grds['Level']; //get the grade point
          $newGP = $CH * $grdPoint;
          $TCH += $CH;
          $TGP += $newGP;
          $CCH += $CH;
            $CGP += $newGP;
            Push("$RegNo Result (".$studrst['ID'].") => Result $CID:{$cdet['CourseCode']} Is Now put into consideration while calculating CGP, and added to student Result as Empty Result","ok"); */
          }else{ //if result exist
            $coursesrst .= $courseDet['CourseCode']."(".$tot.$grds['Grade']."), ";
                $coursesrstn .= $courseDet['CourseCode']."(".$tot.$grds['Grade']."), ";
                
                /* ."|".$grds['Level']."|".rawurlencode($grds['Grade'])."|".rawurlencode($grds['Desc'])."|".$grds['PASS']."|".$CH."|".$GP; */
                $grdPoint = (int)$grds['Level']; //get the grade point
            $newGP = $CH * $grdPoint;
            //Form the new rst structure
            $NewRstDB[$CID] = $ScoreArr[0]."|".$ScoreArr[1]."|".$grds['Level']."|".rawurlencode($grds['Grade'])."|".rawurlencode($grds['Desc'])."|".$grds['PASS']."|".$CH."|".$newGP;
            $RstInfo[$CID]['CA'] = $ScoreArr[0];
            $RstInfo[$CID]['Exam'] = $ScoreArr[1];
            $RstInfo[$CID]['Total'] =(float)$ScoreArr[0] + (float)$ScoreArr[1];
            $RstInfo[$CID]['Point'] = $grds['Level'];
            $RstInfo[$CID]['Grade'] = $grds['Grade'];
            $RstInfo[$CID]['GradeName'] = $grds['Desc'];
            $RstInfo[$CID]['Pass'] = $grds['PASS'];
            $RstInfo[$CID]['GradePoint'] = $newGP;

            $ngrdstruc = GetGrade(-1,$grdstr,$schgrdstr);
            $RstInfo[$CID]["GradeStruc"] = $ngrdstruc;

            $TCH += $CH;
            $CurTCH += $CH;
            $TGP += $newGP;
            $CurTGP += $newGP;
            $CCH += $CH;
            $CGP += $newGP;
            $TCR++;
            //proccess repeat
$Rept = UpdateRepeat($Rept,$grds);
          }
          
          


//check if repeat and not exist in current repeat
if((int)$grds['PASS'] == 0 && !in_array($CID,$curReprArr[1])){
    Push("$RegNo Result (".$studrst['ID'].") => Failed $CID:{$cdet['CourseCode']} but not found in Repeat","err");
    Push("$RegNo Result (".$studrst['ID'].") => Failed $CID:{$cdet['CourseCode']} and Transfered to Repeat","ok");
}




      }
//$NewRstDB
Push(" ******************* $RegNo Result (".$studrst['ID'].") => Result Details *******************");
if(trim($studrst['RstInfo']) == "" && count($NewRstDB) > 0){
    Push("$RegNo Result (".$studrst['ID'].") => Empty Result Info","err");
    Push("$RegNo Result (".$studrst['ID'].") => Result Info Formed and Added","ok");
    //Push("$RegNo Result (".$studrst['ID'].") => Formed Result Info (Score) - ".json_encode($NewRstDB));
   // Push("$RegNo Result (".$studrst['ID'].") => Formed Result Info (Course) - ".json_encode($RstInfo));

//$RstInfo
}



//add No result String
if(count($NewRstDB) < 1){
    $coursesrstn = "No Result - ".$coursesrstn;
}

Push(" ******************* $RegNo Result (".$studrst['ID'].") => Result Details *******************");


      Push(" ******************* $RegNo Result (".$studrst['ID'].") => Recalculation *******************");
      Push("************ BCH and BGP ***********");
      if($curBCH != $newBCH){
        Push("$RegNo Result (".$studrst['ID'].") => Wrong CH Brought Forward (".$curBCH.")","err");
        Push("$RegNo Result (".$studrst['ID'].") => CH Brought Forward Updated (".$newBCH.")","ok");
    }
    
    if($curBGP != $newBGP){
        Push("$RegNo Result (".$studrst['ID'].") => Wrong GP Brought Forward (".$curBGP.")","err");
        Push("$RegNo Result (".$studrst['ID'].") => GP Brought Forward Updated (".$newBGP.")","ok");
    }
    Push("************ BCH and BGP ***********");
      //report CCH and CGP
      Push("************ GPA and CGPA ***********");

     

if($TCH != $studrst['TCH'] || $TGP != $studrst['TGP']){ //wrong database TCH or TGP
    Push("$RegNo Result (".$studrst['ID'].") => Wrong Database TCH or TGP","err");
    Push("$RegNo Result (".$studrst['ID'].") => Database TCH and TGP Updated","ok");
}

      $stcgpa = ($CurCCH == $CCH && $CurCGP == $CGP)?'ok':'err';
      $GPA = $TCH>0?number_format(($TGP/$TCH),2):'0.00';
      $CurGPA = $CurTCH>0?number_format(($CurTGP/$CurTCH),2):'0.00';
      $stgpa = "ok";
if($CurGPA != $GPA){
    Push("$RegNo Result (".$studrst['ID'].") => Wrong GPA, mainly due to wrong result entering flow, change of CH or Grade Point","err");
    Push("$RegNo Result (".$studrst['ID'].") => GPA Recalculated Currectly","ok");
    $stgpa = "err";
}

$CurCGPA = $CurCCH>0?($CurCGP/$CurCCH):0;
      $CGPA = $CCH>0?($CGP/$CCH):0;

      $CurclassPassdet = GetClassPass($CurCGPA,$classPassStr,$classPassDetAll);
      $CurclassOfPass = is_array($CurclassPassdet)?$CurclassPassdet['ClassName']:"";

      $classPassdet = GetClassPass($CGPA,$classPassStr,$classPassDetAll);
      $classOfPass = is_array($classPassdet)?$classPassdet['ClassName']:"";

      $CurCGPA = number_format($CurCGPA,2);
      $CGPA = number_format($CGPA,2);

      
      
      
      Push("$RegNo Result (".$studrst['ID'].") => Current CCH:$CurCCH , CGP:$CurCGP");
      Push("$RegNo Result (".$studrst['ID'].") => Recalculated CCH:$CCH , CGP:$CGP");

      Push("$RegNo Result (".$studrst['ID'].") => Current Class Of Pass:$CurclassOfPass");
      Push("$RegNo Result (".$studrst['ID'].") => New Class Of Pass:$classOfPass");
      if($stcgpa == "err"){
        Push("$RegNo Result (".$studrst['ID'].") => CGPA wrongly calculated mainly due to wrong result entering flow, change of CH or Grade Point","err"); 
        Push("$RegNo Result (".$studrst['ID'].") => CGPA Recalculated Correctly","ok");  
      }else{
         
      }
      Push("************ GPA and CGPA ***********");

      //report Repeat
      Push("************ Repeat ***********");
      //form cur repeat in order
sort($curReprArr[1]);
sort($curReprArr[0]);
$curRepr = (count($curReprArr[0]) > 0?":".implode("::",$curReprArr[0]).":":"")."+".(count($curReprArr[1]) > 0?":".implode("::",$curReprArr[1]).":":"");
      Push("$RegNo Result (".$studrst['ID'].") => Current Repeat - ".$curRepr);
$Rpearr = explode("+",$Rept);
foreach($Rpearr as $iin => $RRR){
    $Rpearr[$iin]  = explode("::",trim($RRR,":"));
    sort($Rpearr[$iin]);
    $Rept .= ":".implode("::",$curReprArr[0]).":"."+";
}
$Rept = rtrim($Rept,"+");

      Push("$RegNo Result (".$studrst['ID'].") => Reformed Repeat - ".$Rept);
      $strept = "";
      if(trim($Rept," +") != trim($curRepr," +")){
        $strept = "err";
        Push("$RegNo Result (".$studrst['ID'].") => Wrong Repeat - $curRepr","err");
        Push("$RegNo Result (".$studrst['ID'].") => Repeat Fixed -$Rept","ok");
      }
      Push("************ Repeat ***********");

      //report unreg courses
      //$unregcourses
      Push("************ Outstanding ***********");
      Push("$RegNo Result (".$studrst['ID'].") => Current Outsatanding - ".$curunregcourses);
      Push("$RegNo Result (".$studrst['ID'].") => Reformed Outstanding - ".$unregcourses);
      $stout = "";
      if(trim($curunregcourses," +") != trim($unregcourses," +")){
        $stout = "err";
        Push("$RegNo Result (".$studrst['ID'].") => Wrong Unregistered Course - $curunregcourses","err");
        Push("$RegNo Result (".$studrst['ID'].") => Unregistered Course Fixed -$unregcourses","ok");
      }
      Push("************ Outstanding ***********");

      Push("<br />");
    //}
     //form the result subs
     //$SemName = (int)$studrst['SemName'] > 1?"Second":"First";
     $rsthtml .= '
            <div>
            <div><strong>'.$RegNo.' - '.$studrst['SesName'].' | '.$LvlName.' '.$studrst['SemName'] .' Semester</strong> <strong>'.$copy.'</strong></div>';
            $rsthtml .= __Table("rowselect=true,style=width:100%;font-size:0.8em;margin:auto;text-align:left;margin-top:10px,id={$RegNo}_".$studrst['ID'].",multiselect=false,data-type=table");
            $rsthtml .= __THeader(array("Troubleshoot","Result","TCH","TGP","GPA","BCH","BGP","CCH","CGP","CGPA","Repeat","OutStanding"),"style=text-align:left");
//Forming current repeat 
            $curReprArr = FormCell($curRepr);
            //$curRepr = $curReprArr[1];
            $curunregcoursesArr = FormCell($curunregcourses);
            //5$curunregcourses = $curunregcoursesArr[1];
            $rsthtml .= __TRecord(array("Before",rtrim($coursesrst,", "),$CurTCH,$CurTGP,$CurGPA,$CurBCH,$CurBGP,$CurCCH,$CurCGP,$CurCGPA,$curReprArr[0],$curunregcoursesArr[0]),"data-id={$RegNo}_".$studrst['ID']."_before");
            $Reptarr = FormCell($Rept,[]);
            $Rept = $Reptarr[1];
//remove duplicate registered course code from outstanding
$outsarr = FormCell($unregcourses,$CourseCodeArr);
$unregcourses = $outsarr[1];
            $rsthtml .= __TRecord(array("After",rtrim($coursesrstn,", "),$TCH,$TGP,$GPA,$newBCH,$newBGP,$CCH,$CGP,$CGPA,$Reptarr[0],$outsarr[0]),"data-id={$RegNo}_".$studrst['ID']."_after,class=ok");
            //DatePicker" data-style="margin-top:-300px;margin-left:-40px" data-input="dndndn"
            $rsthtml .=___Table();
$rsthtml .= '</div>';
Push(DataString2($NewRstDB));
$RGPA = (float)str_replace(",","",$GPA);
$RCGPA = (float)str_replace(",","",$CGPA);
$query .= "UPDATE result_tb SET Rst='".$dbo->SqlSafe(DataString2($NewRstDB))."',Rept='".$Rept."',RstInfo='".$dbo->SqlSafe(json_encode($RstInfo))."',Outst='".$unregcourses."',TCH=$TCH,TGP=$TGP,BCH=$newBCH,BGP=$newBGP,CCH=$CCH,CGP=$CGP, GPA=$RGPA, CGPA=$RCGPA, TRC=$TCR , COP='".$dbo->SqlSafe($classOfPass)."', COPRule='".$dbo->SqlSafe($classPassStr)."', COPDetails='".$dbo->SqlSafe(json_encode($classPassDetAll))."' WHERE ID = {$studrst['ID']};";

/*  $query .= "UPDATE result_tb SET Rst = '".$dbo->SqlSafe($RstDet['Rst'])."', Rept='{$RstDet['Rept']}', RstInfo='".$dbo->SqlSafe(json_encode($newRstInfo))."', TCH={$rtn['TCH']} , TGP={$rtn['TGP']}, BCH={$rtn['BCH']} , BGP={$rtn['BGP']} , CGP={$rtn['CGP']} , CCH={$rtn['CCH']}, GPA={$rtn['GPA']}, CGPA={$rtn['CGPA']},TRC=$TRC , COP='".$dbo->SqlSafe($classOfPass)."', COPRule='".$dbo->SqlSafe($classPassStr)."', COPDetails='".$dbo->SqlSafe(json_encode($classPassDetAll))."' WHERE ID = ".$RstDet["ID"].";"; */
   

            
 }

}else{

    Push($allrst[1]." ".$RegNo." Result(s) Not Found","err");
}

//fix if fixing is enabled
if($fixnow){
    Push("Fixing ($fix) issues ....");
   $q = $dbo->Connection->multi_query($query);
   if(!$q){
       Push("Fixing Error => ".$dbo->Connection->error,"err");
   }else{
    Push("All Issues Fixed","ok");
   }
}

//echo '<div id="'.$RegNo.'">&nbsp;</div>';
if((int)$num < 1){
    Box("class=ep-animate-opacity");
    echo $rsthtml;
    echo '
        <div style="padding:6px">
    <div style="float:left;width:70%"><strong class="err">'.$errs.' Issues</strong> | <strong class="ok">'.$fix.' Fixes</strong>  | <strong class="">'.$note.' Notes</strong></div>
    <div style="float:right;width:30%">';
    LogoButton('onclick=_(\''.$RegNo.'_tray\').ToggleShowHide();return false;,style=display:block;float:right;color:#fff,class=altBgColor2,logo=list-alt,text=Process Tray');
    echo '<div style="clear:both"></div></div><div style="clear:both"></div>
    <div style="margin:auto;padding:6px;margin-top:5px;background-color:#fff;border:#ccc 1px solid;min-height:100px;max-height:200px;display:none;overflow:auto" id="'.$RegNo.'_tray">
    '.$dump.'
    </div>
    </div>
    
    ';
    _Box();
}else{
    FlatTRecord("class=ep-animate-opacity");
    FlatTData($num,"size=5");
    FlatTData($RegNo.' - '.$studName,"size=40");
    FlatTData($NumRst,"size=10");
    FlatTData($errs,"size=10,style=font-weight:bold,class=altColor");
    FlatTData($fix._LogoButton('style=margin-left:10px;color:#fff,class=success indfixbtn,id='.$RegNo.'_fixbtn,onclick=Exams.ResultFixer.IndFixer(this),logo=wrench'),"size=20,style=font-weight:bold,class=ok");
    FlatTData($note,"size=10");
    FlatTData('<i class="fa fa-ellipsis-h"></i>',"size=5,style=text-align:left;cursor:pointer,onclick=_('".$RegNo."_det').ToggleShowHide(),class=altColor2Hover,title=View Details");
   /* echo '
          <div style="clear:both"></div>

          <div class="subbx" style="display:none" id="'.$RegNo.'_det">'; */
FlatTDataSub("id={$RegNo}_det,style=display:none");
            echo $rsthtml;
         echo '
        <div style="padding:6px">
    <div style="float:left;width:70%"><strong class="err">'.$errs.' Issues</strong> | <strong class="ok">'.$fix.' Fixes</strong>  | <strong class="">'.$note.' Notes</strong></div>
    <div style="float:right;width:30%">';
    LogoButton('onclick=_(\''.$RegNo.'_tray\').ToggleShowHide();return false;,style=display:block;float:right;color:#fff,class=altBgColor2,logo=list-alt,text=Process Tray');
    /* echo '<button onclick="_(\''.$RegNo.'_tray\').ToggleShowHide()" style="display:block;float:right"  class="altBgColor2 bbtn"><i class="fa fa-list-alt"></i> Process Tray</botton>'; */
    echo'<div style="clear:both"></div></div><div style="clear:both"></div>
    <div style="margin:auto;padding:6px;margin-top:5px;background-color:#fff;border:#ccc 1px solid;min-height:100px;max-height:200px;display:none;overflow:auto" id="'.$RegNo.'_tray">
    '.$dump.'
    </div>
    </div>';
        //echo '</div>';
        _FlatTDataSub();
          _FlatTRecord();
}

}
         // echo '<div id="'.$RegNo.'_scroll" style=""></div>';
?>