<?php
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
require("../../../../general/getinfo.php");
AllowUser("RUpload");
//require("../../../../epconfig/GenScript/PHP/getinfo.php");

//add result utilities
require_once("utility.php");





//function to get grades based on updatetype **NO MORE IN USE**
function GetGradeLocal($scorestr = "",$CA,$EX,$grdstr,$schgrdstr){
global $updatetype;
global $RstInfoID;
$tot = (int)$CA + (int)$EX;
/* $brdw = explode("|",$scorestr);
if($updatetype == 0 && count($brdw) > 2){ //if to use result existing settings and if it exist
   $grds = ["Level"=>$brdw[2],"Grade"=>$brdw[3],"Desc"=>$brdw[4],"PASS"=>$brdw[5]];
  // $grds["ScoreStr"] = $brdw[0]."|".$brdw[1]."|".$grds['Level']."|".$grds['Grade']."|".$grds['Desc']."|".$grds['PASS'];
}else{ */
  $grds = GetGrade($tot,$grdstr,$schgrdstr,$RstInfoID);
  
//}
$grds["ScoreStr"] = $CA."|".$EX."|".$grds['Level']."|".$grds['Grade']."|".$grds['Desc']."|".$grds['PASS'];
return $grds;
}

//function to form result update/insert query string
function FormResultQuery($GroupID = 1,$insert = true){
  //import globals into functions
 global  $discolDS;
 global $sdatastrDS;
 global $rstparamDS;
 global $dbo;
  //var fields = ["sestb","rstudstudy","rstudfac","rstuddept","rstudprog","rstudlvl","semest"];
 global $Lvl;
  global  $Sem;
  global  $Ses;
  global  $progid;
  global  $courseID;
  global  $studyID;
  global $courseDet;
  global $schgrdstr;
  global $grdstr;
  global $updatetype;
  global $strictlvlmode;
  global $rstScoreStrucObj;
  global $rstScoreStrucIDObj;
  global $rstScoreStrucMaxObj;
  global $RstInfoID;
   $totrw = (int)$sdatastrDS["MaxDataRow"]; //total datarow sent
  //$update string;
  $query = "";
  $fcoursID = $courseID;
  
          $CH = (int)$courseDet['CH'];
  //loop through each row
  for($rw=1; $rw <= $totrw; $rw++){
      $RegNo = rawurldecode($sdatastrDS[$rw."_".$discolDS['RegNo']]);
      $Readonly = rawurldecode($sdatastrDS[$rw."_readonly"]);
      $Disable = rawurldecode($sdatastrDS[$rw."_disable"]);

      $ScoreArr = [];
      $tot = 0;
      foreach($rstScoreStrucIDObj as $FID){
        $ScoreInd = (float)rawurldecode($sdatastrDS[$rw."_".$discolDS[$FID]]);
        $tot += $ScoreInd;
        $ScoreArr[] = $ScoreInd;
      }

      //Get the student Current CA and Exam
     /* $CA = rawurldecode($sdatastrDS[$rw."_".$discolDS['CA']]);
     $Exm = rawurldecode($sdatastrDS[$rw."_".$discolDS['Exm']]); */

     $RstCourseID = (int)rawurldecode($sdatastrDS[$rw."_".$discolDS['RstRegCID']]);
     $courseID = $RstCourseID > 0?$RstCourseID:$fcoursID;
     //exit($RstCourseID);
     //if(trim($RegNo) == "" || $Readonly == "true" || $Disable == "true" || (trim($CA) == "" && trim($Exm) == "") ){ //if no regno proceed to next row or result is outdated
      if(trim($RegNo) == "" || $Readonly == "true" || $Disable == "true" ){ //if no regno proceed to next row or result is outdated
        continue;
      }
      $proccnumfailed = true; //proccess result based on allowable number of failed
      $couseExistInRept = false;
//AK17/NAS/BIO/032
      


//$CA = (float)$CA; $Exm = (float)$Exm;
      
    
     
     //

     //Form The result string
     
    //$tot = (float)$CA + (float)$Exm;

   //$grds = GetGrade($tot,$grdstr,$schgrdstr);

   if((int)$strictlvlmode < 1){
    // exit("Is not Strict");
     //a safer approach to get student level in a particular sesion is to get it from course registration, if not exit fall back to old calculating method
    $Lvl = StudLevelSesSafe($RegNo,$Ses);
   }else{
    //exit("Is Strict");
   }
    
    
   // exit($StudCourseRegSes);
    //calculate student level 
    //$Lvl = StudLevelSes($RegNo,$Ses);
     //get the student result 
     $studrst = $dbo->Select("result_tb","","RegNo='$RegNo' AND Lvl=$Lvl AND Sem=$Sem AND SesID=$Ses AND GroupID >= $GroupID");
     if(is_array($studrst)){
       //check if record exist 
       if($studrst[1] > 0){//result found
         while($indstudrst = $studrst[0]->fetch_assoc()){
         
           $crst = $indstudrst['Rst'];
           
          // $rstinfo = trim($indstudrst['RstInfo']) == "" || trim($indstudrst['RstInfo']) == "[]"?[]:json_decode($indstudrst['RstInfo'],true);
           //$CGP = (int)$indstudrst['CGP'];
           //$CCH = (int)$indstudrst['CCH'];
           //New
           //$TGP = (int)$indstudrst['TGP'];
           //$TCH = (int)$indstudrst['TCH'];
           //New
           $crstArr = $dbo->DataArray($crst);
           
           //get the old score and calculate GP/CH, then subtract from total GP & CH. Calculate the new and add respectively
           //*************************************************
          /*  if(isset($crstArr[$courseID])){ //if result exit
           $proccnumfailed = false;
           $couseExistInRept = true;
             $oldscore = $crstArr[$courseID];
             //get ca and exam
             $oldscoreArr = explode("|",$oldscore);
             if(count($oldscoreArr) == 2){
               $oldTot = (int)$oldscoreArr[0] + (int)$oldscoreArr[1];
               $oldgrds = GetGrade($oldTot,$grdstr,$schgrdstr);
               $oldGP = $CH * $oldgrds['Level'];
               
               //deduct oldGP and oldCH from CGP and CCH respectively
               $CGP -= $oldGP;
               $CCH -= $CH;

             }
             
           }
 */
           //**************************************************
           $crstArr[$courseID] = isset($crstArr[$courseID])?$crstArr[$courseID]:"";
            //check if Back Save
           /*  if($updatetype  < 1 && isset($rstinfo[$courseID]['GradeStruc'])){
               //get 
               $grds = GetGradeFromString($Tot,$rstinfo[$courseID]["GradeStruc"]);
            }else{
              $grds = GetGrade($tot,$grdstr,$schgrdstr);
            }
            */
           //exit(json_encode($grds));
$scoreb4 = $crstArr[$courseID];
/* $scoreb4 = explode("|",$scoreb4);
 //check if no changes found - if normal save, and CA and Exam are the same (cos the system will use the result info so there will be no change)
 //check if changes made
 $changesmade = false;
 //get the scoreb4 scores
 if(strpos($scoreb4[0],",") !== false){ // if new score structure (>=v4)
    //get all scores
    $Scoreb4Arr = explode(",",$scoreb4[0]);
    if(count($Scoreb4Arr) == count($ScoreArr)){ //if same signature
       //confirm individual score
       foreach($Scoreb4Arr as $scind=>$Scoreb4Val){
         if((float)$Scoreb4Val != $ScoreArr[$scind]){
          $changesmade = true; break;
         }
       }
    }else{
      $changesmade = true;
    }

 }else{ //if old structure
  if(count($ScoreArr) == 2){ //CA and Exam
    if($ScoreArr[0] != (float)$scoreb4[0] || $ScoreArr[1] != (float)$scoreb4[1]){
      $changesmade = true;
    }
  }else{
    $changesmade = true;
  }
 } */
// exit($updatetype);
$changesmade = IsChangesMade($scoreb4,$ScoreArr);
//if Normal Save and the score structure is valid and no score not changed, then no need to do any thing
 if($updatetype < 1 && count($scoreb4) >= 2 && $changesmade == false){
   
  continue;
} 
//if(count())
           //update the score
           //$crstArr[$courseID] = $CA."|".$Exm;
           $crstArr[$courseID] = implode("|",[implode(",",$ScoreArr),implode(",",$rstScoreStrucMaxObj)]);
           //will be properly format (includes the grading details) in Recalculate
          //$grdPoint = (int)$grds['Level']; //get the grade point
          //$newGP = $CH * $grdPoint;
          
           $urst = $dbo->DataString($crstArr,false);
          
           
           //calculate cummulatives 
           //$CGP += $newGP;
           //$CCH += $CH;

           //$Rept = $indstudrst['Rept'];
           //$Rept = UpdateRepeat($Rept,$grds,$proccnumfailed);


           /* $RstInfo = $crst['RstInfo'];
           //check if result info exist
           if(is_null($RstInfo) || trim($RstInfo) == ""){
            $RstInfo = FormRstInfo($crstArr);
           }else{ //if RstInfo already exist
             $RstInfo = UpdateRstInfo($RstInfo,$courseDet);
           } */
          // $query .= $tot."|".$grds['PASS'].";";
          $indstudrst['Rst'] = $urst;


          //$indstudrst['Rept'] = $Rept;

          
          //$indstudrst['CGP'] = $CGP;
          //$indstudrst['CCH'] = $CCH;
          
            //recalculate result
            $newcalc = Recalculate($indstudrst);
            
            if($newcalc['SubQuery'] != ""){
              $query .= $newcalc['SubQuery'] ;
              //echo $query;
            }
            
         }
        
       }else{//no result found
         //$query .= $tot."|".$grds['PASS'].";";
          if($GroupID > 1){ //meaning lower result group exist
            //Get the imideate result 
            $imdrst = $dbo->SelectFirstRow("result_tb","","RegNo='$RegNo' AND Lvl=$Lvl AND Sem=$Sem AND SesID=$Ses AND GroupID < $GroupID ORDER BY GroupID DESC Limit 1");
            if(is_array($imdrst)){
              //if immediate result found
              $crst = $imdrst['Rst'];
              //$imCGP = (int)$imdrst['CGP'];
              //$imCCH = (int)$imdrst['CCH'];
              $crstArr = $dbo->DataArray($crst);
              //Get the old immediate score, calculate GP
              /* if(isset($crstArr[$courseID])){
                $imdoldscore = $crstArr[$courseID];
                $imdoldscoreArr = explode("|",$imdoldscore);
                if(count($imdoldscoreArr) == 2){
                  $imdoldtot = $imdoldscoreArr[0] + $imdoldscoreArr[1];
                  $imoldgrds = GetGrade($imdoldtot,$grdstr,$schgrdstr);
                 $imoldGP = $CH * $imoldgrds['Level'];
               
               //deduct oldGP and oldCH from CGP and CCH respectively
                  $imCGP -= $imoldGP;
                  $imCCH -= $CH;
                }
              } */
              //$crstArr[$courseID] = $ScoreStr;
              $crstArr[$courseID] = isset($crstArr[$courseID])?$crstArr[$courseID]:"";
           //$grds = GetGradeLocal($crstArr[$courseID],$CA,$Exm,$grdstr,$schgrdstr);
           if($crstArr[$courseID] != ""){
             /* $prevrst = explode("|",$crstArr[$courseID]);
             if($CA == (float)$prevrst[0] && $Exm == (float)$prevrst[1])continue;  
            if(IsChangesMade($prevrst,$ScoreArr) == false)continue;*/ 
             }
           //update the score
          //  $crstArr[$courseID] = $CA."|".$Exm;
           $crstArr[$courseID] = implode("|",[implode(",",$ScoreArr),implode(",",$rstScoreStrucMaxObj)]);
           
          //$grdPoint = (int)$grds['Level']; //get the grade point
          //$newGP = $CH * $grdPoint;
              $urst = $dbo->DataString($crstArr,false);
              //check if update done
              /* if($crst == $urst){
                continue;
              } */
              $Rept = $imdrst['Rept'];
              $OutSt = $imdrst['Outst'];

              //$imdrst['Rept'] = UpdateRepeat($Rept,$grds,true);

              //set the new GroupID
              $imdrst['GroupID'] = $GroupID;

              //set the new rst
              $imdrst['Rst'] = $urst;

              //add the new result GP and CH to the CGP and CCH
              //$imCGP += $newGP;
                  //$imCCH += $CH;
                  $newcalc = Recalculate($imdrst,false); //perform insert
            if($newcalc['SubQuery'] != ""){
              $query .= $newcalc['SubQuery'] ;
            }
              //form insert
               // $query .= "INSERT INTO result_tb (`RegNo`, `Lvl`, `Sem`, `SesID`, `Rst`, `Outst`,`Rept`,`GroupID`,`CGP`,`CCH`) VALUES ('$RegNo',$Lvl,$Sem,$Ses,'$urst', '$OutSt', '$Rept', $GroupID,$imCGP , $imCCH);";
            }else{ 
              //student record does not exist atall even though the current group is not one
              //Posible course is after result approved some student register for the course, and result was un-approve in order to upload the new student result (the new student did not have any result, but the current result group is not 1)
               //Perform the normal insert operation
               $Rept = '';$OutSt='';
          //form imedite level sem
         // $implvlsem = GetPrevLvlSem($Lvl,$Sem);
          $imdCGP = 0;$imdCCH=0;
         // if($implvlsem['err'] == ""){
           /* $imLvl = $implvlsem['level'];$imSem = $implvlsem['semester'];
            $imdrst = $dbo->SelectFirstRow("result_tb","","RegNo='$RegNo' AND Lvl=$imLvl AND Sem=$imSem ORDER BY ID DESC Limit 1");*/
            $imdrst = GetPrevResult($RegNo,$Lvl,$Sem);
            $Rept = ""; $iTCH = $iTGP = $iBCH = $iBGP = $iCCH = $iCGP = 0;
            if(is_array($imdrst)){//if exist
               $Rept = $imdrst['Rept'];
               $ReptArr = explode("+",$Rept);
               if(count($ReptArr) > 1){
                 $Rept = $ReptArr[1]."+".$ReptArr[1];
               }
               $OutSt = $imdrst['Outst'];
               $OutStArr = explode("+",$OutSt);
               if(count($OutStArr) > 1){
                 $OutSt = $OutStArr[1]."+".$OutStArr[1];
               }
               
               $iCGP = $iBGP = $imdCGP = (int)$imdrst['CGP'];
               $iBCH = $iCCH = $imdCCH = (int)$imdrst['CCH'];
            }
            //update the repeat str
            //$Rept = UpdateRepeat($Rept,$grds,true);
         // }
         //$crstArr[$courseID] = isset($crstArr[$courseID])?$crstArr[$courseID]:"";
           //$grds = GetGradeLocal("",$CA,$Exm,$grdstr,$schgrdstr);
           //update the score
           $ScoreStr = $grds['ScoreStr'];
         // $grdPoint = (int)$grds['Level']; //get the grade point
         // $newGP = $CH * $grdPoint;
          // $urst = $courseID."=".$CA."|".$Exm;
          $urst = $courseID."=".implode("|",[implode(",",$ScoreArr),implode(",",$rstScoreStrucMaxObj)]);
          
          //$imdCCH += $CH;
          //$imdCGP += $newGP;

          /* $query .= "INSERT INTO result_tb (`RegNo`, `Lvl`, `Sem`, `SesID`, `Rst`, `Outst`,`Rept`,`GroupID`,`CGP`,`CCH`,`TGP`,`TCH`,`BGP`,`BCH`,RstInfo) VALUES ('{$RstDet['RegNo']}',{$RstDet['Lvl']},{$RstDet['Sem']},{$RstDet['SesID']},'{$RstDet['Rst']}', '{$RstDet['Outst']}', '{$RstDet['Rept']}', {$RstDet['GroupID']},{$rtn['CGP']} , {$rtn['CCH']},{$rtn['TGP']},{$rtn['TCH']},{$rtn['BGP']},{$rtn['BCH']},'".$dbo->SqlSafe(json_encode($newRstInfo['RstInfo']))."');"; */
        $RstArr = ['RegNo'=>$RegNo,'Lvl'=>$Lvl,'Sem'=>$Sem,'SesID'=>$Ses,'Rst'=>$urst,'Outst'=>$OutSt,'Rept'=>$Rept,'GroupID'=>$GroupID,"TCH"=>$iTCH,"TGP"=>$iTGP,"BCH"=>$iBCH,"BGP"=>$iBGP,"CCH"=>$iCCH,"CGP"=>$iCGP,"RstInfo"=>"","COP"=>""];
        $newcalc = Recalculate($RstArr,false); //perform insert
        if($newcalc['SubQuery'] != ""){
          $query .= $newcalc['SubQuery'] ;
        }
            }
          }else{// meaning no result exist atall
          $Rept = '';$OutSt='';
          //form imedite level sem
         // $implvlsem = GetPrevLvlSem($Lvl,$Sem);
          $imdCGP = 0;$imdCCH=0;
         // if($implvlsem['err'] == ""){
           /* $imLvl = $implvlsem['level'];$imSem = $implvlsem['semester'];
            $imdrst = $dbo->SelectFirstRow("result_tb","","RegNo='$RegNo' AND Lvl=$imLvl AND Sem=$imSem ORDER BY ID DESC Limit 1");*/
            $imdrst = GetPrevResult($RegNo,$Lvl,$Sem);
            $Rept = ""; $iTCH = $iTGP = $iBCH = $iBGP = $iCCH = $iCGP = 0;
            if(is_array($imdrst)){//if exist
               $Rept = $imdrst['Rept'];
               $ReptArr = explode("+",$Rept);
               if(count($ReptArr) > 1){
                 $Rept = $ReptArr[1]."+".$ReptArr[1];
               }
               $OutSt = $imdrst['Outst'];
               $OutStArr = explode("+",$OutSt);
               if(count($OutStArr) > 1){
                 $OutSt = $OutStArr[1]."+".$OutStArr[1];
               }
               
               $iCGP = $iBGP = $imdCGP = (int)$imdrst['CGP'];
               $iBCH = $iCCH = $imdCCH = (int)$imdrst['CCH'];
            }
            //update the repeat str
            //$Rept = UpdateRepeat($Rept,$grds,true);
         // }
         //$crstArr[$courseID] = isset($crstArr[$courseID])?$crstArr[$courseID]:"";
           //$grds = GetGradeLocal("",$CA,$Exm,$grdstr,$schgrdstr);
           //update the score
           $ScoreStr = $grds['ScoreStr'];
         // $grdPoint = (int)$grds['Level']; //get the grade point
         // $newGP = $CH * $grdPoint;
          // $urst = $courseID."=".$CA."|".$Exm;
          $urst = $courseID."=".implode("|",[implode(",",$ScoreArr),implode(",",$rstScoreStrucMaxObj)]);
          
          //$imdCCH += $CH;
          //$imdCGP += $newGP;

          /* $query .= "INSERT INTO result_tb (`RegNo`, `Lvl`, `Sem`, `SesID`, `Rst`, `Outst`,`Rept`,`GroupID`,`CGP`,`CCH`,`TGP`,`TCH`,`BGP`,`BCH`,RstInfo) VALUES ('{$RstDet['RegNo']}',{$RstDet['Lvl']},{$RstDet['Sem']},{$RstDet['SesID']},'{$RstDet['Rst']}', '{$RstDet['Outst']}', '{$RstDet['Rept']}', {$RstDet['GroupID']},{$rtn['CGP']} , {$rtn['CCH']},{$rtn['TGP']},{$rtn['TCH']},{$rtn['BGP']},{$rtn['BCH']},'".$dbo->SqlSafe(json_encode($newRstInfo['RstInfo']))."');"; */
        $RstArr = ['RegNo'=>$RegNo,'Lvl'=>$Lvl,'Sem'=>$Sem,'SesID'=>$Ses,'Rst'=>$urst,'Outst'=>$OutSt,'Rept'=>$Rept,'GroupID'=>$GroupID,'GroupID'=>$GroupID,"TCH"=>$iTCH,"TGP"=>$iTGP,"BCH"=>$iBCH,"BGP"=>$iBGP,"CCH"=>$iCCH,"CGP"=>$iCGP,"RstInfo"=>"","COP"=>""];
        $newcalc = Recalculate($RstArr,false); //perform insert
        if($newcalc['SubQuery'] != ""){
          $query .= $newcalc['SubQuery'] ;
        }
         //  $query .= "INSERT INTO result_tb (`RegNo`, `Lvl`, `Sem`, `SesID`, `Rst`, `Outst`,`Rept`,`GroupID`,`CGP`,`CCH`) VALUES ('$RegNo',$Lvl,$Sem,$Ses,'$urst','$OutSt','$Rept',$GroupID,$imdCGP,$imdCCH);";

          }
       }
     }
  }
  return $query;
}


