<?php

//R033 - 
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//Snipet Used in Pages/Script/Course/loadstudreg.php in cportal
//So Any update done here should be done there
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function GetStudentCourses($Param){
    
    global $dbo;
    //session_start();
    HasLogin($Param);

    //check if AutoCourseReg is disabled
    //get the course control detaisl
    $courseCntr = $dbo->SelectFirstRow("coursecontrol_tb");
    if($courseCntr['AutoRegStatus'] == "TRUE"){
        Error(40,'<br/><button class="bbwa-button w3-large" onclick="Application.Load({ApplyGID:3,AutoLoad:true,Home:true,Logout:false,Guest:true,OpenFrom:\'open-from-menu\'})" ><span class="mbri-credit-card"></span> &nbsp; Make Payment Now</button>');
    }

    //check if its semester strict
    $curentSem = NULL;
    if($courseCntr['SemStrict'] == 'TRUE'){
         //get the current semester details
      $curentSem = $dbo->SelectFirstRow("semester_tb","","Current=1",MYSQLI_ASSOC);
      if(!is_array($curentSem))Error(77);
    
    } 


    $maxsem = 2;
    //get the maximum semester number
    $semma = $dbo->SelectFirstRow("semester_tb","count(ID)","Enable = 1");
    if(is_array($semma)){
        $maxsem = (int)$semma[0];
    }

    $studDet = $dbo->SelectFirstRow("studentinfo_tb","","RegNo='{$Param['LoginName']}' OR JambNo='{$Param['LoginName']}'");
            if(is_array($studDet)){
                $studDet['RegNo'] = (is_null($studDet['RegNo']) || trim($studDet['RegNo']) == "")?$studDet['JambNo']:$studDet['RegNo'];
    //get last course Registered
    $coursereg = $dbo->SelectFirstRow("coursereg_tb","*,Lvl as LevelID, Sem as SemesterID","RegNo='".$studDet['RegNo']."' OR RegNo='".$studDet['JambNo']."' ORDER BY Lvl DESC, Sem DESC",MYSQLI_ASSOC);
            if(!is_string($coursereg)){
                if(!is_array($coursereg)){
                    $coursereg = [];
                    list($LevelID,$SemesterID) = GetStudentLevelSemesterWhenSchoolStart($studDet['RegNo']);
                    //$coursereg['LevelID'] = 1;
                    //$coursereg['SemesterID'] = 0;
                }else{
                    $LevelID = $coursereg['LevelID'];
                    $SemesterID = $coursereg['SemesterID'];
                    
                    $SemesterID++;
                    
                if($SemesterID > $maxsem){
                    $SemesterID = 1;
                    $LevelID++;
                } 
                }
                
                //get the school current session21`
                $curses = GetSchoolSession();
                //verify if the current semester
                if(!is_null($curentSem) && $SemesterID != $curentSem['Num']) Error(78);
                if(!is_null($curentSem) && $SemesterID > 1 && $coursereg['SesID'] != $curses['SesID']) Error(78);

                
            //Error(4," - ".$LevelID." ; ".$SemesterID);
            //Error(4," - ".$LevelID." ; ".$SemesterID);
            //get the student progid
            
              $ProgID = $studDet['ProgID'];
              
              //check payment
              $PayDet = $dbo->SelectFirstRow("payhistory_tb","","(RegNo='".$studDet['RegNo']."' OR RegNo='".$studDet['JambNo']."') AND Lvl = {$LevelID} AND Sem >= $SemesterID AND SemPart > 0 AND ProgID=$ProgID AND PayID = {$courseCntr['PayID']}");
              $LevelName = GetStudentLevelName($LevelID,$studDet['StudyID'],$ProgID);
                  $semester = GetStudentSemesterName($SemesterID);
               if(is_array($PayDet)){
                   //get current session
                   
                   $lvlses = $curses['SesID'];
                   $LevelIDOp = OperationalLevel($LevelID,$ProgID);
                   //spilover student management
                   //1.get the maximum level
                 
                  //get the courses
                  $Courses = $dbo->Select("course_tb","","DeptID=".$ProgID." AND Lvl=$LevelIDOp AND Sem=$SemesterID AND StartSesID <= $lvlses AND (EndSesID >= $lvlses OR EndSesID = 0) AND CourseStatus = 0");
                  if(!is_array($Courses))Error(32);
                  if($Courses[1] < 1)Error(33);
                  //get the max ch
                  $maxch = GetMaxCH($ProgID,$LevelID,$SemesterID);
                  $StudCourses = [];
                  $semclass = "semcourse";
                  $autoclass = "autoreg";
                  $llcclass = "llc";
                  $accCH = 0;
                  //loop through each student courses and add classes as required
                  while($indcourse = $Courses[0]->fetch_assoc()){
                    $indcourse['Class'] = $semclass;
                    $indcourse['CourseCode'] = strtoupper($indcourse['CourseCode']);
                    $indcourse['Title'] = ucwords($indcourse['Title']);
                    //get the ch
                    $accCH += (int)$indcourse['CH'];
                    if($accCH <= $maxch){
                        $indcourse['Class'] .= " ".$autoclass;
                    }
                    $StudCourses[] = $indcourse;
                  }

                  //if lower level courses is enabled
                  $LLC = [];
                  if($courseCntr['LowerLevel'] == 'TRUE'){
                    $LCoursese = [];
                    $lCourses = $dbo->Select("course_tb","","DeptID=".$ProgID." AND Lvl<$LevelIDOp AND Sem=$SemesterID  AND CourseStatus = 0 ORDER BY Lvl Desc");
                    if(!is_array($lCourses))Error(32);
                    if($lCourses[1] > 0){
                        $LevelSesArr = [];
                        while($lindcourse = $lCourses[0]->fetch_assoc()){
                            if(!isset($LevelSesArr[$lindcourse['Lvl']])){
                                //check if student register for course at the Lvl Sem
                                $courseregll = $dbo->SelectFirstRow("coursereg_tb","","RegNo='{$Param['LoginName']}' AND Lvl=".$lindcourse['Lvl']." AND Sem=".$lindcourse['Sem']);
                                if(is_array($courseregll)){ //if course registration exist for the lower level
                                //get the sesid
                                $LevelSesArr[$lindcourse['Lvl']] = (int)$courseregll["SesID"];
                                }else{
                                    //if the student does not register for the level which is abnormal
                                    //use the current session
                                    $LevelSesArr[$lindcourse['Lvl']] = $lvlses;  
                                }
                            }

                            //check if course not expired 
                            //StartSesID <= $lvlses AND (EndSesID >= $lvlses OR EndSesID = 0)
                            if((int)$lindcourse['StartSesID'] <= $LevelSesArr[$lindcourse['Lvl']] || ((int)$lindcourse['EndSesID'] >=  $LevelSesArr[$lindcourse['Lvl']] || (int)$lindcourse['EndSesID'] == 0)){
                                $lindcourse['Class'] = $llcclass;
                                $lindcourse['CourseCode'] = strtoupper($lindcourse['CourseCode']);
                                $lindcourse['Title'] = ucwords($lindcourse['Title']);
                            //get the ch
                           /*  $accCH += (int)$indcourse['CH'];
                            if($accCH <= $maxch){
                                $indcourse['Class'] .= " ".$autoclass;
                            } */
                            $LCoursese[] = $lindcourse;
                            }
                            
                            
                          }
                    }
                    if(count($LCoursese) > 0){
                        $LLC["Courses"] = $LCoursese;
                    }
                  }
                  
                  return ["SLC"=>["Courses"=>$StudCourses],"LLC"=>$LLC,"LevelName"=>$LevelName,"SemesterName"=>$semester,"LevelID"=>$LevelID,"SemesterID"=>$SemesterID,"ProgID"=>$studDet['ProgID'],"RegNo"=>$Param['LoginName'],"SemesterClass"=>$semclass,"AutoClass"=>$autoclass,"LLCClass"=>$llcclass,"LevelIDOp"=>$LevelIDOp];
               }else{
                   //Make the page auto reload incase user make payment
                   $Param['PageClass'] = "ReloadOnPaid";
                   $Param["ErrorImage"] = "images/pages/notpaid.png";
                   Error(13,' <br/> <button class="bbwa-button w3-large" onclick="((event)=>{Application.Load({ApplyGID:3,AutoLoad:true,Home:true,Logout:false,Guest:true,OpenFrom:\'open-from-menu\'});event.stopPropagation();})(event)" ><span class="mbri-credit-card"></span> &nbsp; Make Payment Now</button>',$Param);
                   /* Error(13,' <hr/>'.$LevelName.' / '.$semester.'<hr/><button class="bbwa-button w3-large" onclick="((event)=>{Application.Load({ApplyGID:3,AutoLoad:true,Home:true,Logout:false,Guest:true,OpenFrom:\'open-from-menu\'});event.stopPropagation();})(event)" ><span class="mbri-credit-card"></span> &nbsp; Make Payment Now</button>',$Param); */
               }
            
               // return $coursereg;
            }else{
                Error(4,": Reading Student Course Registration History Failed ".$coursereg);
            }
        }else{
            Error(4,": Reading Student Details Failed");
        }
}

  //R034
  function RegisterCourses($Param){
    global $dbo;global $__Root__;
    //Error(5," - ".json_encode($Param['toogleLcourses']);
    //check if a valid login student
    if(!isset($Param['RegNo']) || trim($Param['RegNo']) == "")Error(8);
  //check if valid course Registration details sent
  if(!isset($Param['CoursesReg']) || count($Param['CoursesReg']) < 1 || !isset($Param['LevelID']) || (int)$Param['LevelID'] < 1 || !isset($Param['SemesterID']) || (int)$Param['SemesterID'] < 1 || !isset($Param['ProgID']) || (int)$Param['ProgID'] < 1)Error(0);
  //get school session
  $getses = GetSchoolSession();
  $RegCoursesDet = [];
  $RegCourse = [];
  $totch = 0;
  //get all the selected courses
  foreach($Param['CoursesReg'] as $coursedet){
      if((int)$coursedet["state"] == 0 || (int)$coursedet["value"] == 0)continue;
      //get the course details
      $cdet = $dbo->SelectFirstRow("course_tb","","CourseID=".$coursedet["value"],MYSQLI_ASSOC);
      //if exist
      if(!is_array($cdet))continue;
      $RegCoursesDet[$coursedet["value"]] = $cdet;
      $RegCourse[] = $coursedet
      ["value"];
      $totch += $cdet['CH'];
  }

  //check if user select one or more coreses
  if(count($RegCourse) < 1)Error(36);

  //check lower level selection
  if((int)$Param['toogleLcourses'] == 1){
       //get all the selected courses
      foreach($Param['LCoursesReg'] as $coursedet){
          if((int)$coursedet["state"] == 0 || (int)$coursedet["value"] == 0)continue;
          //get the course details
          $cdet = $dbo->SelectFirstRow("course_tb","","CourseID=".$coursedet["value"],MYSQLI_ASSOC);
          //if exist
          if(!is_array($cdet))continue;
          $RegCoursesDet[$coursedet["value"]] = $cdet;
          $RegCourse[] = $coursedet
          ["value"];
          $totch += $cdet['CH'];
      }
  }

  //get the max ch (function from getinfo.php)
  $maxch = GetMaxCH($Param['ProgID'],$Param['LevelID'],$Param['SemesterID']);
  if($totch >  $maxch)Error(34," ($maxch)");

//check if already registered
$creg = $dbo->SelectFirstRow("coursereg_tb","ID","RegNo='".$dbo->SqlSafe($Param['RegNo'])."' AND Lvl=".$dbo->SqlSafe($Param['LevelID'])." AND Sem=".$dbo->SqlSafe($Param['SemesterID'])."");
if(is_array($creg)){
  
$Param['CourseRegID'] = $creg["ID"];
$ardata = "{Src:'{$__Root__}general/Slip.php?CourseRegID=".urlencode($creg["ID"])."&folder=Course&file=Slipi.php&SubDir=".urlencode($dbo->Config['SubDir'])."',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:4}";
$Param["PrintData"] = $ardata;
$Param["AutoReg"] = [];
return $Param;
}

  //register courses
  $reg = $dbo->InsertID2("coursereg_tb",["RegNo"=>$Param['RegNo'],"Lvl"=>$Param['LevelID'],"CoursesID"=>implode("~",$RegCourse),"SesID"=>$getses['SesID'],"Sem"=>$Param['SemesterID'],"RegDate"=>date('Y-m-d'),"MaxCH"=>$maxch,"CouresRegData"=>json_encode($RegCoursesDet),"TotCH"=>$totch]);
  //$reg = 1;
  if(is_numeric($reg)){
       
      //5. Generate New RegNo and Update as required
      $autoreg = AutoGenRegNo($Param['RegNo']);
      //Error(29," - ".$autoreg);
      //if error
       if(!is_array($autoreg) &&  $autoreg != "##"  &&  $autoreg != "####"){
          //remove course registered
          $del = $dbo->Delete("coursereg_tb","ID=".$reg);
          if($autoreg == "#")$autoreg = "Reading School Details Failed";
          if($autoreg == "###")$autoreg = "Reading Student Details Failed";
          if($autoreg == "#####")$autoreg = "Global Update Failed";
          Error(29, ", and Course Registration Reversed - ".$autoreg); 
      } 
      $AutoReg = [];
      //$autoreg = [$Param['RegNo']];
      if(is_array($autoreg)){
          $AutoReg = ["NewReg"=>$autoreg[0],"NRedirectData"=>"{Src:'{$__Root__}general/Slip.php?regno={$autoreg[0]}&folder=Form&SubDir=".urlencode($dbo->Config['SubDir'])."',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:30}"];
          $Param['RegNo'] = $autoreg[0];

          $studprog = $dbo->SelectFirstRow("studentinfo_tb","ProgID,SurName,FirstName,Phone","RegNo='{$Param['RegNo']}' OR JambNo='{$Param['RegNo']}'");
          if(is_array($studprog)){
              $sch = GetSchool();
              //Send Message
              $sendmail = $dbo->SendSMS($sch['Abbr'],"Hello, ".$studprog['SurName']." ".$studprog['FirstName']. ", your school Registration Number is {$Param['RegNo']}",$studprog['Phone'],"234",$sch['OpUName'],$sch['OpUPassw'],$sch['OpSMSLive']=="FALSE"?false:true);
              $rstdet = explode("|",$sendmail);
              if(strtolower($rstdet[0]) == "success"){
              //$sendmail = TRUE;
              }
          }

          
      }
      $Param['CourseRegID'] = $reg;
      $ardata = "{Src:'{$__Root__}general/Slip.php?CourseRegID=".urlencode($reg)."&folder=Course&file=Slipi.php&SubDir=".urlencode($dbo->Config['SubDir'])."',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:4}";
  $Param["PrintData"] = $ardata;
  //$Param['RegNo'] = 
  //$rdata = "{Src:'Slip.php?regno={$Param['RegNo']}&folder=Form',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:30}";
  $Param["AutoReg"] = $AutoReg;
  //Error(35,json_encode($Param));
      return $Param;
  }else{
      Error(35);
  }
}

