<?php
include_once ("_dirinfo.php");

include_once (PATH_TO_ROOT."init.php");
include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.treeData.php");



$tableName = $db->get('_Projects',$_POST['id_project'],'proj_name,language',DB_WARPIT_WEBCATI_BASE);;
$id_language = $tableName['language'];
$tableName = $tableName['proj_name'];
$db->ChangeDatabase(DB_WARPIT_WEBCATI);

class mysteryShopMan extends TreeDataManipulator {
	
	
	function selectAction()
	{
		
		$parent = $_POST['node'];
		$id = $_POST['node'];
		
		if(false)
		{
			$qVar = $this->db->get($this->table,$id);
			//$qOdg = 
		}
		else
		{
			require_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
		
			$sql = $this->db->SQLexecute("SELECT * FROM _LanguageText");
			while($row = $this->db->fetchRow($sql))
			{
				$i=$row[0];
				$var = $row[1];
				$selVpr .= ",(SELECT lngText FROM ".$this->table."_language b WHERE id_question = $this->table.id AND id_language = $this->id_langage AND id_text_type = $i) as $var";
			}
			$sql = "SELECT * $selVpr FROM $this->table WHERE q_pos > 0 ORDER BY q_pos";
	
			if (!$res = $this->db->SQLexecute($sql)) 
			{			
			  return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
			}
			else 
			{
			
				
				//get score values!
				$sqlScor = "SELECT * from $this->table".'_mystery';
				$resScor = $this->db->SQLexecute($sqlScor);
				while ($rowScor = $this->db->fetchAssoc($resScor))
				{
					$id_q = $rowScor['id_question'];
					$id_a = $rowScor['id_answer'];
					$id_l = $rowScor['id_legend'];
					if( $id_l )
					{
						//if there isn't a stronger parent already!
						if($scores[$id_q] !== true && $scores[$id_q][$id_a] !== true)
						{
							$scores[$id_q][$id_a][$id_l] = true;
							$scValues[$id_q][$id_a][$id_l] = $rowScor['sc_value'];
						} 
					}
					else if( $id_a )
					{
						//if there isn't a stronger parent already!
						if($scores[$id_q] !== true )
						{
							$scores[$id_q][$id_a] = true;
							$scValues[$id_q][$id_a] = $rowScor['sc_value'];
						} 
					}
					else
						$scores[$id_q] = true;
				}
				//print_r($scores);
				while ($row = $this->db->fetchAssoc($res)) {
					
					
					// Response parameters.
					$path = array();
					$path['id']			= $row['id'];	
					$path['q_name']	=$row['q_name'];				
					
					$path['leaf']		= false;
					$path['children'] = array();
					
					$q = Question::createQuestion($row['tip_sql'],$this->db,$row);
					$path['iconCls'] = $q->getIconCls();
					$path['q_pos'] = $row['q_pos'];
					if($scores[$path['id']] === true) $path['score'] = 'checked';
					$ans = $q->getAnswerArray();
					$legArr = $q->getLegendArray();
					if($legArr)
					{
						foreach ($legArr as $pos=>$lab) {
							$ansNode = array();
							$ansNode['id'] = $path['id'].'_'.$lab[0];
							$ansNode['value'] = $lab[0];
							$ansNode['q_name'] = '   '.$lab[1];
							if($scores[$path['id']][$lab[0]] === true) $ansNode['score'] = 'checked';
							$ansNode['q_pos'] = $pos;
							
							
								foreach ($ans as $posLeg=>$leg) {
									$legNode = array();
									$legNode['id'] = $ansNode['id'].'_'.$leg[0];
									$legNode['value'] = $leg[0];
									$legNode['q_name'] = '   '.$leg[1];
									$legNode['q_pos'] = $posLeg;
									if($scores[$path['id']][$lab[0]][$leg[0]] === true) $legNode['score'] = 'checked';
									$legNode['leaf'] = true;
									if($scValues[$path['id']][$lab[0]][$leg[0]])
										$legNode['sc_value'] = $scValues[$path['id']][$lab[0]][$leg[0]];
									$ansNode['children'][] = $legNode;
								}
								$ansNode['leaf'] = false;
							
							
								
								
						
						$path['children'][] = $ansNode;
								
						}
					}
					else
					{ 
						foreach ($ans as $pos=>$lab) {
							$ansNode = array();
							$ansNode['id'] = $path['id'].'_'.$lab[0];
							$ansNode['value'] = $lab[0];
							$ansNode['q_name'] = '   '.$lab[1];
							if($scores[$path['id']][$lab[0]] === true) $ansNode['score'] = 'checked';
							$ansNode['q_pos'] = $pos;
							if($scValues[$path['id']][$lab[0]])
										$ansNode['sc_value'] = $scValues[$path['id']][$lab[0]];
							$ansNode['leaf'] = true;
							
							$path['children'][] = $ansNode;
						}
					}
					$nodes[] = $path;
					
				}
				
				
			}
		}
		return json_encode($nodes);
	}

