<?php
	class cEvaluateTestPage extends cStudentPage
	{
		function Process()
		{
			if ( !$this->bLoggedIn ) 
			{
				return true;
      }
      else
			{ 
	      // znic sessiony ohladom testovania
	      if (isset($_SESSION['testId']))
	      {
	      	unset($_SESSION['testId']);
	      }
	      if (isset($_SESSION['testOpen']))
	      {
	      	unset($_SESSION['testOpen']);
	      }
	      
				$query = "SELECT *
									FROM tTest 
								 	WHERE id='".$this->getParams['testId']."' AND mark IS NOT NULL;";
				$result = $this->db->QueryToRow($query);
	      // ak test este nebol vyhodnoteny...
				if ( $result == 0 ) 
				{
					// v pripade ze su poslane nasledujuce parametre, tak ich spracuj (pocitanie casu straveneho nad otazkou)
					if (isset($this->getParams["oldQId"]) && isset($this->getParams["time"]))
					{
						$qid = $this->getParams["oldQId"];
						$timeDif = time() - (is_numeric($this->getParams["time"])?$this->getParams["time"]:time());
			      $query = "UPDATE tTestAnswer SET totalTime = totalTime + $timeDif WHERE id_test = '".$this->getParams['testId']."' AND index = '$qid';";
						$result = $this->db->Query($query);   
					}
								
					// vyhodnotenie testu
					// napln pole skalou
					$query = "SELECT tS.*, tC.name, tC.id AS id_course
										FROM tCourse AS tC
										INNER JOIN tScale AS tS ON tS.id = tC.id_scale
										INNER JOIN tTestTemplate AS tTT ON tTT.id_course = tC.id
										INNER JOIN tTest AS tT ON tT.id_testTemplate = tTT.id
										WHERE tT.id = '".$this->getParams["testId"]."';";
					$scale = $this->db->QueryToRow($query);

					$this->smarty->assign("courseId", $scale['id_course']);
					$this->smarty->assign("courseName", $scale['name']);
	
					// napln pole odpovedami
		      $query = "SELECT tQ.id AS id_question, tQ.question, tA.text, tTATA.value, tA.correct, ".
		               "tTA.comment, tTA.points, tTA.id AS id_testAnswer ".
		               "FROM tTest AS tT, tTestTemplate AS tTT, tTestItems as tTI, tAnswerSet AS tAS, ".
		               "tQuestion AS tQ, tAnswer AS tA, tTestAnswerToAnswer AS tTATA, tTestAnswer AS tTA ".
		               "WHERE tT.id=".$this->getParams["testId"]." AND tT.id_user=".$this->userId." AND ".
		               "tT.id_testTemplate=tTT.id AND tTI.id_testTemplate=tTT.id AND ".
		               "tTI.id_answerSet=tAS.id AND tAS.id_question=tQ.id AND ".
		               "tA.id_answerSet=tAS.id AND tTATA.id_answer=tA.id AND ".
		               "tTATA.id_testAnswer=tTA.id AND tTA.id_test=tT.id ".
		               "ORDER BY tQ.id;";
		      $answers = $this->db->QueryToArray($query);
		      $questionId = 0;
		      $totalPoints = 0;
		      $points = 0;
					foreach ($answers as $answer) 
					{
						// zistit typ odpovede: full, missing, partial, bad
						
						if ($questionId == 0 || $questionId != $answer['id_question']) // ak som narazil na novu otazku
						{
																			
							if ($questionId != 0) 
							{
								if ($bad) // odpoved je zla
								{
									$answerType = 'bad';
									$points = $scale['ptsBad'];
								}
								elseif (!$answered) // odpoved nie je zodpovedana
								{
									$answerType = 'missing';
									$points = $scale['ptsEmpty'];
								}
								elseif ($partial) // odpoved je ciastocna
								{
									$answerType = 'partial';
									$points = $scale['ptsPartial'];
								}
								else // odpoved je spravna
								{
									$answerType = 'full';
									$points = $scale['ptsFull'];
								}

								// nastav spravne hodnoty v tTestAnswer
								$query = "UPDATE tTestAnswer SET points='$points', answerType='$answerType' WHERE id='$testAnswerId';";
								$result = $this->db->Query($query);
								$totalPoints += $points;
							}

							$questionId = $answer['id_question'];
							$testAnswerId = $answer['id_testAnswer'];
							$answered = false;
							$partial = false;
							$bad = false;
						}
						
						if ($answer['value'] === '1') $answered = true; // na otazku bolo odpovedane
						
						if ($answer['correct'] !== '1' && $answer['value'] === '1') // ak odpoved nie je spravna a aj napriek tomu je oznacena
						{
							$bad = true;
						}
						elseif ($answer['correct'] === '1' && $answer['value'] !== '1') // ak odpoved nie je oznacena ale je spravna
						{
							$partial = true;
						}
					}

					// treba spracovat este poslednu otazku
					if ($bad) // odpoved je zla
					{
						$answerType = 'bad';
						$points = $scale['ptsBad'];
					}
					elseif (!$answered) // odpoved nie je zodpovedana
					{
						$answerType = 'missing';
						$points = $scale['ptsEmpty'];
					}
					elseif ($partial) // odpoved je ciastocna
					{
						$answerType = 'partial';
						$points = $scale['ptsPartial'];
					}
					else // odpoved je spravna
					{
						$answerType = 'full';
						$points = $scale['ptsFull'];
					}

					// nastav spravne hodnoty v tTestAnswer
					$query = "UPDATE tTestAnswer SET points='$points', answerType='$answerType' WHERE id='$testAnswerId';";
					$result = $this->db->Query($query);
					$totalPoints += $points;

					// nastav spravne hodnoty v tTest
					// zisti aka je pridelena znamka na zaklade poctu bodov
					if ($totalPoints < $scale['E'])
					{
						$mark = 'Fx';
					}
					elseif ($totalPoints < $scale['D'])
					{
						$mark = 'E';
					}
					elseif ($totalPoints < $scale['C'])
					{
						$mark = 'D';
					}
					elseif ($totalPoints < $scale['B'])
					{
						$mark = 'C';
					}
					elseif ($totalPoints < $scale['A'])
					{
						$mark = 'B';
					}
					else
					{
						$mark = 'A';
					}
					$query = "UPDATE tTest SET points='$totalPoints', mark='$mark', totalTime=totalTime-NOW() WHERE id='".$this->getParams["testId"]."';";
					$result = $this->db->Query($query);
	      }
	      else
	      {
	      	return false;
	      }
	    }
			return true;
    }
    
    function Draw()
    {
    
      if ( !$this->bLoggedIn )
      {
        $this->smarty->display("login.tpl");
      }
      else
      {
	      // vyber informacie o uzivatelovi
				$query = "SELECT CONCAT(tU.namePrefix, ' ', tU.surname, ', ', tU.name, ' ', tU.nameSuffix) AS name ".
	               "FROM tUser AS tU, tStudents AS tS WHERE tU.id=".$this->userId." ".
	               "AND tU.id=tS.id;";
	      $result = $this->db->QueryToRow($query);
	      if ( $result != 0 )
	      {
	        $this->smarty->assign("userInfo",$result);
	      }
	      
	      // vyber informacie o teste
				$query =	"SELECT Now() AS date, tT.comment, tT.mark, tT.points FROM tTest AS tT
									 WHERE tT.id='".$this->getParams["testId"]."';";
	      $result = $this->db->QueryToRow($query);
	
	      if ( $result != 0 )
	      {
	        $this->smarty->assign("examDate",$result["date"]);
	        $this->smarty->assign("testComment",$result["comment"]);
	        $this->smarty->assign("testMark",$result["mark"]);
	        $this->smarty->assign("testPoints",$result["points"]);
	      }
	
	      $query = "SELECT tQ.id AS id_question, tQ.question, tA.text, tTATA.value, tA.correct, ".
	               "tTA.comment, tTA.points, tTA.id AS id_testAnswer ".
	               "FROM tTest AS tT, tTestTemplate AS tTT, tTestItems as tTI, tAnswerSet AS tAS, ".
	               "tQuestion AS tQ, tAnswer AS tA, tTestAnswerToAnswer AS tTATA, tTestAnswer AS tTA ".
	               "WHERE tT.id=".$this->getParams["testId"]." AND tT.id_user=".$this->userId." AND ".
	               "tT.id_testTemplate=tTT.id AND tTI.id_testTemplate=tTT.id AND ".
	               "tTI.id_answerSet=tAS.id AND tAS.id_question=tQ.id AND ".
	               "tA.id_answerSet=tAS.id AND tTATA.id_answer=tA.id AND ".
	               "tTATA.id_testAnswer=tTA.id AND tTA.id_test=tT.id ".
	               "ORDER BY tQ.id;";
	      $result = $this->db->QueryToArray($query);
	      if ( $result != 0 )
	      {
	        $questions=array();
	        foreach ($result as $key=>$value)
	        {
	          if (empty($questions[$value["id_question"]]))
	          {
	            $questions[$value["id_question"]]["question"]=$value["question"];
	            $questions[$value["id_question"]]["id_testAnswer"]=$value["id_testAnswer"];
	            $questions[$value["id_question"]]["comment"]=$value["comment"];
	            $questions[$value["id_question"]]["points"]=$value["points"];
	            $questions[$value["id_question"]]["answers"]=array();
	          }
	          array_push($questions[$value["id_question"]]["answers"], array("text"=>$value["text"], "value"=>$value["value"], "correct"=>$value["correct"]));
	        }
	        $i=0;
	        foreach ($questions as $key=>$value)
	        {
	          $i++;
	          $questions[$key]["number"]=$i;
	        }
	        $this->smarty->assign("questions",$questions);
	      }
	      
				// zmaz timeStampy
				$query = "DELETE FROM tTimeStamp WHERE id_test='".$this->getParams["testId"]."' AND id_user='".$this->userId."';";
  			$result = $this->db->Query($query);    	

	      $query = "SELECT * 
									FROM tTest
									WHERE id_exam='0' AND id='".$this->getParams["testId"]."';";
	      $result = $this->db->QueryToRow($query);
	      // ak sa jedna o demotest, tak zmaz vsetky informacie o nom...
	      if ($result!=0)
	      {
	      	// zmaz zaznamy v tTestAnswerToAnswer
					$query = "DELETE FROM tTestAnswerToAnswer WHERE id_testAnswer IN (SELECT id FROM tTestAnswer WHERE id_test='".$this->getParams["testId"]."');";
	  			$result = $this->db->Query($query);    	
	      	// zmaz zaznamy v tTestAnswer
					$query = "DELETE FROM tTestAnswer WHERE id_test='".$this->getParams["testId"]."';";
	  			$result = $this->db->Query($query);    	
	      	// zmaz zaznam v tTest
					$query = "DELETE FROM tTest WHERE id='".$this->getParams["testId"]."';";
	  			$result = $this->db->Query($query);    	
	      }
	      
	      $this->smarty->assign("testId", $this->getParams["testId"]);
	
	      $this->smarty->assign("content", "evaluateTest.tpl");
	      parent::Draw();
	    }
    }
	}
?>