//R035
function UndoCourseRegistration($Param){
  
  global $dbo;
  //session_start();
  HasLogin($Param);

  //conform required fields
  if(!isset($Param['CourseRegID']) || (int)$Param['CourseRegID'] == 0){
    Error(0);
  }

  //delete the courseReg Details
  $delc = $dbo->Delete("coursereg_tb","ID=".$Param['CourseRegID']." AND RegNo='".$Param['LoginName']."'");
  if(is_array($delc)){
      return [];
  }else{
      Error(37);
  }

}

//R069
function UpdateCourses($Param){
    global $dbo;global $__Root__;
    //Error(5," - ".json_encode($Param['toogleLcourses']);
    //check if a valid login student
    if(!isset($Param['RegNo']) || trim($Param['RegNo']) == "")Error(8);
  //check if valid course Registration details sent
  if(!isset($Param['CoursesReg']) || count($Param['CoursesReg']) < 1 || !isset($Param['CourseRegID']))Error(0);
  //check if already registered
$creg = $dbo->SelectFirstRow("coursereg_tb","*","ID=".$dbo->SqlSafe($Param['CourseRegID']));
if(!is_array($creg))Error(38);
  //get school session
  $getses = GetSchoolSession();

  //check if not same session
  if($getses['SesID'] != $creg['SesID'])Error(68);

  //check if result already uploaded
  $hasResult = $dbo->SelectFirstRow("result_tb","ID","RegNo='".$creg['RegNo']."' AND Lvl=".$creg['Lvl']." AND Sem=".$creg['Sem']." AND SesID=".$creg['SesID']);
  if(is_array($hasResult))Error(69);

  $RegCoursesDet = [];
  $RegCourse = [];
  $totch = 0;
  //get all the selected courses
  foreach($Param['CoursesReg'] as $coursedet){
      if((int)$coursedet["state"] == 0 || (int)$coursedet["value"] == 0)continue;
      //get the course details
      $cdet = $dbo->SelectFirstRow("course_tb","","CourseID=".$coursedet["value"],MYSQLI_ASSOC);
      //if exist
      if(!is_array($cdet))continue;
      $RegCoursesDet[$coursedet["value"]] = $cdet;
      $RegCourse[] = $coursedet
      ["value"];
      $totch += $cdet['CH'];
  }

  //check if user select one or more coreses
  if(count($RegCourse) < 1)Error(36);

  //check lower level selection
  if((int)$Param['toogleLcourses'] == 1){
       //get all the selected courses
      foreach($Param['LCoursesReg'] as $coursedet){
          if((int)$coursedet["state"] == 0 || (int)$coursedet["value"] == 0)continue;
          //get the course details
          $cdet = $dbo->SelectFirstRow("course_tb","","CourseID=".$coursedet["value"],MYSQLI_ASSOC);
          //if exist
          if(!is_array($cdet))continue;
          $RegCoursesDet[$coursedet["value"]] = $cdet;
          $RegCourse[] = $coursedet
          ["value"];
          $totch += $cdet['CH'];
      }
  }

  //get the max ch (function from getinfo.php)
  $maxch = GetMaxCH($Param['ProgID'],$Param['LevelID'],$Param['SemesterID']);
  if($totch >  $maxch)Error(34," ($maxch)");


/* if(is_array($creg)){
  
$Param['CourseRegID'] = $creg["ID"];
$ardata = "{Src:'{$__Root__}general/Slip.php?CourseRegID=".urlencode($creg["ID"])."&folder=Course&file=Slipi.php&SubDir=".urlencode($dbo->Config['SubDir'])."',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:4}";
$Param["PrintData"] = $ardata;
$Param["AutoReg"] = [];
return $Param;
} */

  //register courses
  $reg = $dbo->Update("coursereg_tb",["CoursesID"=>implode("~",$RegCourse),"RegDate"=>date('Y-m-d'),"MaxCH"=>$maxch,"CouresRegData"=>json_encode($RegCoursesDet),"TotCH"=>$totch],"ID=".$dbo->SqlSafe($Param['CourseRegID']));
  //$reg = 1;
  if(is_array($reg)){
       
      //5. Generate New RegNo and Update as required
      $autoreg = AutoGenRegNo($Param['RegNo']);
      //Error(29," - ".$autoreg);
      //if error
       if(!is_array($autoreg) &&  $autoreg != "##"  &&  $autoreg != "####"){
          //remove course registered
          //$del = $dbo->Delete("coursereg_tb","ID=".$reg);
          if($autoreg == "#")$autoreg = "Reading School Details Failed";
          if($autoreg == "###")$autoreg = "Reading Student Details Failed";
          if($autoreg == "#####")$autoreg = "Global Update Failed";
          Notify($Param['RegNo'] , "We encourter error($autoreg) trying to generate your Official School Registration Number. Kindly report to the ICT Team", "ERROR: Registration Number Generation", "0");
         // Error(29, ", and Course Registration Reversed - ".$autoreg); 
      } 
      $AutoReg = [];
      //$autoreg = [$Param['RegNo']];
      if(is_array($autoreg)){
          $AutoReg = ["NewReg"=>$autoreg[0],"NRedirectData"=>"{Src:'{$__Root__}general/Slip.php?regno={$autoreg[0]}&folder=Form&SubDir=".urlencode($dbo->Config['SubDir'])."',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:30}"];
          $Param['RegNo'] = $autoreg[0];

          $studprog = $dbo->SelectFirstRow("studentinfo_tb","ProgID,SurName,FirstName,Phone","RegNo='{$Param['RegNo']}' OR JambNo='{$Param['RegNo']}'");
          if(is_array($studprog)){
              $sch = GetSchool();
              $title = "Official School Registration Number";
              $msg = "Hello, ".$studprog['SurName']." ".$studprog['FirstName']. ", your school Registration Number is {$Param['RegNo']}";
              //Send Message
              $sendmail = $dbo->SendSMS($sch['Abbr'],$msg,$studprog['Phone'],"234",$sch['OpUName'],$sch['OpUPassw'],$sch['OpSMSLive']=="FALSE"?false:true);
              $rstdet = explode("|",$sendmail);
              if(strtolower($rstdet[0]) == "success"){
              //$sendmail = TRUE;
              }
              //send notificaton
        Notify($Param['RegNo'] , $msg, $title, "0");
        $Param["__Notify__"] = ["Title" => $title, "Msg" => $msg];
          }

          
      }
      //$Param['CourseRegID'] = $reg;
      $ardata = "{Src:'{$__Root__}general/Slip.php?CourseRegID=".urlencode($Param['CourseRegID'])."&folder=Course&file=Slipi.php&SubDir=".urlencode($dbo->Config['SubDir'])."',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:4}";
  $Param["PrintData"] = $ardata;
  //$Param['RegNo'] = 
  //$rdata = "{Src:'Slip.php?regno={$Param['RegNo']}&folder=Form',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:30}";
  $Param["AutoReg"] = $AutoReg;
  //Error(35,json_encode($Param));
      return $Param;
  }else{
      Error(35);
  }
}

