<?php
/*

ALTER TABLE `modModule` DROP FOREIGN KEY `modModule.strCourseCode`;
ALTER TABLE `modModule` ADD CONSTRAINT `modModule.strCourseCode` FOREIGN KEY ( `refCourseID` ) REFERENCES `tblCourse` ( `CourseID` ) ON DELETE CASCADE ON UPDATE CASCADE

 *
 */

include_once("_nemo.list.cls.php");

class Module extends NemoList
{
   private $ID = 0;

   public function __construct($DataKey)
   {
      parent::__construct($DataKey);
   }

   public function getList($frCourseID=0)
   {
      global $SystemSettings;

      $Where = "";

      if($frCourseID != 0)
      {
         $sqlSelect = ", concat('<input type=checkbox value=\"checked\" id=xchkSelect name=\"chkSelect[',ModuleID,']\" >')  as 'Select'";
         $this->isSelectable = 0;
         $this->isSortable = 0;

         $Where .= " AND modModule.refCourseID = '$frCourseID'";
      }

      $this->ListSQL("
         SELECT modModule.ModuleID, modModule.strModuleName AS 'Module Name', modModule.intModuleNumber AS 'Number', modModule.dtReleaseDate AS 'Release Date', blnActive AS Active, strLastUser AS 'Last User', dtLastEdit AS 'Last Edit'$sqlSelect
         FROM modModule
         WHERE 1=1 $Where
         ORDER BY intModuleNumber, strModuleName",0,"module.php");

      //print_rr($this->Columns["Select"]);
      $this->Columns["Select"]->html->align = "center";
      $this->Columns["Select"]->html->class = "module_select";
      $this->Columns["Select"]->html->width = "1%";

      return $this->renderTable("Course Modules List");
   }



   public static function ReleaseIWPCPDPoints($ModuleID)
   {
      //20110831 - removed Project Mark, renamed Project to Portfolio - pj
      global $xdb, $TR, $BR, $SP, $SystemSettings;

      //INI


      $intPercentage = 0;
      //check if this is the only module in the course
      $row = $xdb->getRowSQL("SELECT count(modAssignment.AssignmentID) as 'intAssignmentCount'
                           FROM modAssignment INNER JOIN (tblCourse INNER JOIN modModule ON tblCourse.CourseID = modModule.refCourseID) ON modAssignment.refModuleID = modModule.ModuleID
                           WHERE (((tblCourse.CourseID)='612') AND ((modAssignment.strType)='Assignment')) AND ModuleID = '$ModuleID'" , 0);
      if($row->intAssignmentCount > 1)
      {
         $Where = " ";
         //$Where = "AND ((modAssignment.AssignmentID) Not In ('$strCurrentAssignment')) ";
      }

      //20190408 - retrieving intAssignmentCount from wrong result - Rachel
      $intAssignmentCount = $row->intAssignmentCount;

      //get all assignments (except the current one) for this course
      $rst = $xdb->doQuery("SELECT tblCourse.CourseID, modAssignment.refModuleID, modAssignment.AssignmentID, tblCourse.intPassRate
                           FROM modAssignment INNER JOIN (tblCourse INNER JOIN modModule ON tblCourse.CourseID = modModule.refCourseID) ON modAssignment.refModuleID = modModule.ModuleID
                           WHERE (((tblCourse.CourseID)='612') AND ((modAssignment.strType)='Assignment')) AND ModuleID = '$ModuleID' $Where", 0);
      
      $intPercentage = 0;
      $CompletedModCount = 0;

      while($row = $xdb->fetch($rst))
      {
         
          

         //Select from the assessment by module, assignmentID, and learner
         // $rowAssessment = $xdb->getRowSQL("
         //    SELECT percAssignmentMark FROM modAssessment 
         //    WHERE refModuleID = '$row->refModuleID' AND refAssignmentID = '$row->AssignmentID' AND refLearnerID = '$LearnerID'", 0);

         // $rstAssessment = $xdb->doQuery("
         //    SELECT tblLearner.*, percAssignmentMark FROM modAssessment INNER JOIN tblLearner ON modAssessment.refLearnerID = tblLearner.LearnerID 
         //    WHERE refModuleID = '$row->refModuleID' AND refAssignmentID = '$row->AssignmentID'", 1);


      // $intRow = 0;
      $rstAss = $xdb->doQuery("SELECT tblLearner.LearnerID, tblLearner.strLearner, tblLearner.strEmail, modAssessment.*
                     FROM modModule INNER JOIN (tblLicence INNER JOIN (modAssessment INNER JOIN tblLearner ON modAssessment.refLearnerID = tblLearner.LearnerID) ON tblLicence.refLearnerID = tblLearner.LearnerID) ON (modModule.refCourseID = tblLicence.refCourseID) AND (modModule.ModuleID = modAssessment.refModuleID)
                     WHERE modAssessment.refAssignmentID = '$row->AssignmentID' AND modAssessment.refModuleID = '$row->refModuleID' AND tblLicence.strStatus='Active' AND tblLearner.blnActive = 1
                     GROUP BY LearnerID, AssessmentID
                     ORDER BY tblLearner.strLearner", 0);

      while($rowLearner = $xdb->fetch($rstAss)){

         if($rowLearner)
         {  
            //20190415 - add completed module counter and compare to total assignments in the course - jacques
            $arrLearnerAssessment[$rowLearner->LearnerID]["strName"] = $rowLearner->strLearner;
            $arrLearnerAssessment[$rowLearner->LearnerID]["LearnerID"] = $rowLearner->LearnerID;

            $arrLearnerAssessment[$rowLearner->LearnerID]["strEmail"] = $rowLearner->strEmail;
            $arrLearnerAssessment[$rowLearner->LearnerID]["CompletedModCount"] += 1;

            $arrLearnerAssessment[$rowLearner->LearnerID]["intPercentage"] += $rowLearner->percAssignmentMark / $intAssignmentCount;

            //20190408 - retrieving intAssignmentCount from wrong result - Rachel
            // $intPercentage += $rowAssessment->percAssignmentMark / $row->intAssignmentCount;
            // $intPercentage += $rowLearner->percAssignmentMark / $intAssignmentCount;
         }
         $intPassRate = $row->intPassRate;
      }

         

// vd($intPassRate);
      }

// print_rr($arrLearnerAssessment);
      // print_rr("CompletedModCount: ".$CompletedModCount);
      // print_rr("intAssignmentCount: ".$intAssignmentCount);
      // print_rr("intPercentage: ".$intPercentage);
      // print_rr("intPassRate: ".$intPassRate);

      $intRow = 0;
      foreach ($arrLearnerAssessment as $key => $rowLearnerAssessment) {
         // print_rr($rowLearnerAssessment);
                  //ini
         $intRow ++;

         if($rowLearnerAssessment["intPercentage"] >= $intPassRate  && $rowLearnerAssessment["CompletedModCount"] == $intAssignmentCount){
            $strEmail = $rowLearnerAssessment["strEmail"];
            $LearnerID = $rowLearnerAssessment["LearnerID"];

            $trList .="
            <tr comment='main row'>
               <td align='right' width='1%'>$intRow</td>
               <td align='left' >
                  <a href='learner.php?Action=Edit&LearnerID=".$rowLearnerAssessment["LearnerID"]."' target=_blank>".$rowLearnerAssessment["strName"]."</a></td>
               <td align='left'>".$rowLearnerAssessment["strEmail"]."</td>
               <td align='left'>".round($rowLearnerAssessment["intPercentage"])."</td>`
               <td align='center' ><input type=checkbox name='chkGrantCPD[$LearnerID]' id='chkSelect' value=\"$strEmail\" /></td>
            </tr>";
         }
      }
      
   

      //,'chkModerated','chkInseta','dblMark1Project','dblMark2Project'
      $output = "
      <table cellspacing=1 cellpadding=0 border=0 width=100% class='tblNemoList'>
         <caption>Release IWP CPD Points</caption>
         <tr>
            <th width='1%'>#</th>
            <th >Learner</th>
            <th >Email Address</th>
            <th >% Marks For Module</th>
            <th width='1%' class='linkbutton2 textColour' onclick='jsToggleSelect();' >Allocate CPD Points</th>
         </tr>
         $trList
      </table>
      $BR
      ";

      return $output;
   }

   public function getCourseTypeModuleList($frCourseTypeID=0)
   {
      global $SystemSettings;

      $Where = "";

      $this->ListSQL("
         SELECT tblCourseTypeModule.CourseTypeModuleID, tblCourseTypeModule.strModuleName AS 'Module Name', tblCourseTypeModule.intModuleNumber AS 'Number', tblCourseTypeModule.strDefaultReleaseSchedule AS 'Default Release Schedule', tblCourseTypeModule.blnActive AS Active, tblCourseTypeModule.strLastUser AS 'Last User', tblCourseTypeModule.dtLastEdit AS 'Last Edit'
         FROM tblCourseTypeModule
         WHERE tblCourseTypeModule.refCourseTypeID = $frCourseTypeID
         ORDER BY intModuleNumber, strModuleName;",0,"course.type.module.php");
      return $this->renderTable("Default Modules List");
   }

   public static function Save(&$ModuleID)
   {
      global $xdb;
      $db = new NemoDatabase("modModule", $ModuleID, null, 0);

      // print_rr($_POST);

      $message = "";
      foreach ($_POST["chkGrantCPD"] as $LearnerID => $strEmail) {

         $rowLearner = $xdb->getRowSQL("SELECT * FROM tblLearner WHERE LearnerID = '$LearnerID'",0);

         $rowModule = $xdb->getRowSQL("SELECT * FROM modModule WHERE ModuleID = '$ModuleID'",0);
  
         grantModuleCPDPoints($LearnerID, $rowModule->refCourseID, $ModuleID, $rowLearner->strName . " ".$rowLearner->strSurname, "", $strEmail, "IWP CPD Points Module");

         $message = " CPD Points granted";
      }

      $db->SetValues($_POST);

      $db->Fields[strLastUser] = $_SESSION['USER']->USERNAME;

      $result = $db->Save();

      if($ModuleID == 0) $ModuleID = $db->ID[ModuleID];

      if($result->Error == 1)
         return $result->Message;
      else
         return "Details Saved. ". $message;
   }

   public static function Delete($chkSelect)
   {
      global $xdb;
      //print_rr($chkSelect);
      if(count($chkSelect) > 0){
      foreach($chkSelect as $key => $value)
      {
         $xdb->doQuery("DELETE FROM modModule WHERE ModuleID = ". $xdb->qs($key));
      }
         return "Records Deleted. ";
      }else{
         return "No Records Selected. ";
      }
   }

   public static function SaveCTM(&$CourseTypeModuleID)
   {
      $db = new NemoDatabase("tblCourseTypeModule", $CourseTypeModuleID, null, 0);

      $db->SetValues($_POST);

      $db->Fields[strLastUser] = $_SESSION['USER']->USERNAME;

      $result = $db->Save();

      if($CourseTypeModuleID == 0) $CourseTypeModuleID = $db->ID[CourseTypeModuleID];

      if($result->Error == 1)
         return $result->Message;
      else
         return "Details Saved. ";
   }

   public static function DeleteCTM($chkSelect)
   {
      global $xdb;
      //print_rr($chkSelect);
      if(count($chkSelect) > 0){
      foreach($chkSelect as $key => $value)
      {
         $xdb->doQuery("DELETE FROM tblCourseTypeModule WHERE CourseTypeModuleID = ". $xdb->qs($key));
      }
         return "Records Deleted. ";
      }
   }

   public static function DeleteChildren($chkSelect)
   {
      global $xdb;
      if(count($chkSelect) > 0){

         $strUniqueID = "'". implode("','", array_keys($chkSelect)) ."'";

         $xdb->doQuery("DELETE FROM modVideo WHERE VideoID IN ($strUniqueID)");
         $xdb->doQuery("DELETE FROM modNote WHERE NoteID IN ($strUniqueID)");
         $xdb->doQuery("DELETE FROM modPractical WHERE PracticalID IN ($strUniqueID)");
         $xdb->doQuery("DELETE FROM modAssignment WHERE AssignmentID IN ($strUniqueID)");

         $xdb->doQuery("DELETE FROM modMilestone WHERE UniqueID IN ($strUniqueID)");
         $xdb->doQuery("DELETE FROM modDownloadContent WHERE UniqueID IN ($strUniqueID)");

         return "Records Deleted. ";
      }
   }
}
?>
