<?php
/*

ALTER TABLE `modAssignment` DROP FOREIGN KEY `modAssignment.strModuleName`;
ALTER TABLE `modAssignment` ADD CONSTRAINT `modAssignment.strModuleName` FOREIGN KEY ( `refModuleID` ) REFERENCES `modModule` ( `ModuleID` ) ON DELETE CASCADE ON UPDATE CASCADE

NOTE UID = CourseCode + ASS + Obf = "ABCNOT123456"
 *
 * 20120827 - added feedback report - pj
 * 20180912 - Added Assessment Evaluator Upload - Rachel
 */

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

class Assignment extends NemoList
{
   private $ID = "";

   public function __construct($DataKey)
   {

      parent::__construct($DataKey);

      $this->isSelectable = 1;
      $this->isPageable =
      $this->isSortable = 0;
   }

   public function getList($frModuleID=0, $blnQuiz=0, $frStatus="")
   {
      global $SystemSettings;

      $Where = "";

      if($blnQuiz == 1){
         $Where .= " AND modAssignment.strType IN ('Feedback Survey','Quiz')";
         $Title = "Quiz / Feedback Survey";
      }
      else{
         $Where .= " AND modAssignment.strType NOT IN ('Feedback Survey','Quiz')";
         $Title = "Assignment";
      }

      if($frModuleID != 0)
      {
         $Where .= " AND modAssignment.refModuleID = '$frModuleID'";
      }
      if($frStatus != "")
      {
         $WhereS .= " AND modMilestone.strStatus='$frStatus'";
      }
      $this->ListSQL("
         SELECT AssignmentID, strAssignment AS Title, (SELECT COUNT(MilestoneID) FROM modMilestone WHERE UniqueID = AssignmentID $WhereS ) AS 'No $frStatus', CASE WHEN Count(modDownloadContent.DownloadID) > 0 THEN 'Yes' ELSE 'No' END AS 'Downloadable Content', modAssignment.blnActive AS Active, modAssignment.strLastUser AS 'Last User', modAssignment.dtLastEdit AS 'Last Edit'
         FROM modDownloadContent RIGHT JOIN modAssignment ON modDownloadContent.UniqueID = AssignmentID
         WHERE 1=1 $Where
         GROUP BY AssignmentID, strAssignment, modAssignment.blnActive, modAssignment.strLastUser, modAssignment.dtLastEdit
         ORDER BY intOrder ASC, strAssignment",0,"mod.assignment.php");
      return $this->renderTable("$Title List");

   }

   public static function Save(&$AssignmentID, $strUniqueID_Prefix)
   {
      //note: the UID prefic needs to be passed to the db.save(), else it will still gen a 6digit UID. UID = CourseTypeCode + Module Object Type + Obf, e.g. "ABCNOT123456"
      $db = new NemoDatabase("modAssignment", $AssignmentID, array("refModuleID","strAssignment"), 0); //set Uninque restraint @ refModuleID & strAssignment
//print_rr($db->Fields);
      $db->SetValues($_POST);
//print_rr($db->Fields); die;
      $db->Fields[strLastUser] = ($_SESSION['CoachName'] ? $_SESSION['CoachName'] : $_SESSION['USER']->USERNAME);

      $result = $db->Save(0,0,$strUniqueID_Prefix);
//print_rr($result); die;
//print_rr($db);
      if($AssignmentID == "") $AssignmentID = $db->ID[AssignmentID];

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

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

   public static function CheckAssessments($AssignmentID)
   {
      global $xdb;

      $xdb->doQuery("
         INSERT IGNORE INTO modAssessment ( refModuleID, refLearnerID, refAssignmentID, percAssignmentMark, strLastUser )
         SELECT modAssignment.refModuleID, tblLearner.LearnerID, modAssignment.AssignmentID, Null AS percAssignmentMark, 'System' AS strLastUser
         FROM (modAssignment INNER JOIN modModule ON modAssignment.refModuleID = modModule.ModuleID) INNER JOIN (tblLicence INNER JOIN tblLearner ON tblLicence.refLearnerID = tblLearner.LearnerID) ON modModule.refCourseID = tblLicence.refCourseID
         GROUP BY modAssignment.refModuleID, tblLearner.LearnerID, modAssignment.AssignmentID, Null, 'System'
         HAVING modAssignment.AssignmentID=". $xdb->qs($AssignmentID));

      if($xdb->Rows)
         return $xdb->Rows ." Assessment(s) added. ";
      else
         return "";

   }

   public static function GetAssessments($AssignmentID, $strType="Upload")
   {
      //20110831 - removed Project Mark, renamed Project to Portfolio - pj
      global $xdb, $TR, $BR, $SP, $SystemSettings;
      //INI
      $required = $SystemSettings[imgRequired];
      $arrChecked = array(0 => "", 1 => "checked");
      $strToday = date("'Y-m-d'");
      $intRow = 0;

      //LOAD
      $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 = ". $xdb->qs($AssignmentID) ." AND tblLicence.strStatus='Active' AND tblLearner.blnActive = 1
                     GROUP BY LearnerID, AssessmentID
                     ORDER BY tblLearner.strLearner");
      $intAss = $xdb->Rows;

      $i = 1;
      while($rowAss = $xdb->fetch_object($rstAss))
      {
         //print_rr($rowAss);
         //ini
         $intRow ++;


         if($rowAss->dtAssessment == "0000-00-00") $rowAss->dtAssessment = "";
         if($rowAss->dtUpload == "0000-00-00") $rowAss->dtUpload = "";

         //load
         $AssID = $rowAss->AssessmentID;

         if($rowAss->dtAssessment == ""){
            $disabled = "disabled";
            $checked = "";
         }else{
            $checked = "checked";
            $disabled = "";
         }

         //chk
         $chkAssessment = "<input type='checkbox' name='chkAssessment[$AssID]' id='chkAssessment[$AssID]' value='checked' $checked onClick=\"enableControls($AssID, this.checked); setDate('dtAssessed[$AssID]', this.checked);\" />";

         //dt
         //NOTE: dtAssessed else it conflicts with tblEvent.dtAssessment
         $dtAssessment = "<input name='dtAssessed[$AssID]' id='dtAssessed[$AssID]' value=\"$rowAss->dtAssessment\" type='text' class='controlText controlNumeric controlDateTime datePicker' $disabled />"; // readonly='readonly'

         //dbl
         //$dblMark1Project = "<input type=text name='dblMark1Project[$AssID]' id='dblMark1Project[$AssID]' value=\"$rowAss->dblMark1Project\" class='controlText controlNumeric controlNarrow' onblur='removeAlpha(this);' $disabled />";
         $percAssignmentMark = "<input type=text name='percAssignmentMark[$AssID]' id='percAssignmentMark[$AssID]' value=\"$rowAss->percAssignmentMark\" class='controlText controlNumeric controlNarrow' onblur='removeAlpha(this);' />";

         $txtComments = "<textarea name='txtComments[$AssID]' id='txtComments[$AssID]' class='controlText controlWideMax' style='height: 90px;' >$rowAss->txtComments</textarea>";
         $txtNotes = "<textarea name='txtANotes[$AssID]' id='txtANotes[$AssID]' class='controlText controlWideMax' style='height: 90px;'>$rowAss->txtNotes</textarea>";


         //20180912 - Added Assessment Evaluator Upload - Rachel
         $strEvaluatorFile = "    
               <input type='file' name='strEvaluatorFile[$AssID]' id='strEvaluatorFile[$AssID]' class='controlText'/>
               <a  style='float: center;display: block;' href='". $SystemSettings[DownloadableContentDirAdmin] ."$rowAss->strEvaluatorFile' target=_blank>$rowAss->strEvaluatorFile</a>
               <span style='float: center;display: block;'>".($rowAss->dtEvaluatorUpload == "0000-00-00" ? "" : $rowAss->dtEvaluatorUpload)."</span>";


         $trList .="
         <tr comment='main row'>
            <td align='right' width='1%'>$intRow</td>
            <td align='left' >
               <a href='learner.php?Action=Edit&LearnerID=$rowAss->LearnerID' target=_blank>$rowAss->strLearner</a></td>
            <td align='center'>$chkAssessment</td>
            <td align='left'>$dtAssessment</td>
            <td align='left'>$percAssignmentMark</td>
            <td align='center' ><a style='float: center;display: block;' href='". $SystemSettings[DownloadableContentDirAdmin] ."$rowAss->strFilename' target=_blank>$rowAss->strFilename</a> <span style='float: center;display: block;'>$rowAss->dtUpload</span></td>
            <td align='center' > $strEvaluatorFile </td>
            <td align='left' >$txtComments</td>
            <td align='left' >$txtNotes</td>
            <td align='center' >$rowAss->strLastUser $rowAss->dtLastEdit</td>
            <td align='center' ><input type=checkbox name='chkSelect[$AssID]' id='chkSelect' value=\"$rowAss->strEmail\" /></td>
         </tr>";
       //<!-- <td align='left'>$dblMark2Project</td> --!>

      }
      //,'chkModerated','chkInseta','dblMark1Project','dblMark2Project'
      $output = js("
         arrControls = new Array('dtAssessed'); //,'percAssignmentMark','txtComments');
      function enableControls(AssID, blnEnabled)
      {
         for(var i in arrControls)
         {
            d(arrControls[i] +'['+ AssID +']').disabled = !blnEnabled;
         }
      }
      function setDate(id, blnChecked, blnAssessmentDate)
      {
         var dt = d(id);
         if(blnChecked == true &&  dt.value == '')  dt.value = $strToday;

      }

      ")."
      <table cellspacing=1 cellpadding=0 border=0 width=100% class='tblNemoList'>
         <caption>Learner Assessments</caption>
         <tr>
            <th width='1%'>#</th>
            <th >Learner</th>
            <th >Assessed</th>
            <th >Date Assessed</th>
            <th >% Marks</th>
            <th >Learner Submisson</th>
            <th >Evaluator Assessment</th>
            <th width='20%'>Comments</th>
            <th width='20%' >Notes</th>
            <th width='1%' >Last User/Edit</th>
            <th width='1%' class='linkbutton2 textColour' onclick='jsToggleSelect();' >Select</th>
         </tr>
         $trList
      </table>
      $BR
      Notes:
      <li>Comments are displayed to each learner on their module page.</li>
      <li>Notes are for internal use only, i.e. the learner never see them.</li>
      <li>Once the Assessment Date has been entered, the marks will be released and be available to the learners. Unchecking the Assessed checkbox will retract the results.</li>

      ";

      return $output;
   }

   public static function GetFeedback($AssignmentID)
   {//20120827 - added feedback report - pj
      global $xdb, $TR, $BR, $SP, $SystemSettings;


      //get total number of active learners

      //foreace survey question, get options and #responses
         //get comments


      $rowCourse = $xdb->getRowSQL("
         SELECT count(LearnerID) as intLearners,  strCourse, strCourseCode, dtDueDate
         FROM (
            SELECT tblLearner.LearnerID, tblCourse.strCourse, tblCourse.strCourseCode, modAssignment.dtDueDate
            FROM modAssignment INNER JOIN (modModule INNER JOIN ((tblLicence INNER JOIN tblLearner ON tblLicence.refLearnerID = tblLearner.LearnerID) INNER JOIN tblCourse ON tblLicence.refCourseID = tblCourse.CourseID) ON modModule.refCourseID = tblCourse.CourseID) ON modAssignment.refModuleID = modModule.ModuleID
            WHERE (((tblLicence.strStatus)='Active'))
            GROUP BY modAssignment.AssignmentID, tblLearner.LearnerID, tblCourse.strCourse, tblCourse.strCourseCode, modAssignment.dtDueDate
            HAVING (((modAssignment.AssignmentID)=\"$AssignmentID\"))
         ) as tblCourseLearner
         GROUP BY strCourse, strCourseCode, dtDueDate",0);
      $intLearners = $rowCourse->intLearners;

      if($intLearners == 0)
         return "";

      $rst = $xdb->doQuery("
         SELECT surResponse.AssignmentID, surResponse.txtComment, surResponse.LearnerID, surResponse.QuestionID, tblLearner.strDisplayName
         FROM surResponse INNER JOIN tblLearner ON surResponse.LearnerID = tblLearner.LearnerID
         WHERE (((surResponse.AssignmentID)=\"$AssignmentID\") AND ((surResponse.txtComment) <> '' And Not (surResponse.txtComment) Is Null))
         ORDER BY tblLearner.strDisplayName",0);
      while($row = $xdb->fetch_object($rst))
      {
         $arrComments[$row->QuestionID] .= "
            <tr>
               <td width='25px'></td>
               <td colspan='3' >$row->strDisplayName - ". str_replace(chr(13),"", $row->txtComment) ."</td>
            </tr>";
      }//print_rr($arrComments);

      $rst = $xdb->doQuery("
         SELECT surQuestion.QuestionID, surOption.OptionID, surQuestion.intOrder AS qOrder, surOption.intOrder AS oOrder, surQuestion.strQuestion, surOption.strOption, Count(surResponse.LearnerID) AS intResponse
         FROM surResponse RIGHT JOIN (surOption RIGHT JOIN surQuestion ON surOption.refQuestionID = surQuestion.QuestionID) ON surResponse.OptionID = surOption.OptionID
         WHERE surQuestion.blnActive=1 AND surQuestion.refAssignmentID=\"$AssignmentID\"
         GROUP BY surQuestion.QuestionID, surOption.OptionID, surQuestion.intOrder, surOption.intOrder, surQuestion.strQuestion, surOption.strOption
         ORDER BY surQuestion.intOrder, surOption.intOrder",0);

      while($row = $xdb->fetch_object($rst))
      {
         $arrQuestions[$row->QuestionID]->Question = $row;
         if($row->OptionID > 0 )
            $arrQuestions[$row->QuestionID]->Options[$row->OptionID] = $row;
      }//print_rr($arrQuestions);

      foreach($arrQuestions AS $QID => $arrOptions)
      {

         if(isset($arrOptions->Options)){
         $Output .= "
            $TR
            <tr>
               <td colspan='2' align='left'><b>Q". $arrOptions->Question->qOrder ." - ". $arrOptions->Question->strQuestion ."</b></td>
               <td colspan='2' align='center'><b>Responses</b></td></tr>";


            foreach($arrOptions->Options AS $OID => $row)
            {
               $Output .=
               "<tr>
                  <td ></td>
                  <td >$row->strOption</td>
                  <td align='right'>". @number_format($row->intResponse,0) ."</td>
                  <td align='right'>". @number_format(round($row->intResponse/$intLearners*100,1),1) ." %</td>
               </tr>";
            }
         }else{
         $Output .= "
            $TR
            <tr>
               <td colspan='4' align='left'><b>Q". $arrOptions->Question->qOrder ." - ". $arrOptions->Question->strQuestion ."</b></td>
            </tr>";
         }

         if(isset($arrComments[$QID]))
         {
            $Output .= "
            $TR
            <tr><td colspan='4'><u>Comments</u>:</td></tr>"
            . $arrComments[$QID];
         }
      }

      return "
         <table cellspacing=1 cellpadding=0 border=0 width='850px' class='tblNemoList'>
            <caption><b style='font-size:26px'>$rowCourse->strCourse $rowCourse->strCode Course Feedback Report</b></caption>
               <col name='A' style='width: 25px;'/>
               <col name='B' style='width: 700px;' />
               <col name='C' style='width: 35px;' />
               <col name='D' style='width: 65px;'/>
            <tr><th colspan='4' align='left'>Closing Date: $rowCourse->dtDueDate</th></tr>

            $Output
         </table>";

   }

   public static function SaveAssessment()
   {//print_rr($_POST); print_rr($_FILES); die("jkhc");

      global $SystemSettings;

      if(is_array($_POST[txtANotes]))
      {
         //ini
         $chkAssessment = $_POST[chkAssessment];
         $dtAssessed = $_POST[dtAssessed];
         $percAssignmentMark = $_POST[percAssignmentMark];
         $txtNotes = $_POST[txtANotes];
         $txtComments = $_POST[txtComments];

         foreach($txtNotes as $AssessmentID => $value)
         {
            $db = new NemoDatabase("modAssessment", $AssessmentID, null, 0);

            //statuses
            if($chkAssessment[$AssessmentID] == "")
            {
               //$db->Fields[percAssignmentMark] = "NULL";
               $db->Fields[dtAssessment] = "NULL";
            }else{
               $db->Fields[percAssignmentMark] = $percAssignmentMark[$AssessmentID];
               $db->Fields[dtAssessment] = $dtAssessed[$AssessmentID];
               $db->doQuery("UPDATE modMilestone SET strStatus = 'Completed', strLastUser = '".($_SESSION['CoachName'] ? $_SESSION['CoachName'] : $_SESSION[USER]->USERNAME)."' WHERE UniqueID = '". $db->Fields[refAssignmentID] ."' AND refLearnerID = ". $db->Fields[refLearnerID]);
            }

            //str

            $db->Fields[txtComments] = $txtComments[$AssessmentID];
            $db->Fields[txtNotes] = $txtNotes[$AssessmentID];
            $db->Fields[strLastUser] = ($_SESSION['CoachName'] ? $_SESSION['CoachName'] : $_SESSION['USER']->USERNAME);

            $result = $db->Save(0,0);
            $intSave ++;

            //$db->doQuery("UPDATE modAssessment
            //         SET dtAssessment = CASE WHEN dtAssessment = '0000-00-00' THEN NULL ELSE dtAssessment END,
            //             dtReAssessment = CASE WHEN dtReAssessment = '0000-00-00' THEN NULL ELSE dtReAssessment END,
            //             dtModerated = CASE WHEN dtModerated = '0000-00-00' THEN NULL ELSE dtModerated END,
            //             dtInseta = CASE WHEN dtInseta = '0000-00-00' THEN NULL ELSE dtInseta END,
            //             dtNLRD = CASE WHEN dtNLRD = '0000-00-00' THEN NULL ELSE dtNLRD END,
            //             dtUpload = CASE WHEN dtUpload = '0000-00-00' THEN NULL ELSE dtUpload END
            //         WHERE AssessmentID = $AssessmentID"); //post save clean: the db.Save() doesn't allow for nulls
         }
      }

      //20180912 - Added Assessment Evaluator Upload - Rachel
      if(is_array($_FILES['strEvaluatorFile']))
      {

         $strEvaluatorFile = $_FILES[strEvaluatorFile];

         foreach($strEvaluatorFile[name] as $AssessmentID => $value)
         { 
            if($strEvaluatorFile["name"][$AssessmentID] != "")
            {
               $db = new NemoDatabase("modAssessment", $AssessmentID, null, 0);
               $strOldFilename = $db->getRowSQL("SELECT * FROM modAssessment WHERE AssessmentID = ". $db->qs($AssessmentID))->strEvaluatorFile; 

               $db->Fields["strEvaluatorFile"] =
               $strFileName = $AssessmentID."_". $strEvaluatorFile["name"][$AssessmentID];
               $db->Fields["dtEvaluatorUpload"] = date("Y-m-d");
               $db->Fields[strLastUser] = ($_SESSION['CoachName'] ? $_SESSION['CoachName'] : $_SESSION['USER']->USERNAME);


               $strPath = $SystemSettings[DownloadableContentDirAdmin];

               chmod($strEvaluatorFile["tmp_name"][$AssessmentID] , 0777);
               if(move_uploaded_file($strEvaluatorFile["tmp_name"][$AssessmentID] , $strPath . $strFileName))
               {
                  if($strOldFilename != "" && $strOldFilename != $strFileName)
                  {
                     unlink($strPath.$strOldFilename);
                  }
                     
                  $message = "New File Uploaded. ";
               }

               $result = $db->Save(0,0);
            }


         }

      }
      if($intSave >> 0)
         return "$intSave Learner Assessment(s) saved. ";
   }


}
?>
