<?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");
include_once(PATH_TO_ROOT."config.php");

$interviewer = '_Interviewer';
/**
 * @var fieldEditManipulator
 */
$intStructure = '_InterviewerStructure';


class fieldEditManipulator extends TreeDataManipulator
{
	
	function insertFieldAction()
		{
			
		$parent = $_POST['parId'];
		$newId = $_POST['nodeId'];
		$text = $_POST['nodeText'];
		$type = $_POST['nodeType'];
		$closed = $_POST['closed'];
		//$orderTree = $_POST['tPos'];
		//$orderGrid = $_POST['qPos'];
		$rs = $this->db->SQLexecute("SELECT id FROM $this->table WHERE field_name = '$text' ");
		if($this->db->fetchAssoc($rs) )
		{
			return "{success:false,error:'Name already exists!'}";
		}
		
		if($newId == 0)
		{
			$orderTree = 1;
		}
		else 
		{
				
				$getNewSql = "SELECT orderBy,id_sup AS par FROM $this->table WHERE id = $newId";
			
				If (!$rs = $this->db->SQLexecute($getNewSql)) {
						
							
							return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getNewSql.'"}';
							
						}	
				if( !$row = $this->db->fetchAssoc($rs))
				{
							return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getNewSql.'"}';
							
				}
				$orderTree = $row['orderBy'];
						
				//if the target is a leaf we put the new item after it
				if($_REQUEST['isTargetF'])
				{
					$orderTree++;
				}
				//if folder is closed we put the item after the folder
				elseif ($closed == 'true')
				{
					$orderTree++;
				}
				//other wise we put the item on the first place in the folder
				else 
					$orderTree = 1;
		
		}
		
		$dataType = getDataType($type);
		
		
		
		
		$sql[] = "ALTER TABLE  `_Interviewer` ADD  `$text` $dataType";
		
			
		//we increase order in tree (!!!NEW!!!) for this parent only!!!!
		$sql[] = "UPDATE $this->table SET orderBy = orderBy+1 WHERE orderBy >= $orderTree AND id_sup = $parent";

		$sql[] = "INSERT INTO $this->table(id_sup,orderBy,field_name,field_text,data_type,is_leaf) VALUES( $parent ,$orderTree,'$text','$text',$type,true ) ";

		if (!$this->db->SQLbegin())
		{
			return '{success:false,error:"Transakcije niso omogocone"}';	
		}
		foreach ($sql as $sqlStatemens) {
			If (!$this->db->SQLexecute($sqlStatemens)) {
				
					$this->db->SQLrollback();
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
				}	
		}
		
			$id = $this->db->GetLastInsertId();
			$userId = $_SESSION['UserInfo']['id'];
			
			if($this->db->NumRows( $this->db->SQLexecute("SELECT * FROM `_InterviewerFieldOrder`")  ) > 0)
			{
			
			$sqlStatemens = "INSERT INTO _InterviewerFieldOrder (user_id,field_id,orderBy,is_hidden) 
				SELECT user_id,$id,max(orderBy)+1,user_id != $userId AND user_id!=0 FROM `_InterviewerFieldOrder` GROUP BY user_id ";
			If (!$this->db->SQLexecute($sqlStatemens)) {
				
					$this->db->SQLrollback();
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
				}
			
			}
			else 
			{
				$this->db->SQLexecute("INSERT INTO _InterviewerFieldOrder (user_id,field_id,orderBy,is_hidden)VALUES(0,$id,1,0) ");
			}
				
				
			$this->db->SQLcommit();
			//now lets try some dirty dirty updating of the orderBy table!
			$this->curOrd = 1;
			$this->dirtyDirtyUpdate(0);
			
			
			return '{success:true,insertId:'.$id .'}';	
		}
		
