<?php
/*

ALTER TABLE `surQuestion` drop FOREIGN KEY `surQuestion.AssignmentID`;
ALTER TABLE `surQuestion` ADD CONSTRAINT `surQuestion.AssignmentID` FOREIGN KEY (`refAssignmentID`) REFERENCES `modAssignment` (`AssignmentID`) ON UPDATE CASCADE ON DELETE CASCADE;
//20181205 - Added Order By to Question Options - Rachel

 *
 *
 *
*/
include_once("_nemo.list.cls.php");

class Question extends NemoList
{
   private $ID = 0;
   public $Filters;

   public function __construct($DataKey)
   {//filter definitions MUST be before parent.construct()
      $this->Filters[frSearch]->tag = "input";
      $this->Filters[frSearch]->html->value = "";
      $this->Filters[frSearch]->html->type = "text";
      $this->Filters[frSearch]->html->class = "controlText";

      parent::__construct($DataKey);
   }

   public function getList($frAssignmentID)
   {
      //ini
      $Where = "";
      $Having = "";
      //sql where
   if($frAssignmentID != "")
   {
      $Where = " AND surQuestion.refAssignmentID = ". $this->db->qs($frAssignmentID);
      $this->isPageable =
      $this->isSortable = 0;
   }else{
      if($this->Filters[frSearch]->html->value != "")
      {
         $like = "LIKE(". $this->db->qs("%".$this->Filters[frSearch]->html->value."%") .")";
         $Where .= " AND (surQuestion.strQuestion $like OR surQuestion.QuestionID $like OR surQuestion.intOrder $like)";
      }

   }

      $this->ListSQL("
         SELECT QuestionID, strSection AS 'Section', strQuestionHeading AS Title, intOrder AS 'Order', blnMandatory AS Mandatory, blnActive AS Active, strLastUser as 'Last User', dtLastEdit as 'Last Edit'
         FROM surQuestion
         WHERE 1=1 $Where
         ORDER BY cast(intOrder as unsigned), strQuestionHeading", 0, "mod.question.php");// AND NOT (surSurveyResponse.OptionID = 0 OR surSurveyResponse.QuestionID is NULL)
      return $this->renderTable("Question List*"). "<i>*Ordered by Section, Order, Title</i>";
   }

   public function getListWI($frAssignmentID)
   {
      //ini
      $Where = "";
      $Having = "";
      //sql where
   if($frAssignmentID != "")
   {
      $Where = " AND surQuestion.refAssignmentID = ". $this->db->qs($frAssignmentID);
      $this->isPageable =
      $this->isSortable = 0;
   }else{
      if($this->Filters[frSearch]->html->value != "")
      {
         $like = "LIKE(". $this->db->qs("%".$this->Filters[frSearch]->html->value."%") .")";
         $Where .= " AND (surQuestion.strQuestion $like OR surQuestion.QuestionID $like OR surQuestion.intOrder $like)";
      }

   }

      $this->ListSQL("
         SELECT QuestionID, strSection AS 'Section', strQuestionHeading AS Title, intOrder AS 'Order', blnMandatory AS Mandatory, blnActive AS Active, strLastUser as 'Last User', dtLastEdit as 'Last Edit'
         FROM surQuestion
         WHERE 1=1 $Where
         ORDER BY strSection, intOrder, strQuestionHeading", 0, "mod.question.php", "Edit2");// AND NOT (surSurveyResponse.OptionID = 0 OR surSurveyResponse.QuestionID is NULL)
      return $this->renderTable("Question List*"). "<i>*Ordered by Section, Order, Title</i>";
   }

   public function getOptionList($refQuestionID)
   {
      global $xdb, $BR;
      $strDetail = "";

      $xdb->doQuery("SELECT * FROM surOption WHERE refQuestionID = ". $xdb->qs($refQuestionID) ." ORDER BY intOrder, strOption",0);
      while($row = $xdb->fetch())
      {
         if($row->blnActive == 1)
            $blnActive = " checked ";
         else
            $blnActive = "";
         $strDetail .= "
         <tr>
            <td><input class='controlText controlWideMax' type='text' name='strOption[".$row->OptionID."]' value=\"".$row->strOption."\"></td>
            <td><input class='controlText controlNumeric' type='text' name='intOptionOrder[".$row->OptionID."]' value=\"".$row->intOrder."\" onblur='removeAlpha(this);'></td>
            <td><input class='controlText controlNumeric' type='text' name='intWeighting[".$row->OptionID."]' value=\"".$row->intWeighting."\" onblur='removeAlpha(this);'></td>
            <td style='text-align: center;'><a style='width: 210px;'href='?QuestionID=$refQuestionID&Action=Delete Option&DeleteOptionID=".$row->OptionID."'>Delete</td>
         </tr>";
      }
      return "
      <table border='0' cellpadding='2' cellspacing='1' width='100%' $htmlAttr>
         <caption>Options</caption>
         <col />
         <col width='10%'/>
         <col width='10%'/>
         <col width='1%'/>
         <tr>
            <th>Option</th>
            <th>Order</th>
            <th>Weighting</th>
            <th>Delete</th>
         </tr>
         $strDetail
      </table>
      $BR
      ";
   }

   public function getAjaxQuestion($QID)
   {
      global $xdb;
      $xdb->doQuery("SELECT strQuestionID, refFundType, intYear, refClusterID FROM
                     surQuestion
                     INNER JOIN surQuestionnaire ON surQuestion.refQuestionaireID = surQuestionnaire.QuestionnaireID
                     INNER JOIN tblYear ON surQuestionnaire.refYearID = tblYear.YearID
                     WHERE QuestionID = '$QID'");
      if($row = $xdb->fetch())
      {
         return js("
            function loadResults(strQuestionID, QID)
            {
               $.ajax({type: 'GET',
                        url: '../../ajaxFunctions.php',
                        data: 'type=LoadResults&strQuestionID='+ strQuestionID +'&intFocusYear=". $row->intYear ."&refFundTypeID=". $row->refFundType ."&intPeriod=4&refClusterID=$row->refClusterID&blnOnline=1',
                        success: function(tblResults){
                        d('divStats_'+ QID).innerHTML = tblResults;
                        }
               });
               return false;
            }")."
            <div id='divStats_$QID' style='float:right;' xstyle='position: relative; top:-10px; left: 38px; z-index:1;'></div>
            ".js("loadResults('$row->strQuestionID', $QID);")."
            ";
            //<img id='imgLoading_$QID' src='images/loader_dark_0.gif' class='imgButton' style='position: relative; top:100px; right: 30%;' onclick=\"loadResults('$row->strQuestionID', $QID,0); destroy(this.id); jsShowElement('divStats_$QID',-1); \" />

      }
   }

   public static function Save(&$QuestionID, $nemo)
   {
      global $xdb;
      //print_rr($_POST);
      $db = new NemoDatabase("surQuestion", $QuestionID, null, 0);//array("refAssignmentID","strSection","strQuestionHeading")

      $db->SetValues($_POST);

      $db->Fields[strLastUser] = $_SESSION['USER']->USERNAME;

      $result = $db->Save(0,0);

      if($QuestionID > 0)
      {
         if(isset($_POST["strOption"]))
         {
            foreach($_POST["strOption"] as $k=>$v)
            {
               if(!isset($_POST["intWeighting"][$k]) || $_POST["intWeighting"][$k] != "")
                  $intWeighting = $_POST["intWeighting"][$k];
               else
                  $intWeighting = "0";
               $xdb->doQuery("UPDATE surOption SET strOption = ".$xdb->qs($_POST["strOption"][$k])."
                             , intOrder = ".$xdb->qs($_POST["intOptionOrder"][$k])."
                             , intWeighting = ".$xdb->qs($intWeighting)."
                             WHERE OptionID = ". $k);
            }
         }

         //20130718 - update parent Assignment record so Assignment.intMarks = SUM(tblQuestion.intMax) - pj
         $xdb->doQuery("UPDATE modAssignment SET intMarks = (SELECT SUM(intMaxScore) FROM surQuestion WHERE refAssignmentID = '". $_POST["refAssignmentID"] ."')
               WHERE AssignmentID = '". $_POST["refAssignmentID"] ."'");

      }else{
         $QuestionID = $result->ID;
      }

      if($result->Error == 1)
         return $result->Message;
      else
         return "Details Saved. ";

   }

   public static function AddOption($refQuestionID)
   {
      global $xdb;
      $row = $xdb->getRowSQL("SELECT MAX(intOrder) as nextOrder FROM surOption WHERE refQuestionID = ". $xdb->qs($refQuestionID));

      $newOptionID++;
      $xdb->doQuery("
                    INSERT INTO surOption (refQuestionID, intOrder)
                    VALUES (". $xdb->qs($refQuestionID).", ". $xdb->qs($row->nextOrder + 1) .")");
      return "Option Added";
   }

   public static function Delete($chkSelect)
   {
      global $xdb;
      //print_rr($chkSelect);
      if(count($chkSelect) > 0){
      foreach($chkSelect as $key => $value)
      {
         //$row = $xdb->getRowSQL("FROM surSurveyQuestion WHERE refQuestionID = ". $xdb->qs($key));

         $xdb->doQuery("DELETE FROM surQuestion WHERE QuestionID = ". $xdb->qs($key));
         //$xdb->doQuery("DELETE FROM surSurveyQuestion WHERE refQuestionID = ". $xdb->qs($key));
         //$xdb->doQuery("DELETE FROM surSurveyResponse WHERE QuestionID = ". $xdb->qs($key));
      }
         return "Records Deleted.";
      }
   }

   public static function DeleteOption($DeleteOptionID)
   {
      global $xdb;
      $xdb->doQuery("DELETE FROM surOption WHERE OptionID = ". $xdb->qs($DeleteOptionID));
      return "Option Deleted";
   }

   public static function getPrevQuestionID(&$QID)
   {
      global $xdb;
      $message = "";
      $xdb->doQuery("SELECT QuestionID, strNumberOrder FROM surQuestion WHERE refQuestionaireID = (SELECT refQuestionaireID FROM surQuestion WHERE QuestionID = $QID) AND strNumberOrder =
                        (
                           SELECT Max(strNumberOrder) as mx
                           FROM surQuestion
                           WHERE strNumberOrder < (SELECT strNumberOrder FROM surQuestion WHERE QuestionID = $QID)
                           AND refQuestionaireID = (SELECT refQuestionaireID FROM surQuestion WHERE QuestionID = $QID)
                        )
                     ");
      if($row = $xdb->fetch())
      {
         $QID = $row->QuestionID;
         if ($xdb->Rows != 1)
         {
            $message = "Duplicate Number Order Detected: " . $row->strNumberOrder;
         }
      }
      else
      {
         $xdb->doQuery("SELECT QuestionID, strNumberOrder FROM surQuestion WHERE refQuestionaireID = (SELECT refQuestionaireID FROM surQuestion WHERE QuestionID = $QID) AND strNumberOrder =
                           (
                              SELECT Max(strNumberOrder) as mx
                              FROM surQuestion
                              WHERE refQuestionaireID = (SELECT refQuestionaireID FROM surQuestion WHERE QuestionID = $QID)
                           )
                        ");
         if($row = $xdb->fetch())
         {
            $QID = $row->QuestionID;
            if ($xdb->Rows != 1)
            {
               $message = "Duplicate Number Order Detected: " . $row->strNumberOrder;
            }
         }
         else
         {
            $message = "Error: Previous Question Not Found.";
            $QID = 0;
         }
      }
      if($message != "")
      {
         return $message;
      }
   }

   public static function getNextQuestionID(&$QID)
   {
      global $xdb;
      $message = "";
      $xdb->doQuery("SELECT QuestionID, strNumberOrder FROM surQuestion WHERE refQuestionaireID = (SELECT refQuestionaireID FROM surQuestion WHERE QuestionID = '$QID') AND strNumberOrder =
                        (
                           SELECT Min(strNumberOrder) as mn
                           FROM surQuestion
                           WHERE strNumberOrder > (SELECT strNumberOrder FROM surQuestion WHERE QuestionID = '$QID')
                           AND refQuestionaireID = (SELECT refQuestionaireID FROM surQuestion WHERE QuestionID = '$QID')
                        )
                     ");
      if($row = $xdb->fetch())
      {
         $QID = $row->QuestionID;
         if ($xdb->Rows != 1)
         {
            $message = "Duplicate Number Order Detected: " . $row->strNumberOrder;
         }
      }
      else
      {
         $xdb->doQuery("SELECT QuestionID, strNumberOrder FROM surQuestion WHERE refQuestionaireID = (SELECT refQuestionaireID FROM surQuestion WHERE QuestionID = '$QID') AND strNumberOrder =
                           (
                              SELECT Min(strNumberOrder) as mn
                              FROM surQuestion
                              WHERE refQuestionaireID = (SELECT refQuestionaireID FROM surQuestion WHERE QuestionID = '$QID')
                           )
                        ");
         if($row = $xdb->fetch())
         {
            $QID = $row->QuestionID;
            if ($xdb->Rows != 1)
            {
               $message = "Duplicate Number Order Detected: " . $row->strNumberOrder;
            }
         }
         else
         {
            $message = "Error: Previous Question Not Found.";
            $QID = 0;
         }
      }
      if($message != "")
      {
         return $message;
      }
   }

   public static function Preview($QuestionID)
   {
      global $xdb, $BR, $SP;

      //copy from nemo survey

      $Question = $xdb->getRowSQL("SELECT * FROM surQuestion WHERE QuestionID = $QuestionID");

      if($Question)
      {
         //20181205 - Added Order By to Question Options - Rachel
         $xdb->doQuery("SELECT * FROM surOption WHERE refQuestionID = $QuestionID ORDER BY intOrder, strOption");
         while($row = $xdb->fetch())
         {
            $Options[$row->OptionID] = $row;
         }
         $Question->Options = $Options;

         $Output .= "<a id='aQuestion[$Question->strQuestionID]' /></a>
            <div class='divQuestion' id='divQuestion[$QID]' style=''>";
               //if q heading
               if($Question->strQuestionHeading != "" && $currentQuestionHeading != $Question->strQuestionHeading)
               {
                  $Output .= "<h2 class='textColour' xstyle='font-size:16px;'>". nl2br($Question->strQuestionHeading) ."</h2>";//wtf?! class divQHeading doesn't want to fucking work!?
                  $currentQuestionHeading = $Question->strQuestionHeading;
               }
//print_rr($Question);

               //$strQ = "Q$Question->strOrder - $Question->strQuestionID [$QID]";
               $Output .= "<p style='margin-bottom: 0px;'><b>Q$Question->intOrder - ". mynl2br($Question->strQuestion) ."</b></p>";
               //if q info
               if($Question->strInformation != "")
               {//not quite working yet
                  $Output .= "
                     <div id='divInfo[$QID]' style='border: 0px dashed #CC922D; margin: 14px; margin-bottom: 0px; position relative; top: -14px; display: block;'>
                        <i>". mynl2br($Question->strInformation) ."</i></div>
                  ";
               }
               $Output .="
         <table class='' width=99% cellpadding=0 cellspacing=0 border=0 style='margin-top: 14px; margin-bottom: 0px;'>
            <tr>
               <td colspan='1' width='90%' valign=top>
                  <table class='tblOptions' width=100% cellpadding=4 cellspacing=0 border=0 id=tblQuestion[$QID] style='border: 0px dashed green; margin-bottom: 0px;'>";
               if(is_array($Question->Options)){
               foreach($Question->Options as $OID => $Option)
               {
                  //switch q/option types
                  //@$control = $this->renderControl($Option, $Question->refOptionType);
                  //$Output .= $control;
                  switch($Question->refOptionType)
                  {
                     case "Radio":
                     case "Yes/No":
                     case "Range":
                        $Output .= "
                           <tr>
                              <td align=center width='5%'><input type=radio name='option[$QID]' id='option[$OID]' value='$OID' ". $Option->selected ." ondblclick='if(this.checked == true){this.checked=false;}'/></td>
                              <td align=left><label for='option[$OID]'>". $Option->strOption ."</label></td>
                           </tr>";//htmlentities($Option->strOption)
                        break;
                     case "Checkbox"://chk has no mandatory checks
                        $Output .= "
                           <tr>
                              <td align=center width='5%'><input type=checkbox name='option[$QID][$OID]' id='option[$QID][$OID]' value='$QID' ". $Option->selected ."/></td>
                              <td align=left><label for='option[$QID][$OID]'>". $Option->strOption ."</label></td>
                           </tr>";
                        break;
                     case "Free Text":
                     default:
                        print_rr($Question); die;
                        break;
                  }
               }
               }else{
                  if(!$Question->blnComments) 
                     $Output .= "<tr><td colspan='100%' style='border: 2px dashed orange; padding: 10px; font-weight: bold;'>No Options loaded for this question</td></tr>";
               }

               if($Question->blnFlag){
                  $class = "textColourAlt";
               }
               else{
                  $class = "textColour";
               }

               //if comment
               if($Question->blnComments)
               {
                  $Output .= "
                     $TR
                     <tr>
                        <td align=center>$SP</td>
                        <td align=left>Comments: $BR<textarea name='txtComment[$QID]' id='txtComment[$QID]' class='$class controlText controlWideMax'>". $Question->txtComment ."</textarea></td>
                     </tr>";
               }

               //if($Question->intFlags != 0){
               //   $strFlags = "<b class='textRed'>($Question->intFlags)</b>";
               //}
               //else{
               //   $strFlags = "($Question->intFlags)";
               //}
               //$Output .= "
               //            <tr>
               //               <td align=center ><input type=checkbox name='chkFlag[$QID]' id='chkFlag[$QID]' value='1' $Question->blnFlag /></td>
               //               <td align=left><label for='chkFlag[$QID]'>Flag this question $strFlags</label></td>
               //            </tr>

               $Output .= "
                  </table>
               </td>
               <td style='border: 0px dashed red;' align=right valign=top>";

               $i++;
               //if(is_array($Question->Options)){
               //   $Output .= "
               //   <img id='imgStats_$QID' src='images/info.png' class='imgButton' height=32 style='display:none; position: relative; top: -28px; left: 26px; float: right; z-index:2;' onclick='jsShowElement(\"divStats_$QID\",-1)'/>
               //   <div id='divStats_$QID' style='display: none; position: relative; top:-10px; left: 38px; z-index:1;'></div>
               //   <img id='imgLoading_$QID' src='images/loader_dark_". ($i%3) .".gif' class='imgButton' style='position: relative; top:100px; right: 30%;' onclick=\"loadResults('$Question->strQuestionID', $QID,0); destroy(this.id); jsShowElement('divStats_$QID',-1); \" />
               //</td>";
               //$jsLoadResults .= "loadResults('$Question->strQuestionID', $QID,1);
               //   ";
               //}
               $Output .= "
            </tr>
         </table>";
      }

      return $Output;
   }

}
?>