	function addScoreAction()
	{
		$ids = explode('_',$_POST['value']);
		$n = count($ids);
		$filds[] = 'id_question';
		if($n>1)
			$filds[] = 'id_answer';
		if($n>2)
			$filds[] = 'id_legend';
		if($_POST['checked'] == 'true')
			$sql = "INSERT INTO $this->table"."_mystery (".implode(',',$filds).",sc_value) VALUES (".implode(',',$ids).",'{$_POST['sc_value']}')";
		else 
		{
			$sql = "DELETE FROM $this->table"."_mystery WHERE id_question=".$ids[0];
			for($i=1;$i<$n;$i++)
				$sql.= ' AND ('.$filds[$i] .' = '.$ids[$i].' OR '.$filds[$i].' IS NULL)';
		}
		$this->db->SQLexecute($sql);
		return "{success:true}";
	}
	function addScvalAction()
	{
		$ids = explode('_',$_POST['value']);
		
		$sql = "UPDATE $this->table"."_mystery SET sc_value = '".$_POST['scVal']."' WHERE id_question = {$ids[0]} AND  id_answer = {$ids[1]}";
		if($ids[2])
	     	$sql.=	" AND  id_legend = {$ids[2]}";
		$this->db->SQLexecute($sql);
		return "{success:true}";
	}
	function saveCommentAction()
	{
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = "UPDATE $this->table"."_structure SET mystery_comment = '{$_POST['value']}' WHERE id = {$_POST['id_record']}";
		$this->db->SQLexecute($sql);
	}
	
	private function getImagesArray()
	{
		$images = $this->db->get($this->table."_structure",$_POST['id_record'],'mystery_image' );
		if(!$images) return array();
		$images = explode('<*>',$images);
		
		foreach ($images as $image) {
			$image = explode('<!>',$image);
			$imageArray[ $image[0] ] = $image[1];
			
		}
		$this->lastId = $image[0];
		return $imageArray;
	}
	
	private function getImagesString($images)
	{
		foreach ($images as $num => $im) {
			$newArr[] = $num.'<!>'.$im;
		}
		if($newArr)
			return implode($newArr,'<*>');
		return '';
	}
	
	function uploadImageAction()
	{
		if ($_FILES['uploadLink']['tmp_name']) {
		
			$bla = end(explode(".", $_FILES['uploadLink']['name']));
			$c = configLoader::loadConfig('paths');
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			
			$images = $this->getImagesArray();
				
			$this->lastId++;
			
			$length = 4;
		    $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
		    $string = '';    
		    for ($p = 0; $p < $length; $p++) {
		        $string .= $characters[mt_rand(0, strlen($characters))];
		    }
			
			$image_name = 'MysteryImage_'.$_POST['id_project'].'_'.$_POST['id_record'].'_'.$this->lastId.'.'.$string;
	
			if(!file_exists($c['warpit_webprojects'].'mystery_shopping'))
				mkdir($c['warpit_webprojects'].'mystery_shopping');
				
			if(file_exists($c['warpit_webprojects'].'mystery_shopping/'.$image_name))	
				unlink($c['warpit_webprojects'].'mystery_shopping/'.$image_name);
			if(	move_uploaded_file($_FILES['uploadLink']['tmp_name'],$c['warpit_webprojects'].'mystery_shopping/'.$image_name ))
			{
				
				
				
				$images[$this->lastId] = $image_name;
				
				$sm = $this->getImagesString($images);
				
				$sql = "UPDATE $this->table"."_structure SET mystery_image = '$sm' WHERE id = ".$_POST['id_record'];
				$this->db->SQLexecute($sql);
				echo "{'success':true}";
				
			}
			else 
				echo "nesto se zalomio";
		}
		else 
		{
			echo 'nemaslike';
		}
	}
	function deleteImageAction()
	{
		$c = configLoader::loadConfig('paths');
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$images = $this->getImagesArray();
		$val = $_POST['value'];
		//delete the image
		if(file_exists($c['warpit_webprojects'].'mystery_shopping/'.$images[$val]))	
			if(!unlink($c['warpit_webprojects'].'mystery_shopping/'.$images[$val]))
				return "zasto da nemugu brisati slike??";
		unset ($images[$val]);
		$this->getImagesString($images);
		$sm = $this->getImagesString($images);
				
		$sql = "UPDATE $this->table"."_structure SET mystery_image = \"$sm\" WHERE id = ".$_POST['id_record'];
		$this->db->SQLexecute($sql);
		return "{success:true}";
		
		//$sql = "UPDATE $this->table"."_structure SET mystery_image = '' WHERE id = ".$_POST['id_record'];
		//		$this->db->SQLexecute($sql);
	}
	function loadImageAction()
	{
		$c = configLoader::loadConfig('paths');
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$images = $this->getImagesArray();
		foreach ($images as $num => $im) {
			$parentForm = "Ext.getCmp($(this).parents('.x-panel')[0].id)";
			$html .= "<table cellpadding=0 celspacing=0><tr><td><img value=$num src={$c['webprojects_www']}mystery_shopping/$im /></td><td valign=top><img onclick=\"$parentForm.deleteImage($num);\" src={$c['warpit_www']}_img/remove_cancel.png /></td></tr></table>";
			
			//$html.= "<div style='width:16;height:16;' onclick=\"$parentForm.deleteImage($num);\" class=icon_red_delete ></div><img value=$num src={$c['webprojects_www']}mystery_shopping/$im /><br>";
		}
		return $html;
	}
}

$manipulator = new mysteryShopMan($db,$tableName);
$manipulator->id_langage = $id_language;
$comm = $_POST['action'].'Action';
if(method_exists($manipulator,$comm))
	echo $manipulator->$comm();
else 
{	
	Echo '{success:false,error:"Unknown action!"}';	
	
}
?>