	function dirtyDirtyUpdate($idSup)
	{
		$sql = "SELECT * FROM $this->table WHERE id_sup = $idSup ORDER BY orderBy";
			$rs = $this->db->SQLexecute($sql);
				while($row = $this->db->fetchAssoc($rs) )
				{
					if( $row['is_leaf'] )
					{
						
						$sqlStatemens = "UPDATE _InterviewerFieldOrder SET orderBy = $this->curOrd WHERE user_id = 0 AND field_id = ".$row['id'];
						If (!$this->db->SQLexecute($sqlStatemens)) {
							$this->db->SQLrollback();
							return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
						}
						$this->curOrd++;
					}
					else 
					{
						
						$this->dirtyDirtyUpdate($row['id']);
					}
					
				}
	}
	
	
	function insertGroupAction()
	{
	//	$orderTree = $_POST['tPos'];
		$id = $_POST['nodeId'];
		$closed = $_POST['closed'];
		$parent = $_POST['parId'];
		
		if($id == 0)
		{
			
			$orderTree = 1;
		}
		else 
		{
		
			if (!$_POST['isTargetF'] && !$closed)
			{
			
				$orderTree = 1;
			}
			else
			{
				$lastSQL = "SELECT orderBy FROM $this->table WHERE id = $id";
			
				$rs = $this->db->SQLexecute($lastSQL);
				if($row = $this->db->fetchAssoc($rs) )
				{
					$orderTree = $row['orderBy']+1;
				}
				else 
				{
					return '{success:false,error:"'.$this->db->GetError().'",statement:"'.$lastSQL.'"}';		
				}
			}
		}
		
		$sql[] = "UPDATE $this->table SET orderBy = orderBy+1 WHERE orderBy >= $orderTree AND id_sup = $parent";
		
		$sql[] = "INSERT INTO $this->table(id_sup,orderBy,field_name,is_leaf) VALUES( $parent ,$orderTree,'".$_POST['nodeText']."',false ) ";
		foreach ($sql as $sqlStatemens) {
				If (!$this->db->SQLexecute($sqlStatemens)) {
					
						$this->db->SQLrollback();
						return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
					}	
			}
			
			return '{success:true,insertId:'.$this->db->GetLastInsertId() .'}';	
		
	}
	function deleteAction()
	{
			if ($_POST['isTargetF'])
			{
				$fieldId = $_POST['nodeId'];
				$sql = "SELECT field_type,field_name FROM $this->table WHERE id = ".$_POST['nodeId'];
				If (!$rs = $this->db->SQLexecute($sql)) {	return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';	}
				$row = $this->db->fetchArray($rs);
				$dType = $row[0];
				$field = $row[1];
				If (!$this->db->SQLexecute("ALTER TABLE  `_Interviewer` DROP  ".$_POST['nodeText'])) {
					
						return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
					}	
				//we need to get the order by for each user so that we can repair order
				$sql = "SELECT user_id,orderBy FROM `_InterviewerFieldOrder` WHERE field_id = $fieldId AND user_id != 0";	
				If (!$res =$this->db->SQLexecute($sql)) {	return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}
				while ($row = $this->db->fetchArray($res))
				{
					$userTmp = $row['user_id'];
					$orderTmp = $row['orderBy'];
					$sql = "UPDATE _InterviewerFieldOrder SET orderBy = orderBy-1 WHERE user_id = $userTmp AND orderBy > $orderTmp"; 
					If (!$this->db->SQLexecute($sql)) {	return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}
				
				}
				
				$sqlStatemens = "DELETE FROM _InterviewerFieldOrder WHERE field_id = ".$_POST['nodeId'];
				If (!$this->db->SQLexecute($sqlStatemens)) {return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';	}
				if($dType == 2 || $dType == 3 || $dType == 4)
				{
					if($dType == 2)
					{
						  //we had checkboxes, so now we have to destroy the extra structures created
						  // OR we selected checkboxes and must create the extra structures	
							$sql = "SELECT * FROM user_input_labels WHERE lab_field = ".$_POST['nodeId'];
							If (!$rs = $this->db->SQLexecute($sql)) {	return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
							}else{
								while ($row = $this->db->fetchAssoc($rs))
								{
									$drop[] = "DROP ".$field.'_'.$row['lab_code'];
								}
							}
							if($drop)
							{
								$sql = "ALTER TABLE _Interviewer ".implode(',',$drop);
								If (!$rs = $this->db->SQLexecute($sql)) {
									return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
								}
							}
					}
					$sql = "DELETE FROM user_input_labels WHERE lab_field = ".$_POST['nodeId'];
					If (!$rs = $this->db->SQLexecute($sql)) {
						return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
					}
					
					
					
				}
				//in user projects we have the same order! 
					//we need to get the order by for each user so that we can repair order
					$sql = "SELECT id_user,orderBy FROM `_UserProjectFieldOrder` WHERE id_field = $fieldId AND field_type = 2 AND id_user != 0";	
					If (!$res =$this->db->SQLexecute($sql)) {	return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}
					while ($row = $this->db->fetchArray($res))
					{
						$userTmp = $row['id_user'];
						$orderTmp = $row['orderBy'];
						$sql = "UPDATE _UserProjectFieldOrder SET orderBy = orderBy-1 WHERE id_user = $userTmp AND orderBy > $orderTmp"; 
						If (!$this->db->SQLexecute($sql)) {	return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}
					
					}
					
					$sqlStatemens = "DELETE FROM _UserProjectFieldOrder WHERE field_type = 2 AND id_field = ".$_POST['nodeId'];
					If (!$this->db->SQLexecute($sqlStatemens)) {return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';	}
					
					
				//now lets try some dirty dirty updating of the orderBy table!
				$ret = parent::deleteAction();
				$this->curOrd = 1;
				$this->dirtyDirtyUpdate(0);
				return $ret;
					
				
			}
			
			return parent::deleteAction();
			
	}
	
	function moveNodeAction()
	{
		parent::moveNodeAction();
		
		$this->curOrd = 1;
		$this->dirtyDirtyUpdate(0);
		return "{success: true,test:'lalala'}";
		
	}
	
	//the function to update field name and field type, which also tries to change the table column!
	function updateNameAction()
	{
		if( $_POST['field'] == 'field_name')
		{
			$field = $_POST['value'];
			$type = getDataType( $_POST['dataType']  );
		}
		else 
		{
			$field = $_POST['fieldName'];
			$type = getDataType( $_POST['value']  );
		}
		$oldField = $_POST['oldName'];
		
		$dType = $_POST['displayType'];
		
		
			if($dType == 2)
			{
				  //we must also rename the checkbox extra fields
					$sql = "SELECT * FROM user_input_labels WHERE lab_field = ".$_POST['id'];
					If (!$rs = $this->db->SQLexecute($sql)) {	return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
					}else{
						while ($row = $this->db->fetchAssoc($rs))
						{
							$drop[] = "CHANGE ".$oldField.'_'.$row['lab_code']." ".$field.'_'.$row['lab_code']." $type NOT NULL";
						}
					}
					if($drop)
					{
						$sql = "ALTER TABLE _Interviewer ".implode(',',$drop);
						If (!$rs = $this->db->SQLexecute($sql)) {
							return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
						}
					}
			}
					
		
		
		If (!$this->db->SQLexecute("ALTER TABLE  `_Interviewer` CHANGE `$oldField` `$field` $type"))
					{
					
						return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
					}	
		
		$sql = 'UPDATE '.$_REQUEST['RMtable']." SET ".$_REQUEST['field']." = '".$_REQUEST['value']."' WHERE id = ".$_REQUEST['id'];
		If (!$rs = $this->db->SQLexecute($sql)) {
				
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
				
				}else{
					
				
				
				return '{success:true,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
			}
	}	
	
	//the function to update field display type, which also tries to delete any data in user_input_labels!
	function updateDisplayTypeAction()
	{
		
			$field = $_POST['fieldName'];
			$newVal = $_POST['value'];
			$oldVal = $_POST['oldVal'];
			if($oldVal == 2 || $newVal == 2)
			{ //we had checkboxes, so now we have to destroy the extra structures created
			  // OR we selected checkboxes and must create the extra structures	
				$sql = "SELECT * FROM user_input_labels WHERE lab_field = ".$_POST['id'];
				If (!$rs = $this->db->SQLexecute($sql)) {
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
				}else{
					while ($row = $this->db->fetchAssoc($rs))
					{
						if($oldVal == 2)
							$drop[] = "DROP ".$field.'_'.$row['lab_code'];
						else 
							$drop[] = "ADD ".$field.'_'.$row['lab_code'] .' INT NOT NULL';
						
					}
				}
				if($drop)
				{
					$sql = "ALTER TABLE _Interviewer ".implode(',',$drop);
					If (!$rs = $this->db->SQLexecute($sql)) {
						return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
					}
				}
			}
			if($newVal != 2 && $newVal != 3 && $newVal != 4  )
			{ //a type has been selected that does not require user_input_labels! so we delete zem!
				$sql = "DELETE FROM user_input_labels WHERE lab_field = ".$_POST['id'];
				If (!$rs = $this->db->SQLexecute($sql)) {
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
				}
			}
	
		/*If (!$this->db->SQLexecute("ALTER TABLE  `_Interviewer` CHANGE `$oldField` `$field` $type NOT NULL"))
					{
					
						return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
					}*/	
		
		$sql = 'UPDATE '.$_REQUEST['RMtable']." SET ".$_REQUEST['field']." = '".$_REQUEST['value']."' WHERE id = ".$_REQUEST['id'];
		If (!$rs = $this->db->SQLexecute($sql)) {
				
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
				
				}else{
					
				
				
				return '{success:true,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
			}
	}	
	
	

}

class gridFieldEditManipulator extends GridDataManipulator
{
	
	function selectAction()
	{
		$result = parent::selectAction();
		//if checkbox is select we send an extra paramers
		if($_POST['checkBox'])
		{
			$fName = $_POST['fieldName'];
			
			//we must check the default values of the table fields, to return the proper value
			$sql = "SHOW COLUMNS FROM _Interviewer LIKE '{$fName}_%' ";
			If (!$this->rs = $this->db->SQLexecute($sql)) {
			
				return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
			
			}
				
			while($row = $this->db->fetchAssoc($this->rs)){
				$allFields[ $row['Field']  ] = $row['Default'];		
			}
			foreach ($this->arr as $key => &$value )
			{
				$ch = $allFields[ $fName.'_'.$value['lab_code'] ];
				if($ch == 0)
					$value['cb_checked'] = 0;
				else
					$value['cb_checked'] = 1; 
			}
			return "{success:true, rows:".json_encode($this->arr)  ." }";
				
		}
		else {
			return $result;
		}
		
	}
	
	function deleteAction()
	{
		$sql = "SELECT language,lab_field,lab_position FROM $this->table WHERE id = ".$_POST['id'];
		If (!$rs = $this->db->SQLexecute($sql))
					{
					
						return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
					}
		$row = $this->db->fetchArray($rs);
		$lan = $row[0];
		$fld = $row[1];
		$pos = $row[2];
		
		$sql = "UPDATE $this->table SET lab_position = lab_position -1 WHERE language = $lan AND lab_field = $fld AND lab_position > $pos";
		If (!$this->db->SQLexecute($sql))
				{
				
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
				}
		
		return parent::deleteAction();
	}
	
	
	function cbAddAction()
	{
		$text = $_POST['nodeText'];
		$type = $_POST['nodeType'];
		
		$dataType = getDataType($type);
		$sql = "ALTER TABLE  `_Interviewer` ADD  `{$text}_0` $dataType NOT NULL";
		If (!$this->db->SQLexecute($sql)) {
				
					$this->db->SQLrollback();
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
				}
		return "{success:true}";
		
	}
	function cbRenameAction()
	{
		$text = $_POST['nodeText'];
		$type = $_POST['nodeType'];
		$oldVal = $_POST['oldVal'];
		$newVal = $_POST['newVal'];
		if($oldVal == '')
			$oldVal = 0;
		if($newVal == '')
			$newVal = 0;
		
		$dataType = getDataType($type);
		$sql = "ALTER TABLE  `_Interviewer` CHANGE  `{$text}_$oldVal` `{$text}_$newVal` $dataType NOT NULL";
		If (!$this->db->SQLexecute($sql)) {
				
					$this->db->SQLrollback();
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
				}
		return "{success:true}";
	}
	function cbRemoveAction()
	{
		$text = $_POST['nodeText'];
		$nId = $_POST['nodeId'];
		if($nId == '')
			$nId = 0;
		$dataType = getDataType($type);
		$sql = "ALTER TABLE  `_Interviewer` DROP  `{$text}_$nId` ";
		If (!$this->db->SQLexecute($sql)) {
				
					$this->db->SQLrollback();
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
				}
		return "{success:true}";
		
	}
	
	function cbCheckedAction()
	{
		$text = $_POST['nodeText'];
		$type = $_POST['nodeType'];
		$nodeId = $_POST['nodeId'];

		$newVal = $_POST['newVal']*$nodeId;
		
		if($nodeId == '')
			$nodeId = 0;
		
		$dataType = getDataType($type);
		$sql = "ALTER TABLE  `_Interviewer` CHANGE  `{$text}_$nodeId` `{$text}_$nodeId` $dataType NOT NULL DEFAULT '$newVal'";
		If (!$this->db->SQLexecute($sql)) {
				
					$this->db->SQLrollback();
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
				}
		return "{success:true,STATEMENT : \"$sql\"}";
	}
	
	function importAction() {
		
		$tmp = explode("/",$_POST['import_value']);
		if ($tmp) {
			foreach ($tmp as $val) {
				$tmp1 = explode(" ",$val,2);
				$sql = 	" INSERT IGNORE INTO ".DB_WARPIT_USERSPOOL.".user_input_labels SET 
								language = ".$_POST['language'].", 
								lab_field = ".$_POST['field'].",
								lab_code = ".$tmp1[0].",
								lab_label = '".trim($tmp1[1])."',
								lab_position = ".$tmp1[0];
				
				$this->db->SQLexecute($sql);
			}
		}
		
		return "{success:true}";
	}
	
}

	

$db->ChangeDatabase($_REQUEST['database']);

if($_POST['RMcomp']=='tree')
	$manipulator = new fieldEditManipulator($db,$_REQUEST['RMtable']);
else 
{
	$manipulator = new gridFieldEditManipulator($db,$_REQUEST['RMtable']);
}
$comm = $_REQUEST['action'].'Action';
if(method_exists($manipulator,$comm))
	echo $manipulator->$comm();
else 
{
	
	echo '{success:false,error:"Unknown action!"}';	
	
}


?>