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

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


class bqwcTreeDataMan extends TreeDataManipulator 
{
	
	function selectAction()
	{
		
		require_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
		
		$parent = $_POST['node'];
		
		$checked = $_POST['checked'];
		$sql = $_REQUEST['SQL'].' WHERE id_sup = '.$parent.' ';
		
		if(isset($_POST['filter']) && $_POST['filter'] != '')
		{
			$fil = $_POST['filter'];
			$sql.= "AND (idLab LIKE '%$fil%' OR is_leaf = 0)";	
		}
		
		
		if (isset($_POST['RMorder'])) {
			$this->order[] = $_POST['RMorder'];
		} else {
			$this->order[] = 'orderBy';
		}
		if (isset($this->order))
		{
			$sql .= 'ORDER BY '.implode(',',$this->order);
		}
		
		
		If (!$res = $this->db->SQLexecute($sql)) 
		{
			
				Echo '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
		}
		else 
		{
		
			// display each child
			while ($row = $this->db->fetchAssoc($res)) {
				// Response parameters.
				$path = array();
				
				
				if($_REQUEST['boldRoots'] && $parent == 0)
				{
					$path['cls']		= 'treeFontBold';
					//$path['children'][] = array(text=>'1');
					//$path['children'][] = array(text=>'2');
				}
				
				$path['text']		=html_entity_decode($row['idLab']);
				
				$path['id']			= $row['id'];
				$path['isQuestion'] = $row['is_leaf']; 
				
			//	$path['cls'] = 'textSize';
				// Check if node is a leaf or a folder.
				
				
				
				if(!$path['isQuestion']){
						$path['leaf']	= false;
						//temporarly till order folder works!
						//$path['draggable'] = false;
						if(isset($_POST['filter']))
						{
							$_POST['node'] = $row['id'];
							if(!$path['children'] = json_decode( $this->selectAction(),true ))
							{
								continue;
							}
						}
						
					} else{
						
						$path['leaf']	= true;
						$path['checked'] = $checked[ $row['tip_sql'] ] == 'true' ? true : false ;
						
						$path['q_id'] = $row['q_id'];
						if(isset($row['tip_sql']))
							$path['qType'] = $row['tip_sql'];
						
						
					}
				if(isset($row['node_img']) && $row['node_img']!= '')
				{
					$path['icon'] = $row['node_img'];
				}
				else 
				{			
					if(!$path['isQuestion']){
						$path['iconCls']	= 'folder';
						
					} else{
						
						$q = Question::createQuestion($path['qType']);
						$path['iconCls'] = $q->getIconCls();
						
						
						
						
					}
				}
				
			//	if (isset($row['q_pos']))
	 		//		$path['q_pos'] = $row['q_pos'];
				if($_POST['structure'] && $row['hasStructure'] == 0 && $path['isQuestion'])
	 				$path['cls'] = 'tree-text-red';
				// call this function again to display this
				// child's children
				$nodes[] = $path;
			}
			
			//return $nodes;
		}
		return json_encode($nodes);
	}

