<?php 

class mysteryCalculator
{
	
	protected $db;
	protected $QuestionScores;
	protected $projectName;
	protected $noQuestionScores = false;
	protected $labelsLanguageID = 89;
	protected $weighting = true;
	protected $weightingMonitor = false;
	
	
	public function __construct($db,$projectName)
	{
		$this->db = $db;
		$this->projectName = $projectName;
	}
	
	/**
	 * With this function we load all scores on question in defined project
	 * 	
	 */
	
	public function LoadQuestionScores() {
		
		$sql = " SELECT a .* , b.q_name, b.tip_sql, b.id as id_question
					FROM ".DB_WARPIT_WEBCATI.".".$this->projectName."_mystery AS a
					LEFT JOIN ".DB_WARPIT_WEBCATI.".".$this->projectName." AS b ON a.id_question = b.id ";
			
		if ($this->hideQuestions) $sql .= " WHERE b.id NOT IN (".implode(",",$this->hideQuestions).")";
		
		//echo $sql;
		$res = $this->db->SQLexecute($sql);
		
		if ($this->db->NumRows($res) == 0) $this->noQuestionScores = true;
		
		while ($zad = $this->db->fetchAssoc($res) )
		{
			
			if (is_null($zad['q_name'])) {
				if ($zad['id_folder'] && $zad['sc_value'] && $this->weighting) $this->FolderWeight[$zad['id_folder']] = $zad['sc_value'];
				continue;
			}
			
			$variableInDatabase = 0;			
			
			if ($zad['tip_sql'] == 1) {
				
				$variableInDatabase = $zad['q_name'];
				//$this->VariableTree[$zad['q_name']][$variableInDatabase] = $variableInDatabase;
				
				$this->QuestionScores[$variableInDatabase][$zad['id_answer']] = $zad['sc_value'];
			
			} elseif ($zad['tip_sql'] == 3 || $zad['tip_sql'] == 2) {
				
				if ($zad['tip_sql'] == 2) {
					$variableInDatabase = $zad['q_name']."_".$zad['id_legend'];	
					$this->QuestionScores[$variableInDatabase][$zad['id_answer']] = $zad['sc_value'];
				} else {
					$variableInDatabase = $zad['q_name']."_".$zad['id_answer'];
					$this->QuestionScores[$variableInDatabase][$zad['id_answer']] = $zad['sc_value'];	
				}
					
				//$this->VariableTree[$zad['q_name']][$variableInDatabase] = $variableInDatabase;
				$this->VariableTree[$variableInDatabase] = $zad['q_name'];
				
				
				$this->QuestNames[$variableInDatabase] = $zad['id_question']; 
				//echo $variableInDatabase."---".$zad['id_answer']."<Br>";
			}
			
			if ($variableInDatabase) $this->databaseVariables[] = $variableInDatabase;
			
		}
		
	}

	
	private function recursiveDeleteSubStructure($aIdSup) {
		
		//echo "Delete item : ".$aIdSup."<br>";
		$this->hideQuestions[$aIdSup] = $aIdSup;
		
		unset($this->QuestStructure[$aIdSup]);
		if (is_array($this->QuestSubStructure[$aIdSup])) {
			foreach ($this->QuestSubStructure[$aIdSup] as $subKeys) {
				//echo $subKeys."<Br>";
				$this->recursiveDeleteSubStructure($subKeys);
			}
		}
		unset($this->QuestSubStructure[$aIdSup]);
		
	}
	
