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

include_once (PATH_TO_ROOT."/mystery/init.php");
include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.treeData.php");
include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.gridData.php");
require_once (PATH_TO_ROOT.'_class/createQuestion/Question.php');
		
class bqwcTreeDataMan extends TreeDataManipulator 
{
	
	public function selectAction()
	{
		if($this->table == '_Groups')
		{
			if($_POST['node'] > 0)
				$_POST['SQL'] = "SELECT a.id,b.proj_name AS idLab,a.is_leaf FROM $this->table a INNER JOIN ".DB_WARPIT_WEBCATI_BASE."._Projects b ON a.id_project = b.id";
			else {
				//echo "/* noter sem */";
				if ( $_SESSION['UserRights'][47] ) {
					$sql = " ( SELECT id_permission FROM Warpit._PermissionLink WHERE p_type = 10 AND id_user = ".$_SESSION['UserInfo']['id']." AND allow = 1 ) 
							UNION 
							(SELECT id FROM ".DB_WARPIT_MYSTERY."._Groups WHERE is_leaf = 0 AND id_sup = 0 AND id_user = ".$_SESSION['UserInfo']['id']." ) ";
					$res = $this->db->SQLexecute($sql);
					while ($zad = $this->db->fetchAssoc($res)) {
								$_xStatProjects[$zad['id_permission']] = $zad['id_permission'];			
					}
					if ($_xStatProjects) {
						$_POST['SQL'] = "SELECT id,idLab,is_leaf FROM ".DB_WARPIT_MYSTERY."._Groups ";
						$_POST['SQLwhere'] = " id IN (".implode(",",$_xStatProjects).")";
					}
					//echo "/* ".$sql." */";
				}
			}
		}
		else if($this->table == 'nimaVeze') return '[]';
		else 	//a createt table
			$_POST['attr'] = 'qName,qType';
		
			
		parent::selectAction();
		if(substr($this->table,0,5) == "Analy")
		{
			foreach ($this->nodes as &$q) {
				if($q['leaf'])
				{
					$q['iconCls'] = Question::createQuestion($q['qType'])->getIconCls() ;
				}
			}
			
		}
		
		return json_encode($this->nodes);
	}
	
	public function addProjectsAction()
	{
		$projs = explode(',',$_POST['projects']);
		$id= $_POST['parentId'];
		foreach ($projs as $pr) {
			$values[] = "($id,$pr,$this->user,1)";
		}
		$this->db->SQLexecute("INSERT INTO $this->table(id_sup,id_project,id_user,is_leaf) VALUES ".implode(',',$values));
		
		return "{success:true}";
		
	}
	
	public function hasQuestion($question,$tip)
	{
		foreach ($this->projects as $proj) {
			$sql = $this->db->SQLexecute("SELECT * FROM $proj WHERE q_name='$question' AND tip_sql = $tip ");
			if(!$this->db->fetchRow($sql))
				return false;
			
		}
		return true;
	}
	
	public function cleanTable($table)//remves all folders with no children
	{
		$sql = $this->db->SQLexecute("SELECT id FROM `$table` a WHERE is_leaf= 0 AND (SELECT COUNT(*) FROM `$table` b WHERE b.id_sup = a.id ) = 0");
		while ($row = $this->db->fetchRow($sql))
			$ids[] = $row[0];
		
		if($ids)
		{
			$this->db->SQLexecute("DELETE FROM $table WHERE id IN (".implode(',',$ids).")");
			$this->cleanTable($table);
		}
			
	}
	public function analyzeAction()
	{
		if(!$_POST['groups']) return "{success:false}";
		$groups = explode(',',$_POST['groups']);
		$tableName = "Analyze_".implode('_',$groups);
		
		$this->db->SQLexecute("DROP TABLE IF EXISTS $tableName");
		$this->db->SQLexecute("CREATE TABLE `$tableName` (
				  `id` int(11) NOT NULL AUTO_INCREMENT,
				  `id_sup` int(11) NOT NULL,
				  `idLab` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
				  `is_leaf` tinyint(1) NOT NULL,
				  `orderBy` int(11) NOT NULL,
				  `qName` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
				 `qType` int(11) NOT NULL,
				  PRIMARY KEY (`id`)
				) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
			
	
		$sql = $this->db->SQLexecute("SELECT id_project FROM _Groups WHERE id_sup IN ({$_POST['groups']})");
		while($row = $this->db->fetchRow($sql))
		{
			$projectIds[] = $row[0];
		}
		//let's get all fodlers/questions from first project
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$this->projects = $this->db->get('_Projects',"id IN (".implode(',',$projectIds).")",'proj_name');
		$projFirst = array_shift($this->projects);
		$langugae = $this->db->get('_Projects',$projectIds[0],'language');
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
		$sql = $this->db->SQLexecute("SELECT a.id,a.id_sup,a.idLab,a.is_leaf,a.orderBy,b.q_name,b.tip_sql FROM $projFirst"."_tree a left join $projFirst b ON a.id = b.id");
		while ($row = $this->db->fetchAssoc($sql))
		{
			//ce je folder, damo avtomatsko not...ce ni, moramo za vse projekte preverit
			if($row['is_leaf'])
			{
				if($this->hasQuestion($row['idLab'],$row['tip_sql']))
				{
					$qText = $this->db->fetchRow( $this->db->SQLexecute("SELECT lngText FROM $projFirst"."_language WHERE id_language=$langugae AND id_question = {$row['id']} AND id_text_type=2"));
					$qText = $qText[0];
					$row['idLab'] .= ' '. strip_tags( $qText);
					
					$values[] = "('".implode("','",$row)."')";
				}
			}
			else {
				$values[] = "('".implode("','",$row)."')";
			}
		}
		$this->db->ChangeDatabase(DB_WARPIT_MYSTERY);
		
		$this->db->SQLexecute("INSERT INTO $tableName VALUES ".implode(',',$values));
		
		$this->cleanTable($tableName);
		return "{success:false, table: '$tableName' }";
	
	}
	public function createStatisticAction()
	{
		
		
		$groups = explode('_',$_POST['projTable']);
		array_shift($groups);
		//get all projects for each group
		
		foreach ($groups as $gIndex => $gId) {
			$sql = $this->db->SQLexecute("SELECT a.id,b.proj_name AS idLab FROM _Groups a INNER JOIN ".DB_WARPIT_WEBCATI_BASE."._Projects b ON a.id_project = b.id WHERE a.id_sup = $gId");
			while ($row = $this->db->fetchRow($sql))
			{
				$grp[$gIndex][] = $row[1];
			}
		}
			
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
		$cols = explode(',',$_POST['columns']);
		//we have an example project to take our questions and shit
		$proj	= $grp[0][0];	
		foreach ($cols as $col) {
			$qId = $this->db->get($proj,"q_name='$col'");
			$q = Question::createQuestionFromTable($this->db,$proj,$qId[0]['id']);
			$ansArr= $q->getAnswerArray();
			
		}
		
		$row = $_POST['row'];
		$qId = $this->db->get($proj,"q_name='$row'");
		$q = Question::createQuestionFromTable($this->db,$proj,$qId[0]['id']);
		$ansArr= $q->getAnswerArray();
		print_r($ansArr);
		
	}

	
}


class preper extends GridDataManipulator 
{

	
}

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

if($_POST['RMcomp'] == 'grid')
$manipulator = new preper($db,$tableName);
else
$manipulator = new bqwcTreeDataMan($db,$tableName);

$manipulator->user = $_SESSION['UserInfo']['id'];

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