//view course reg details - R036
function LoadCourseReg($Param){
  //Error(40," -- ".$Param['TestData']);
  //Error(4,json_encode($Param));
  global $dbo;global $__Root__;
  if(isset($Param['CourseRegID'])){ //if the course reg ID is set
      $totch = 0;
      if(is_array($Param['CourseRegID']))$Param['CourseRegID']=$Param['CourseRegID'][0];
      
       //get the course settings
    $courseSettings = $dbo->SelectFirstRow("coursecontrol_tb");
    if(!is_array($courseSettings))Error(4);

    //get it from database
    $courseReg = $dbo->SelectFirstRow("coursereg_tb","","ID=".$Param['CourseRegID'],MYSQLI_ASSOC);
    if(!is_array($courseReg))Error(70,$courseReg);

    $getses = GetSchoolSession();

  
    $currSem = GetCurrentSem();

  
$allowEdit = [1];
    //check if course registration closed
    if($courseSettings['Status'] == "CLOSED" || $getses['SesID'] != $courseReg['SesID'] || $courseSettings['AutoRegStatus'] == "TRUE" || $currSem['Num'] != $courseReg['Sem'] ){
        $allowEdit = [];
    }
   
    
    $RtnArr = NULL;
    //get the courses registered
    $cregded = $courseReg['CouresRegData'];
    if(trim($cregded) != ""){//if it exist
       //convert to array
       $CoursesRegArr = json_decode($cregded,true);
       if(is_array($CoursesRegArr) && count($CoursesRegArr) > 0){ //if course registered details found
          $RtnArr = [];
          //loop trough the details and from the new return arr of courses
          foreach($CoursesRegArr as $CID=>$CDet){
              $CDet["CourseCode"] = strtoupper(trim($CDet["CourseCode"]));
              $CDet["Title"] = ucwords(trim($CDet["Title"]));
              $RtnArr[] = $CDet;
              $totch += (int)$CDet['CH'];
          }
       }
    }

    if(is_null($RtnArr)){ //if course detatils not found i.e registration is done on <v4
      $RtnArr = [];
       //get the courses registered string
       $CRegs = $courseReg['CoursesID'];
       if(trim($CRegs) != ""){
           //if the course reg details exist
           $CRegsArr = explode("~",$CRegs);
           if(count($CRegsArr) > 0){
               foreach($CRegsArr as $CID){
                   //get the course details
                   $cdet = $dbo->SelectFirstRow('course_tb',"","CourseID=".$CID,MYSQLI_ASSOC);
                   if(is_array($cdet)){
                      $cdet["CourseCode"] = strtoupper(trim($cdet["CourseCode"]));
                      $cdet["Title"] = ucwords(trim($cdet["Title"]));
                       $RtnArr[]=$cdet;
                       $totch += (int)$cdet['CH'];
                   }
               }
           }
       }

    }
   // $Param['CourseRegID'] = $reg;
      $ardata = "{Src:'{$__Root__}general/Slip.php?CourseRegID=".urlencode($Param['CourseRegID'])."&folder=Course&file=Slipi.php&SubDir=".urlencode($dbo->Config['SubDir'])."',PayperType:'A4',Orientation:'P',MarginTop:4,MarginBottom:4}";
      $ardatacard = "{Src:'{$__Root__}general/Slip.php?CourseRegID=".urlencode($Param['CourseRegID'])."&folder=CourseCard&file=Slipi.php&SubDir=".urlencode($dbo->Config['SubDir'])."',PayperType:'A5',Orientation:'L',MarginTop:4,MarginBottom:4}";
    //Error(0,json_encode());
  //$Param["PrintData"] = $ardata;
    return ["TotalCH"=>$totch,"TotalCourses"=>count($RtnArr),"Courses"=>$RtnArr,"RegNo"=>$courseReg['RegNo'],"LevelID"=>$courseReg['Lvl'],"SemesterID"=>$courseReg['Sem'],"SessionID"=>$courseReg['SesID'],"PrintData"=>$ardata,"PrintDataCard"=>$ardatacard,"AllowEdit"=>$allowEdit];
  }
  Error(0,' - Fetching Course Registration Details Failed');
}