	public function LoadQuestionnaireTree() {
		
		$sql = " SELECT a.id,a.id_sup,a.idLab,a.is_leaf, b.lngText  FROM  ".DB_WARPIT_WEBCATI.".".$this->projectName."_tree as a
					LEFT JOIN ".DB_WARPIT_WEBCATI.".".$this->projectName."_language as b 
						ON 			a.id_question = b.id_question 
							AND  	b.id_text_type = 2 
							AND 	b.id_language = ".$this->labelsLanguageID."
					ORDER BY id_sup ASC, orderBy ASC ";
		//echo $sql;	
		$res = $this->db->SQLexecute($sql);
		while ($zad = $this->db->fetchAssoc($res)) {
			$this->QuestStructure[$zad['id']] = $zad['id_sup'];	
			$this->QuestSubStructure[$zad['id_sup']][] = $zad['id'];			
			
			$this->QuestNames[$zad['id']] = $zad['idLab'];			
			$this->QuestNames[$zad['idLab']] = $zad['id'];
			
			// directory structure
			if ($zad['is_leaf'] == 0) {
				if ($zad['id_sup'] == 0) $this->FolderStructure['main'][$zad['id']] = $zad['idLab'];
				else $this->FolderStructure['sub'][$zad['id_sup']][$zad['id']] = $zad['idLab'];
			} else {
				$this->QuestNamesLabels[$zad['id']] = $zad['lngText'];
			}
		}
		
		
		if (is_array($this->hideGroups)) {
			foreach ($this->hideGroups as $HideKeys) $this->recursiveDeleteSubStructure($HideKeys);
		}
	
	}
	
	
	private function RecursivePointAdded($aIdQuest,$aPointType,$aScoreVal) {

		while ($this->QuestStructure[$this->QuestNames[$aIdQuest]] != 0) {
			
			$aIdQuest = $this->QuestStructure[$this->QuestNames[$aIdQuest]];
			$this->calculatedScoresFolders[$aIdQuest][$aPointType] += abs($aScoreVal);
			$this->calculatedScoresFolders[$aIdQuest]['total'] += abs($aScoreVal);
			$this->calculatedScoresFolders[$aIdQuest]['lab'] = $this->QuestNames[$aIdQuest];
			$aIdQuest = $this->QuestNames[$aIdQuest];

		}
		
	}
	
	/**
	 * Enter description here...
	 *
	 * @param record array $rec
	 */
	
	public function CalculateRecord($rec) {

		foreach ($rec as $key=>$val) {
			//echo $key." -> ".$val." ==> ".$this->QuestionScores[$key][$val]."<br>";
			if (!$this->QuestionScores[$key][$val]) continue;
			
			$ScoreVal = $this->QuestionScores[$key][$val];
			
			if ( $ScoreVal > 0 ) {
				
				$this->calculatedScores[$key]['pos'] += $ScoreVal;
				$this->calculatedScores[$key]['total'] += $ScoreVal;
				
				if ($questionName = $this->VariableTree[$key]) {
					$this->calculatedScores[$questionName]['pos'] += $ScoreVal;
					$this->calculatedScores[$questionName]['total'] += $ScoreVal;
				}
				
				// preparing array for filters in table, so we can show only records which have on this questions this answers
				// we have one for positive values and one for negative values
				$this->QuestionFilterValues[$key]['pos'][$val] = $val;
				
				
				$this->RecursivePointAdded($key,'pos',$ScoreVal);
				
				$this->calculatedScoresTotal['total'] += abs($ScoreVal);
				$this->calculatedScoresTotal['pos'] += abs($ScoreVal);
			
			} elseif ($ScoreVal < 0) {
				
				$this->calculatedScores[$key]['neg'] += abs($ScoreVal);
				$this->calculatedScores[$key]['total'] += abs($ScoreVal);
				
				if ($questionName = $this->VariableTree[$key]) {
					$this->calculatedScores[$questionName]['neg'] += abs($ScoreVal);
					$this->calculatedScores[$questionName]['total'] += abs($ScoreVal);
				}
				
				// preparing array for filters in table, so we can show only records which have on this questions this answers
				// we have one for positive values and one for negative values
				$this->QuestionFilterValues[$key]['neg'][$val] = $val;
				
				$this->RecursivePointAdded($key,'neg',$ScoreVal);
				
				$this->calculatedScoresTotal['total'] += abs($ScoreVal);
				$this->calculatedScoresTotal['neg'] += abs($ScoreVal);
				
			}
		}
		
	}

	
	public function ControlWeightOutput($aIdFolder, $aValue) {
		if ($this->FolderWeightFactor[$aIdFolder]) return round($this->FolderWeightFactor[$aIdFolder] * $aValue,1);
		return $aValue;
	}
	
