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

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

class SampleTemplateMan extends TreeDataManipulator{
	public function insertItemAction()
	{
		$ret = parent::insertItemAction();
		if($_POST['addLeaf']) //umm...we create table and, umm...update record in tree and stuff :)
		{
			
			$idTemplate = trim ( $_POST['templateId'] );
			if(!$idTemplate)
			{
				$treeWhere = 'id_user = '.$_SESSION['UserInfo']['id'];
				$tableName = 'samplingDataUser___'.$_SESSION['UserInfo']['id'];
			}
			else
			{
				$treeWhere = 'id = '.$idTemplate;
				$tableName = 'samplingDataTemplate___'.$idTemplate;
			}
			
			$newTable = "samplingDataTemplate___".$this->insertId;
			$sql = "CREATE TABLE $newTable SELECT * FROM $tableName";
			$this->db->SQLexecute($sql);
			
			$res = $this->db->get('_SamplingTemplates',$treeWhere);
			$res = $res[0];
			
			$this->db->SQLexecute("ALTER TABLE  $newTable ADD PRIMARY KEY (  `id` )");
			$this->db->SQLexecute("ALTER TABLE  $newTable CHANGE  `id`  `id` INT( 11 ) NOT NULL AUTO_INCREMENT");
			
			$sql = "UPDATE  _SamplingTemplates SET id_group = '".$res['id_group']."',id_fields = '".$res['id_fields']."' WHERE id = $this->insertId";
			$this->db->SQLexecute($sql);
		}
		return $ret;
	}
	public function deleteAction()
	{
		
		$this->db->SQLexecute("DROP TABLE IF EXISTS samplingDataTemplate___".$_POST['nodeId']);
			
		return parent::deleteAction();
	}
	
}
	
	
	$db->ChangeDatabase($_POST['database']);
	
	$manipulator = new SampleTemplateMan($db,$_POST['RMtable']);	
	$comm = $_POST['action'].'Action';
	if(method_exists($manipulator,$comm))
		echo $manipulator->$comm();
	else 
	{
		echo '{success:false,error:"Unknown action!"}';	
	}

?>