//R037
function LoadCoursesRegHistory($Param){
  
  global $dbo;
  //session_start();
  HasLogin($Param);

  //get student details
  $studDet = $dbo->SelectFirstRow("studentinfo_tb","","RegNo='{$Param['LoginName']}' OR JambNo='{$Param['LoginName']}' LIMIT 1");
  if(!is_array($studDet))Error(8);
  
  //get all Courses Registered
  $coursesReg = $dbo->Select("coursereg_tb","","RegNo='{$studDet['RegNo']}' OR RegNo='{$studDet['JambNo']}' ORDER BY Lvl DESC, Sem DESC",MYSQLI_ASSOC);

  //get the student programme details

  
  if(!is_array($coursesReg))Error(4);
  if($coursesReg[1] < 1)Error(38);
  
  //loop and form the history array
  $HistArr = [];
  //for speed and optimization do an internal cache
  $LevelName = [];
  $SemesterName = [];
  $SessionName = [];
  while($courseRegi = $coursesReg[0]->fetch_assoc()){
      //get the course RegDetails
      if(!isset($LevelName[$courseRegi['Lvl']])){ //if not in cache
        //get it
        // $LevelName[$courseRegi['Lvl']] = GetStudentLevelName($courseRegi['Lvl'],$studDet['StudyID']);
        $LevelName[$courseRegi['Lvl']] =  GetLevelNameI($courseRegi['Lvl'],$studDet['StudyID'],$studDet['RegNo']);
      }
      if(!isset($SemesterName[$courseRegi['Sem']])){ //if not in cache
          //get it
          $SemesterName[$courseRegi['Sem']] = GetStudentSemesterName($courseRegi['Sem']);
        }
        if(!isset($SessionName[$courseRegi['SesID']])){ //if not in cache
          //get it
          $SessionName[$courseRegi['SesID']] = GetSessionName($courseRegi['SesID']);
        }

        $RegIDsArr = explode("~",$courseRegi['CoursesID']);
        $totcourse = count($RegIDsArr);

        //get the total ch
        $totch = $courseRegi['TotCH'];
        if($totch < 1 && $totcourse > 0){ //if courses exist and totch = 0, meaning it is <v4 registration
          //use the reg string
          foreach($RegIDsArr as $CID){
              $cdet = $dbo->SelectFirstRow('course_tb',"","CourseID=".$CID,MYSQLI_ASSOC);
                   if(is_array($cdet)){
                      $totch += $cdet['CH'];
                   }
          }
        }
        
$RegDate = date('d, M Y', strtotime($courseRegi['RegDate']));
if($RegDate == date('d, M Y'))$RegDate = "Today";
        $HistArr[] = ["SessionName"=>$SessionName[$courseRegi['SesID']],"LevelName"=>$LevelName[$courseRegi['Lvl']],"SemesterName"=>$SemesterName[$courseRegi['Sem']],"CourseRegID"=>$courseRegi['ID'],"RegDate"=>$RegDate,"TotalCourses"=>$totcourse,"TotalCH"=>$totch];

  }
  return $HistArr;
}