	public function CalculateWeighting() {
		
		foreach ($this->FolderStructure['main'] as $idMainFolder => $FolderLab) {
			
			if (!$this->calculatedScoresFolders[$idMainFolder]['total'] || !$this->FolderWeight[$idMainFolder]) continue;
			
			/*echo  "main #1 : ".$this->calculatedScoresFolders[$idMainFolder]['total']."<br>";
			echo  "main #2 : ".$this->calculatedScoresTotal['total']."<br>";
			echo  "main #3 : ".($this->calculatedScoresFolders[$idMainFolder]['total'] / $this->calculatedScoresTotal['total'] * 100)."<br>";
			*/
			
			$this->FolderWeightFactor[$idMainFolder] = $this->FolderWeight[$idMainFolder] / ($this->calculatedScoresFolders[$idMainFolder]['total'] / $this->calculatedScoresTotal['total'] * 100);
			
			if ($this->weightingMonitor) {
				echo "<b>".$FolderLab." (".$this->calculatedScoresFolders[$idMainFolder]['total'].")</b><br>
						....w: ".$this->FolderWeight[$idMainFolder]."% <br>
						....%:	".round($this->calculatedScoresFolders[$idMainFolder]['total'] / $this->calculatedScoresTotal['total'] * 100,2)." % <br>
						....f: ".$this->FolderWeightFactor[$idMainFolder]."<br>
						....n: <font color=red>".round($this->calculatedScoresFolders[$idMainFolder]['total'] * $this->FolderWeightFactor[$idMainFolder],2)."</font>";
			}
				
			if ( $this->FolderStructure['sub'][$idMainFolder] ) {
				if ($this->weightingMonitor) echo "<br>------------------------<br>";
				
				foreach ($this->FolderStructure['sub'][$idMainFolder] as $idSubFolder => $SubFolderLab) {
					
					$this->FolderWeightFactor[$idSubFolder] = 1;
					
					if (!$this->calculatedScoresFolders[$idSubFolder]['total']) continue;
					if ($this->FolderWeight[$idSubFolder]) {
						$this->FolderWeightFactor[$idSubFolder] = $this->FolderWeightFactor[$idMainFolder] * ($this->FolderWeight[$idSubFolder] / ($this->calculatedScoresFolders[$idSubFolder]['total'] / $this->calculatedScoresFolders[$idMainFolder]['total'] * 100));
					} elseif ($this->FolderWeightFactor[$idMainFolder]) {
						$this->FolderWeightFactor[$idSubFolder] = $this->FolderWeightFactor[$idMainFolder];
					}
					
					
					if ($this->weightingMonitor) {
						echo "<Br><i>".$SubFolderLab." (".$this->calculatedScoresFolders[$idSubFolder]['total'].")</i><br>
						....w: ".$this->FolderWeight[$idSubFolder]."% <br>
						....%:	".round($this->calculatedScoresFolders[$idSubFolder]['total'] / $this->calculatedScoresFolders[$idMainFolder]['total'] * 100,2)." % <br>
						....fsup: ".$this->FolderWeightFactor[$idSubFolder]."<br>
						....n: <font color=red>".round($this->calculatedScoresFolders[$idSubFolder]['total'] *  $this->FolderWeightFactor[$idSubFolder],2)."</font>";
		
					}
				}
			}
			if ($this->weightingMonitor)  echo "<hr>";
		}
		
	}
	
	
	public function LoadRecords($id) {
		if ($this->noQuestionScores == true) return false;
		
		$sql = "SELECT ".implode(",",$this->databaseVariables)." 
					FROM ".DB_WARPIT_WEBCATI_BASE.".".$this->projectName."_structure 
						WHERE id IN (".$id.") ";
		$res = $this->db->SQLexecute($sql);
		while ($rec = $this->db->fetchAssoc($res)) $this->CalculateRecord($rec);
		$this->CalculateWeighting();
		return true;
	}
	
}
	



?>