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

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


class ExtraVarMan extends GridDataManipulator
{
	public function updateAction()
	{
		$tmp = $this->db->get($this->table,$_POST['id'],"id_project,var_name,var_type");
		
		$editField = $_POST['field'] == 'var_name';
		
		if($editField && !$_POST['value'])
			return "{success:false, error: 'Field name must not be empty!'}";
			
		extract($tmp);
		include_once(PATH_TO_ROOT."config.php");
		
		
		$var_type = getDataType($editField ?  $var_type : $_POST['value'] );
		
		$projectName = $this->db->get('_Projects',$id_project,'proj_name');
		
		$sql = "ALTER TABLE $projectName"."_structure ";
		
		//if old fields exist we change the field...otherwise we add it!
		if($editField || $var_name)
		{
			if($var_name)
			{
				$sql .= "CHANGE EV_$var_name ";
			}
			else
			{
				$sql .= "ADD ";
			}
			if( $editField )
			{
				$sql .=  'EV_'.$_POST['value']." ".$var_type;
			}
			else
			{
				$sql .=  'EV_'.$var_name." ".$var_type;
			}
			try {
				$this->db->SQLexecute($sql);
			}
			catch (Exception $e)
			{
				return $this->db->JsonError();
			}
		}
			
		return parent::updateAction();
		
	}
	public function deleteAction()
	{
		$tmp = $this->db->get($this->table,$_POST['ids'],"id_project,var_name");
			
		extract($tmp);
		$projectName = $this->db->get('_Projects',$id_project,'proj_name');
		if($var_name)
		{
			$sql = "ALTER TABLE $projectName"."_structure DROP EV_$var_name";
			try {
				$this->db->SQLexecute($sql);
			}
			catch (Exception $e)
			{
				return $this->db->JsonError();
			}
		}
		return parent::deleteAction();	
		
		
	}
}

$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

$project = $_POST['RMtable'];

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