//discol&sdatastr&rstparam
if(isset($_POST['discol'])){
 
  extract($_POST);//rstScoreStruc
  if(!isset($RstInfoID) || (int)$RstInfoID < 1)exit("#Result Settings Not Found");
  //get grading structure
  $grdstr = $dbo -> SelectFirstRow("resultinfo_tb","","ID = ".$RstInfoID);
  //$grdstr = $dbo -> SelectFirstRow("resultinfo_tb","","ID = (select GrdStrucID from school_tb limit 1)");
$classPassStr = $grdstr['ClassOfPass'];
          $grdstr = is_array($grdstr)?$grdstr[1]:""; //The Grading e,g 34-60=2&<34=1
          $schgrdstr = GetGradeDetAll($RstInfoID);
          $classPassDetAll = GetClassPassDetAll($RstInfoID);
  
 // exit();
  $rstScoreStrucMaxObj = json_decode(urldecode($rstScoreStrucMax),true);
  $rstScoreStrucObj = json_decode(urldecode($rstScoreStruc),true);
  $rstScoreStrucIDObj = json_decode(urldecode($rstScoreStrucID),true);
  //form data strings
  $discolDS = $dbo->DataArray($discol);
  $sdatastrDS = $dbo->DataArray($sdatastr);
  $rstparamDS = $dbo->DataArray($rstparam);

  //var fields = ["sestb","rstudstudy","rstudfac","rstuddept","rstudprog","rstudlvl","semest"];
  $Lvl = rawurldecode($rstparamDS["rstudlvl"]);
  $Sem = rawurldecode($rstparamDS["semest"]);
  $Ses = rawurldecode($rstparamDS["sestb"]);
  $progid = rawurldecode($rstparamDS["rstudprog"]);
  $courseID = rawurldecode($rstparamDS["rcourse"]);

  $studyID = rawurldecode($rstparamDS["rstudstudy"]);

  //Get the Result Course Details
  $courseDet = $dbo->SelectFirstRow("course_tb c, coursegroup_tb cg","c.*,cg.AllowFail","c.CourseID=$courseID AND c.GroupID = cg.ID LIMIT 1");

  $isupdate = false;
  //print_r($courseDet);
  //exit();
  if(!is_array($courseDet)){
    exit("#Invalid Course");
  }
  //$studcourses = GetCourses($progid,$Lvl,$Sem);
  //Check if Approval row Exist
  $apprst = $dbo->SelectFirstRow("resultapprove_tb","","ProgID = $progid AND Ses = $Ses AND Lvl = $Lvl AND Sem = $Sem AND CourseID = $courseID AND StudyID = $studyID ORDER BY GroupID DESC LIMIT 1");

  
  //$apprv = null;//hold the result approval status 
  $query = ""; //holds the entire query to run at the end
  $rststrucjson = urldecode($rstScoreStruc);
  $rststrucjsonMax = urldecode($rstScoreStrucMax);
  
  if(!is_array($apprst)){ //if not exist
       
       $query .= "INSERT INTO `resultapprove_tb`(`ProgID`, `Ses`, `Lvl`, `Sem`, `CourseID`, `StudyID`, `Status`, `GroupID`, `ScoreStruc`, `ScoreStrucMax`,`RstInfoID`) VALUES ($progid,$Ses,$Lvl,$Sem,$courseID,$studyID,'FALSE',1,'".$dbo->SqlSafe($rststrucjson)."','".$dbo->SqlSafe($rststrucjsonMax)."',$RstInfoID);";
       $query .= FormResultQuery(1); //form the result query for the new group
  }else{ //if approval exist
   // exit($rstScoreStruc);
    //check if score struc not set
    if((int)$apprst['RstInfoID'] != (int)$RstInfoID){
       $upd = $dbo->Update("resultapprove_tb",["ScoreStruc"=>$rststrucjson,"ScoreStrucMax"=>$rststrucjsonMax,"RstInfoID"=>$RstInfoID],"ID=".$apprst['ID']);
       //exit($rststrucjson);
    }
       $AppGroupID = $apprst["GroupID"];
       $Status = $apprst["Status"];
       //check Stautus 
       if($Status == "TRUE"){ //if result is approved
         exit("Operation Aborted, Result Already Approved");
       }else{ //if not approved
         $query .= FormResultQuery($AppGroupID); //form the result query for the current group id
       }

       
  }
  
 if(trim($query) != ""){
  $dump = $dbo->Connection->multi_query($query);
  if(!$dump){
    echo "#Server Error: ".$dbo->Connection->error;
  }else{
     echo "*Result Saved";
  }
 }else{
   echo "No Change Found";
 }
  
}



?>