	function saveFilterAction()
	{
		$userId = $_POST['isPublic'] ? 0 : $_SESSION['UserInfo']['id'];
		$projectId = $_POST['projectId'];
		$name = $_POST['name'];
		$value = mysql_real_escape_string($_POST['value']);
		$filterType = $_POST['isCommon' ] ? 0 : $_POST['filterType'];
		
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = "REPLACE INTO _userStatFilters (id_user,id_project,name,filter,filterType ) ". 
		"VALUES ( $userId, $projectId , '$name','$value', $filterType )";
		if($this->db->SQLexecute($sql))
		{
			return '{success:true}';
		}
		else {
			return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
		}
		
		
	}
	function showFilterAction()
	{
		$userId = $_SESSION['UserInfo']['id'];
		$projectId = $_POST['projectId'];
		$filterType = $_POST['filterType'];
		
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = "SELECT id,name,filter FROM _userStatFilters WHERE (id_user = $userId OR id_user=0) AND ( filterType = $filterType OR filterType = 0 ) AND id_project = $projectId";
		
		$this->arr = array();
		If (!$this->rs = $this->db->SQLexecute($sql)) {
			
				echo '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
			
			}else{
				
				while($obj = $this->db->fetchAssoc($this->rs)){
					$this->arr[] = $obj;
				}
				$echo = '{success:true';
				$echo.= ', STATEMENT: "'.$sql.'",rows: '.json_encode($this->arr);
				$echo.='}';
				return $echo;
			
		}
		
	}
	function compareUsersAction()
	{
		$idProject = $_POST['id_project'];
		$tableName = $this->db->get('_Projects',$idProject,'proj_name',DB_WARPIT_WEBCATI_BASE);
		
		$arr = array(array('id' => 0, 'name' => $_POST['special'] ? $_POST['special'] : "--- Select user ---") ) ;
		
		if($_POST['flagbad'])
		{
			$cnd = " AND flag_bad=101";
		}
		
		if($_POST['hasUnique'])
		{
			$sql = "SELECT id, uniqueAddress_1 as name FROM $tableName"."_structure WHERE status=1 AND (user_type=1 OR user_type=0)$cnd";
			$res = $this->db->SQLexecute($sql);
			
			while ($row = $this->db->fetchAssoc($res)) {
				
				$arr[] = $row;
			}
		}
		else
		{
			$sql = "SELECT DISTINCT a.id,a.username as name FROM ".DB_WARPIT_MAIN."._user a INNER JOIN ".DB_WARPIT_WEBCATI_BASE.".$tableName"."_structure b ON a.id = b.user_id AND user_type = 1 AND status = 1$cnd";
			//echo "/*$sql*/";
			$res = $this->db->SQLexecute($sql);
			
			while ($row = $this->db->fetchAssoc($res)) {
				$row['id'] = 'admin_'.$row['id'];
				$arr[] = $row;
			}
			
			$sql = "SELECT DISTINCT a.id,a.username as name FROM _Interviewer a INNER JOIN $tableName"."_structure b ON a.id = b.user_id AND user_type = 0 AND status = 1$cnd";
			//echo "/*$sql*/";
			$res = $this->db->SQLexecute($sql);
			while ($row = $this->db->fetchAssoc($res)) {
				$arr[] = $row;
			}
		}
		return "{success:true, rows: ".json_encode($arr)." }";
		
	}
	function userRecordsAction()
	{
		$idProject = $_POST['id_project'];
		$tableName = $this->db->get('_Projects',$idProject,'proj_name',DB_WARPIT_WEBCATI_BASE);
		
		if($_POST['flagbad'])
		{
			$cnd = " AND flag_bad=101";
		}
		
		
		$id = $_POST['id_record'];
		if(substr($id,0,5) == 'admin')
		{
			$userType = 1;
			$id = substr($id,6);
		}
		else 
			$userType = 0;
			
		$arr = array();
		$sql = "SELECT id, id as name,flag_bad FROM $tableName"."_structure WHERE user_id = $id AND user_type = $userType AND status = 1$cnd";
		$res = $this->db->SQLexecute($sql);
		while ($row = $this->db->fetchAssoc($res)) {
			$arr[] = $row;
		}
		
		return "{success:true, rows: ".json_encode($arr)." }";
		
	}
	function confirmRecordAction()
	{
		$idProject = $_POST['id_project'];
		$tableName = $this->db->get('_Projects',$idProject,'proj_name',DB_WARPIT_WEBCATI_BASE);
		
		$idRecord = $_POST['id_record'];
		$val = $_POST['value'] == 1 ? 101 : 99;
		$sql = "UPDATE $tableName"."_structure SET flag_bad = $val WHERE id = $idRecord";
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$this->db->SQLexecute($sql);
		
		return "{success:true}";
	}
	function getNextGraphAction()
	{
		include(PATH_TO_ROOT.'webcati/_forms/statistics/showGraph.php');
		//Echo '{success:true,error:"OK!"}';
	}
}

$db->ChangeDatabase($_POST['database']);
$tableName = $_POST['RMtable'];


$manipulator = new bqwcTreeDataMan($db,$tableName.'_tree');
$manipulator->tableGrid = $tableName;
$manipulator->tableTree = $tableName.'_tree';

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