//R068
function GetStudentCoursesEdit($Param){
    
    global $dbo;
    //session_start();
    HasLogin($Param);

    //check if AutoCourseReg is disabled
    //get the course control detaisl
    $courseCntr = $dbo->SelectFirstRow("coursecontrol_tb");
    if($courseCntr['AutoRegStatus'] == "TRUE"){
        Error(40,'<br/><button class="bbwa-button w3-large" onclick="Application.Load({ApplyGID:3,AutoLoad:true,Home:true,Logout:false,Guest:true,OpenFrom:\'open-from-menu\'})" ><span class="mbri-credit-card"></span> &nbsp; Make Payment Now</button>');
    }

    $maxsem = 2;
    //get the maximum semester number
    $semma = $dbo->SelectFirstRow("semester_tb","count(ID)","Enable = 1");
    if(is_array($semma)){
        $maxsem = (int)$semma[0];
    }

    $studDet = $dbo->SelectFirstRow("studentinfo_tb","","RegNo='{$Param['LoginName']}' OR JambNo='{$Param['LoginName']}'");
            if(is_array($studDet)){
                $studDet['RegNo'] = (is_null($studDet['RegNo']) || trim($studDet['RegNo']) == "")?$studDet['JambNo']:$studDet['RegNo'];
    //get the course Registered
    $coursereg = $dbo->SelectFirstRow("coursereg_tb","*,Lvl as LevelID, Sem as SemesterID","ID=".$Param['CourseRegID'],MYSQLI_ASSOC);
            if(is_array($coursereg)){
                $getses = GetSchoolSession();

                //check if not same session
                if($getses['SesID'] != $coursereg['SesID'])Error(68);
              
                //check if result already uploaded
                $hasResult = $dbo->SelectFirstRow("result_tb","ID","RegNo='".$studDet['RegNo']."' AND Lvl=".$coursereg['Lvl']." AND Sem=".$coursereg['Sem']." AND SesID=".$coursereg['SesID']);
                if(is_array($hasResult))Error(69);
                
                /* if(!is_array($coursereg)){
                    $coursereg = [];
                    list($LevelID,$SemesterID) = GetStudentLevelSemesterWhenSchoolStart($studDet['RegNo']);
                    //$coursereg['LevelID'] = 1;
                    //$coursereg['SemesterID'] = 0;
                }else{
                    $LevelID = $coursereg['LevelID'];
                    $SemesterID = $coursereg['SemesterID'];
                    
                    $SemesterID++;
                    
                if($SemesterID > $maxsem){
                    $SemesterID = 1;
                    $LevelID++;
                } 
                } */
                
            //Error(4," - ".$LevelID." ; ".$SemesterID);
            //Error(4," - ".$LevelID." ; ".$SemesterID);
            //get the student progid
            $LevelID = $coursereg['LevelID'];
            $SemesterID = $coursereg['SemesterID'];
              $ProgID = $studDet['ProgID'];
              $RegisteredCourses = trim($studDet['CoursesID']) != ""?explode("~",$studDet['CoursesID']):[];
              //check payment
             /*  $PayDet = $dbo->SelectFirstRow("payhistory_tb","","(RegNo='".$studDet['RegNo']."' OR RegNo='".$studDet['JambNo']."') AND Lvl = {$LevelID} AND Sem >= $SemesterID AND SemPart > 0 AND ProgID=$ProgID AND PayID = {$courseCntr['PayID']}"); */
              $LevelName = GetStudentLevelName($LevelID,$studDet['StudyID'],$ProgID);
                  $semester = GetStudentSemesterName($SemesterID);
              // if(is_array($PayDet)){
                   //get current session
                   //$curses = GetSchoolSession();
                   $lvlses = $coursereg['SesID'];
                   $LevelIDOp = OperationalLevel($LevelID,$ProgID);
                  //get the courses
                  $Courses = $dbo->Select("course_tb","","DeptID=".$ProgID." AND Lvl=$LevelIDOp AND Sem=$SemesterID AND StartSesID <= $lvlses AND (EndSesID >= $lvlses OR EndSesID = 0) AND CourseStatus = 0");
                  if(!is_array($Courses))Error(32);
                  if($Courses[1] < 1)Error(33);
                  //get the max ch
                  $maxch = GetMaxCH($ProgID,$LevelID,$SemesterID);
                  $StudCourses = [];
                  $semclass = "semcourse";
                  $autoclass = "autoreg";
                  $llcclass = "llc";
                  $accCH = 0;
                  //loop through each student courses and add classes as required
                  while($indcourse = $Courses[0]->fetch_assoc()){
                    $indcourse['Class'] = $semclass;
                    $indcourse['CourseCode'] = strtoupper($indcourse['CourseCode']);
                    $indcourse['Title'] = ucwords($indcourse['Title']);
                    $indcourse['Checked'] = "";
                    if(in_array($indcourse['ID']."",$RegisteredCourses)){
                        $indcourse['Checked'] = "checked";
                    }
                    //get the ch
                    $accCH += (int)$indcourse['CH'];
                    if($accCH <= $maxch){
                        $indcourse['Class'] .= " ".$autoclass;
                    }
                    $StudCourses[] = $indcourse;
                  }

                  //if lower level courses is enabled
                  $LLC = [];
                  if($courseCntr['LowerLevel'] == 'TRUE'){
                    $LCoursese = [];
                    $lCourses = $dbo->Select("course_tb","","DeptID=".$ProgID." AND Lvl<$LevelIDOp AND Sem=$SemesterID  AND CourseStatus = 0 ORDER BY Lvl Desc");
                    if(!is_array($lCourses))Error(32);
                    if($lCourses[1] > 0){
                        $LevelSesArr = [];
                        while($lindcourse = $lCourses[0]->fetch_assoc()){
                            if(!isset($LevelSesArr[$lindcourse['Lvl']])){
                                //check if student register for course at the Lvl Sem
                                $courseregll = $dbo->SelectFirstRow("coursereg_tb","","RegNo='{$Param['LoginName']}' AND Lvl=".$lindcourse['Lvl']." AND Sem=".$lindcourse['Sem']);
                                if(is_array($courseregll)){ //if course registration exist for the lower level
                                //get the sesid
                                $LevelSesArr[$lindcourse['Lvl']] = (int)$courseregll["SesID"];
                                }else{
                                    //if the student does not register for the level which is abnormal
                                    //use the current session
                                    $LevelSesArr[$lindcourse['Lvl']] = $lvlses;  
                                }
                            }

                            //check if course not expired 
                            //StartSesID <= $lvlses AND (EndSesID >= $lvlses OR EndSesID = 0)
                            if((int)$lindcourse['StartSesID'] <= $LevelSesArr[$lindcourse['Lvl']] || ((int)$lindcourse['EndSesID'] >=  $LevelSesArr[$lindcourse['Lvl']] || (int)$lindcourse['EndSesID'] == 0)){
                                $lindcourse['Class'] = $llcclass;
                                $lindcourse['CourseCode'] = strtoupper($lindcourse['CourseCode']);
                                $lindcourse['Title'] = ucwords($lindcourse['Title']);
                            //get the ch
                           /*  $accCH += (int)$indcourse['CH'];
                            if($accCH <= $maxch){
                                $indcourse['Class'] .= " ".$autoclass;
                            } */
                            $LCoursese[] = $lindcourse;
                            }
                            
                            
                          }
                    }
                    if(count($LCoursese) > 0){
                        $LLC["Courses"] = $LCoursese;
                    }
                  }
                  
                  return ["SLC"=>["Courses"=>$StudCourses],"LLC"=>$LLC,"LevelName"=>$LevelName,"SemesterName"=>$semester,"LevelID"=>$LevelID,"SemesterID"=>$SemesterID,"ProgID"=>$studDet['ProgID'],"RegNo"=>$Param['LoginName'],"SemesterClass"=>$semclass,"AutoClass"=>$autoclass,"LLCClass"=>$llcclass,"CourseRegID"=>$Param['CourseRegID']];
              // }else{
                   //Make the page auto reload incase user make payment
                   /* $Param['PageClass'] = "ReloadOnPaid";
                   $Param["ErrorImage"] = "images/pages/notpaid.png";
                   Error(13,' <br/> <button class="bbwa-button w3-large" onclick="((event)=>{Application.Load({ApplyGID:3,AutoLoad:true,Home:true,Logout:false,Guest:true,OpenFrom:\'open-from-menu\'});event.stopPropagation();})(event)" ><span class="mbri-credit-card"></span> &nbsp; Make Payment Now</button>',$Param); */
                   /* Error(13,' <hr/>'.$LevelName.' / '.$semester.'<hr/><button class="bbwa-button w3-large" onclick="((event)=>{Application.Load({ApplyGID:3,AutoLoad:true,Home:true,Logout:false,Guest:true,OpenFrom:\'open-from-menu\'});event.stopPropagation();})(event)" ><span class="mbri-credit-card"></span> &nbsp; Make Payment Now</button>',$Param); */
               //}
            
               // return $coursereg;
            }else{
                Error(4,": Reading Student Registered Courses Failed ");
            }
        }else{
            Error(4,": Reading Student Details Failed");
        }
}

?>