<?php
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
require("../../../../general/getinfo.php");
AllowUser("rstfix");
include "utility.php";
//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 if no Setting assigned to the 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';


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 ASC,r.Sem ASC,r.GroupID DESC");
if(is_array($allrst) && $allrst[1] > 0){
    $GroupManage = [];
    $CarryBCH = 0;$CarryBGP = 0;$PreRepeat = '';$PreOuts = '';
    $cnt = 1;
    //return ["SubQuery"=>$RstDet['RegNo'] . " ; ".$upwardRst[1]];
     while($upwrst = $allrst[0]->fetch_assoc()){ //loop trough all the upward results
        $rstsign = $upwrst['Lvl']."_".$upwrst['Sem']."_".$upwrst['SesID'];
        if(in_array($rstsign,$GroupManage))continue; //if a copy of the result already seen means this one is outdatated copy, skip it;
        $GroupManage[] = $rstsign;
      if($cnt > 1){
         $upwrst['BCH'] = $CarryBCH; $upwrst['BGP'] = $CarryBGP; //update the Brought forwards 
      }
      
      $cnt++;
      $NumRst++;
  //recalculate the result
  //use the result RstInfoID if exist, else use the Main RstInfoID;
  $WRstInfoID = (int)$upwrst['RstInfoID'] == 0?$RstInfoID:(int)$upwrst['RstInfoID'];
  
        $newrst =  Recalculate($upwrst,true,false,$PreRepeat,$WRstInfoID,$PreOuts); //recalculate the result only
        
        //exit(json_encode($newrst));
        $query .= $newrst["SubQuery"]; //get the update query
        //return ["SubQuery"=>json_encode($upwrst)];
        $CarryBCH = $newrst['CCH'];$CarryBGP = $newrst['CGP']; //set the next Brought forward to the current cummulatives
        $PreRepeat = $newrst['Rept'];
        $PreOuts = $newrst['Outst'];
     }
}else{
    Push($allrst[1]." ".$RegNo." Result(s) Not Found","err");
}

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

//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>';
?>