<?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."_ajaxManipulators/_class/class.formData.php");
include_once(PATH_TO_ROOT."config.php");

$interviewer = '_Interviewer';
$intStructure = '_InterviewerStructure';

class telManagmentManipulator extends TreeDataManipulator
{
	public $tableAddon;
	function selectAction()
	{
			
		$parent = $_POST['node'];
		$isTable = $_POST['isTable'];
		if($isTable)
		{
			$sql = 'SELECT * FROM '.$this->table.'Addon WHERE id_telbaza = '.$parent.' ';
		}
		else 
		{
			$sql = 'SELECT * FROM '.$this->table.' WHERE id_sup = '.$parent.' ';
		
		}
		 
		if(isset($_POST['filter']) && $_POST['filter'] != '')
		{
			$fil = $_POST['filter'];
			$sql.= "AND id_lab LIKE '%$fil% '";	
		}
		
		$sql .= ' ORDER BY orderBy';
		
		If (!$res = $this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';	}
		else 
		{
		
			// display each child
			while ($row = $this->db->fetchAssoc($res)) {
				// Response parameters.
				$path = array();
				$path['text']		=html_entity_decode( $row['name'] );
				$path['id']			= $row['id'];
				//becaouse we alter the IDs to get unique IDs for the tree we save the original ID
				$path['origId']    = $row['id'];
				if($row['is_leaf'] && !$isTable )
				{
					$path['isTable'] = true;
					$path['leaf'] = false;
				//	$path['allowDrop'] = false;
					$path['iconCls'] = 'icon_database';
					
				}
				else if($isTable)
				{
					$path['leaf']=true;
					$path['isField']=true;
					$path['id'] .= '_field';
				}
				else 
				{
					$path['leaf'] = false;
				}
				$nodes[] = $path;
			}
			
			//return $nodes;
		}
		return json_encode($nodes);
	}

    //Section #1 20150305 Tanis
	function copyAction()
    {
        $copyFrom = $_POST['id_from'];
        $copyTo = $_POST['id_to'];
        $sql =  "SELECT * FROM " . DB_WARPIT_WEBCATI_BASE . "." . $this->tableAddon . " WHERE id_telbaza =  " . intval($copyFrom);
        $rs = $this->db->SQLexecute($sql);
        $newId = 0;
        while($dat = $this->db->fetchAssoc($rs) )
        {
            $_POST['parId'] = $copyTo;
            $_POST['nodeId'] = $newId;
            $_POST['nodeText'] = $dat['name'];
            $_POST['dataType'] = $dat['type'];
            $_REQUEST['isTargetF'] = 1;
            $_POST['isCapi'] = 0;
            
            $rtnData = json_decode($this->insertFieldAction(), TRUE);
            if($rtnData['success'])
                $newId = $rtnData['insertId'];
            
                      
        }
        
        $rtn['success'] = true;
        return json_encode($rtn);   
        
    }
	//End Section #1 20150305 
	function insertTableAction()
		{
		
			
		$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 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;
		
		}
		if($_POST['isCapi'])
		{
			$create_telbase = "CREATE TABLE `capi___$text` (
			  `id` int(7) NOT NULL AUTO_INCREMENT,
			  `id_municipality` int(3) NOT NULL DEFAULT '0',
			  `municipality` varchar(120) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
			  `id_settlement` int(4) NOT NULL DEFAULT '0',
			  `settlement` varchar(120) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
			  `id_street` int(4) NOT NULL DEFAULT '0',
			  `street` varchar(150) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
			  `address` int(4) NOT NULL DEFAULT '0',
			  `addon_address` varchar(5) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
			  `zip` int(4) NOT NULL DEFAULT '0',
			  `town` varchar(120) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
			  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
			  `x_coordinate` int(9) NOT NULL DEFAULT '0',
			  `y_coordinate` int(9) NOT NULL DEFAULT '0',
			  `id_region` int(3) NOT NULL DEFAULT '0',
			  `population` int(11) NOT NULL DEFAULT '0',
			  `type_settlement` int(1) NOT NULL DEFAULT '0',
			  `id_import` int(11) default '0',  
			  `time_import` int(11) NOT NULL DEFAULT '0',
			  `proj_reserved` int(5) NOT NULL DEFAULT '0',
			  `tdisable` tinyint(1) NOT NULL DEFAULT '0',
			  PRIMARY KEY (`id`),
			  KEY (`id_municipality`),
			  KEY (`id_settlement`),
			  KEY (`id_street`),
			  KEY (`address`),
			  KEY (`zip`),
			  KEY (`x_coordinate`),
			  KEY (`y_coordinate`),
			  KEY (`id_region`),
			  KEY (`population`),
			  KEY (`type_settlement`),
			  KEY (`id_import`),
			  KEY (`proj_reserved`),
			  KEY (`tdisable`)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";

		}
		else
		{
		
			$text_telnum = $_POST['telNumAsText'];
			$unique_telnum = $_POST['uniqueTelNum'];
			// ustvarim novo bazo za telefonske stevilke
			$telnum_type = "int";
			$telnum_type_long = "12";
			if ($text_telnum) {
				$telnum_type = "char";
				$telnum_type_long = "30";
			}	
			$create_telbase="CREATE TABLE tel___$text ( 
				id int(8) NOT NULL auto_increment, 
				tdisable tinyint(1) NOT NULL default '0',
				oms $telnum_type(5) NOT NULL default '0', 
				telephone ".$telnum_type."(".$telnum_type_long.") NOT NULL default '0', 
				region int(4) NOT NULL default '0', 
				town char(50) NOT NULL default '', 
				zip int(4) NOT NULL default '0', 
				name char(250) NOT NULL default '', 
				address char(60) NOT NULL default '', 
				usp_klici int(5) NOT NULL default '0', 
				neusp_klici int(5) NOT NULL default '0', 
				status int(2) NOT NULL default '0', 
				status_rec int(2) NOT NULL default '0',
				usp_day int(2) NOT NULL default '0', 
				usp_month int(2) NOT NULL default '0', 
				usp_year int(4) NOT NULL default '0', 
				usp_min int(2) NOT NULL default '0', 
				usp_hour int(2) NOT NULL default '0', 
				usp_utime int(11) NOT NULL default '0', 
				neusp_day int(2) NOT NULL default '0', 
				neusp_month int(2) NOT NULL default '0', 
				neusp_year int(4) NOT NULL default '0', 
				neusp_min int(2) NOT NULL default '0', 
				neusp_hour int(2) NOT NULL default '0', 
				neusp_utime int(11) NOT NULL default '0', 
				proj_reserved int(5) NOT NULL default '0',
				proj_status int(2) NOT NULL default '0', 
				proj_status_rec int(2) NOT NULL default '0',
				id_import int(11) default '0',  
				time_import int(11) NOT NULL default '0',
				PRIMARY KEY  (id),";
	
	 		if ($unique_telnum) $create_telbase .= "UNIQUE KEY oms_tel (oms,telephone),";
	
			$create_telbase .= "
				KEY tdisable (tdisable),
				KEY region (region), 
				KEY oms (oms), 
				KEY telephone (telephone), 
				KEY proj_reserved (proj_reserved), 
				KEY status (status), 
				KEY status_and_rec (status, status_rec),
				KEY id_import (id_import),
				KEY zip (zip), 
				KEY usp_utime (usp_utime), 
				KEY neusp_utime (neusp_utime), 
				KEY proj_status_rec (proj_status_rec),
				KEY proj_status (proj_status)) ENGINE=INNODB";
			
			
		}
		$sql[] = $create_telbase;	
		//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,name,is_leaf) VALUES( $parent ,$orderTree,'$text',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.'"}';
				}	
		}
			$this->db->SQLcommit();
		
			$id = $this->db->GetLastInsertId();
			return '{success:true,insertId:'.$id .'}';	
		}
		
	function insertFieldAction()
		{
				
		$parent = $_POST['parId'];
		$newId = $_POST['nodeId'];
		$text = $_POST['nodeText'];
		$type = $_POST['dataType'];
		$closed = $_POST['closed'];
		
		$tableAddon = $this->table.'Addon';
		$tablePrefix = $_POST['isCapi'] ? 'capi___' : 'tel___';
		$fieldPrefix = $_POST['isCapi'] ? 'capi_' : 'tel_';
		
		
		$tableTel = $tablePrefix.$_POST['parText'];
		
		//$orderTree = $_POST['tPos'];
		//$orderGrid = $_POST['qPos'];
		$rs = $this->db->SQLexecute("SELECT id FROM $this->tableAddon WHERE name = '$text' AND id_telbaza = $parent");
		if($this->db->fetchAssoc($rs) )
		{
			return "{success:false,error:'Name already exists!'}";
		}
		
		if($newId == 0)
		{
			$orderTree = 1;
		}
		else 
		{
				if($_REQUEST['isTargetF'])
					{
					$getNewSql = "SELECT orderBy,name FROM $this->tableAddon 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'];
					$orderTree++;
					$nodeBeforeName = " AFTER TP_".$row['name'];
				}
				//other wise we put the item on the first place in the folder
				else 
				{
					$orderTree = 1;
//					$getNewSql = "SELECT orderBy,name FROM $this->tableAddon WHERE orderBy = 1 AND id_telbaza = $parent";
//					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.'"}';}
//					$nodeBeforeName = " BEFORE TP_".$row['name']; before doesn't exist :(
					$nodeBeforeName = " AFTER TP_zip";

					
				}
		
		}
		
		$dataType = getDataType($type);
		
		$sql[] = "ALTER TABLE  `$tableTel` ADD  `$fieldPrefix$text` $dataType NOT NULL";
		
		//we update tables for projects that have this tables
		if(!$_POST['isCapi'])
		{
			$sqlTmp = "SELECT id,proj_name FROM _Projects WHERE id_telname = $parent";
			$res = $this->db->SQLexecute($sqlTmp);
			while($row = $this->db->fetchRow($res))
			{
				$tblStructure = $row[1].'_structure';
				if($this->db->TableExists($tblStructure))
				{
					$sql[] = "ALTER TABLE $tblStructure ADD TP_$text $dataType $nodeBeforeName";
				}
				//if its int, bool, or tinyint
				 if(in_array($type,array(4,5,7)))
				 {
				 	$tblIndex = $row[1].'___telIndex'; 
				 	$sql[] = "ALTER TABLE $tblIndex ADD tel_$text $dataType";
				 }
			}
		}
		
		
		//we increase order in tree (!!!NEW!!!) for this parent only!!!!
		$sql[] = "UPDATE $this->tableAddon SET orderBy = orderBy+1 WHERE orderBy >= $orderTree AND id_telbaza = $parent";

		$sql[] = "INSERT INTO $this->tableAddon(id_telbaza,orderBy,name,type,is_leaf) VALUES( $parent ,$orderTree,'$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();
			$this->db->SQLcommit();
						
			return '{success:true,insertId:'.$id .'}';	
		}
		
	
	function deleteAction()
	{
			$tablePrefix = $_POST['isCapi'] ? 'capi___' : 'tel___';
		
			if ($_POST['isTargetF'])
			{
				$sql = "SELECT 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);
				$tName = $tablePrefix.$row[0];
				If (!$this->db->SQLexecute("DROP TABLE  `$tName`")) {return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';}	
				
				$sqlStatemens = "DELETE FROM $this->tableAddon WHERE id_telbaza = ".$_POST['nodeId'];
				If (!$this->db->SQLexecute($sqlStatemens)) {
					
						return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
					}
				
			}
			
			return parent::deleteAction();
			
	}
	
	function moveNodeAction()
	{
		if($_POST['isField'])
		{
			//id of the node that was dragged
			$oldId = $_POST['nodeId'];
			//id of the node that we dropped onto
			//there a 2 options: we disabled append (see $point)
			$newId = $_POST['targetId'];
			//where the node was dropped according to the new node (later as the targeted note)
			$point = $_POST['movePoint'];
			
			// we get the orderBy and parent of the dragged node
			$getOldSql = "SELECT orderBy,id_telbaza FROM $this->tableAddon WHERE id = $oldId";
			If (!$rs = $this->db->SQLexecute($getOldSql)) {	return '{success:false,error:"'.$this->db->GetError().'" ,STATEMENT: "'.$getOldSql.'"}';}	
			$row = $this->db->fetchAssoc($rs);
			$oldPos = $row['orderBy'];
			$oldParent = $row['id_telbaza'];
			//if we dropped into the table, the pos is 1
			if($newId == 0)
			{
				$point = 'above'; //so we don't mix up ordering
				$newPos = 1;
				$parent = 0;
			}
			else 
			{	
			//we find the new positions according to the $point 
				if($point=='append')
				{
					//append means that we have moved the question into a folder (the target node is a folder)
					//we must find it's first child and replace it's position, so that the new node will take first place
					$getNewSql = "SELECT orderBy,id AS par FROM $this->tableAddon WHERE id = $newId";	
					
				}
				//we get the position of the target node
				else
				{
					$getNewSql = "SELECT orderBy,id_telbaza AS par FROM $this->tableAddon WHERE id = $newId";
				}
				//NOTE! later we adjust the position acording to the point of drop!!!
					
				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.'"}';}
				$newPos = $row['orderBy'];
				$parent = $row['par'];
			}
			//if we moved a node down, we must lower ALL indexes
			if($point == 'below')
			{	//we increase the position so that it's after the targeted note
				$newPos++;
			}
			elseif ($point == 'append') {
				//new rule: append is first in folder so position is one :)
				$newPos = 1;
			}
			
			
			$sql[] = "UPDATE $this->tableAddon SET orderBy = $newPos , id_telbaza = $parent WHERE id = $oldId";
				if($parent == $oldParent)	//if parent is the same 
				{
					//if we moved the node down, we decrease the position of all nodes inbetween
					//now we have 2 nodes with this new position and we lower the other one (id <> gridId)
					if ($oldPos < $newPos  )
					{
						$sql[] = "UPDATE $this->tableAddon SET orderBy = orderBy -1 WHERE orderBy > $oldPos AND orderBy < $newPos AND id_telbaza = $parent ";
						$sql[] = "UPDATE $this->tableAddon SET orderBy = orderBy -1 WHERE orderBy = $newPos AND id = $oldId AND id_telbaza = $parent";
					}
					if ($oldPos > $newPos  )
					{//vice verse if we moved the node up
						$sql[] = "UPDATE $this->tableAddon SET orderBy = orderBy +1 WHERE orderBy < $oldPos AND orderBy > $newPos AND id_telbaza = $parent";
						$sql[] = "UPDATE $this->tableAddon SET orderBy = orderBy +1 WHERE orderBy = $newPos AND id <> $oldId AND id_telbaza = $parent";
					}
				}
				//otherwise...we lower all indexes from old parent and increase all in new parent (similar to insert and delete!!!)
				else 
				{
					$sql[] = "UPDATE $this->tableAddon SET orderBy = orderBy+1 WHERE orderBy > $newPos AND id_telbaza = $parent";
					$sql[] = "UPDATE $this->tableAddon SET orderBy = orderBy +1 WHERE orderBy = $newPos AND id <> $oldId AND id_telbaza = $parent";
					
					$sql[] = "UPDATE $this->tableAddon SET orderBy = orderBy-1 WHERE orderBy > $oldPos AND id_telbaza = $oldParent";
				}
			
			$this->db->SQLbegin();
			
			foreach ($sql as $sqlStatemens) {
				If (!$this->db->SQLexecute($sqlStatemens)) {
					
						$this->db->SQLrollback();
						Echo '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
						return;
					}	
			}
			
			$this->db->SQLcommit();
			return "{success:true}";
		}
		else 
			return parent::moveNodeAction();
		
		
	}
	
		
	
}

class telFieldEditManipulator extends GridDataManipulator
{
	
	function updateAction()
	{
		$tablePrefix = $_POST['isCapi'] ? '_Capi' : '_Telephone';
			$fieldPrefix = $_POST['isCapi'] ? 'capi_' : 'tel_';
		$telPrefix = $_POST['isCapi'] ? 'capi___' : 'tel___';
		
		if( $_POST['field'] == 'name')
		{
			$field = $_POST['value'];
			$type = getDataType( $_POST['dataType']  );
		}
		else 
		{
			$field = $_POST['fieldName'];
			$type = getDataType( $_POST['value']  );
		}
		
		
		$oldField = $_POST['oldName'];
		
		If (!$rs = $this->db->SQLexecute("SELECT name FROM  $tablePrefix"."Tables WHERE id = ".$_POST['tableId'] ))	{return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';}	
		$row = $this->db->fetchArray($rs);
		$tableTel = $telPrefix. $row[0];
		
		$dType = $_POST['displayType'];
		if($_POST['field'] == 'name' || $_POST['field'] == 'type')
		If (!$this->db->SQLexecute("ALTER TABLE  `$tableTel` CHANGE `$fieldPrefix$oldField` `$fieldPrefix$field` $type NOT NULL"))
					{
					
						return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';
					}	
		
		$sql = 'UPDATE '.$_POST['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.'"}';	}
		
		return '{success:true,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
		
		
	}
	
	function deleteAction()
	{
		$tablePrefix = $_POST['isCapi'] ? '_Capi' : '_Telephone';
			$fieldPrefix = $_POST['isCapi'] ? 'capi_' : 'tel_';
		$telPrefix = $_POST['isCapi'] ? 'capi___' : 'tel___';
		
		//we get info about the row being deleted! it's position the name of the field and the name of the column
		$sql = "SELECT a.id_telbaza,a.orderBy,a.name,b.name FROM $this->table a INNER JOIN $tablePrefix"."Tables b ON a.id_telbaza = b.id  WHERE a.id IN (".$_POST['ids'].')';
		If (!$rs = $this->db->SQLexecute($sql))	{return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';	}
		$row = $this->db->fetchArray($rs);
		$telId = $row[0];
		$pos = $row[1];
		$fldName = $fieldPrefix.$row[2];
		$tblName = $telPrefix.$row[3];
		//we remove the column from the appropriate table
		If (!$this->db->SQLexecute("ALTER TABLE  `$tblName` DROP  ".$fldName)) {return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';	}	
		
		//we update tables for projects that have this tables
		if(!$_POST['isCapi'])
		{
			$sqlTmp = "SELECT id,proj_name FROM _Projects WHERE id_telname = $telId";
			$res = $this->db->SQLexecute($sqlTmp);
			while($rowStruc = $this->db->fetchRow($res))
			{
				$tblStructure = $rowStruc[1].'_structure';
				$tblIndex = $rowStruc[1].'___telIndex';
				if($this->db->TableExists($tblStructure))
				{
					$sql = "ALTER TABLE $tblStructure DROP TP_".$row[2];
					$this->db->SQLexecute($sql);
					
				}
				try {
					$sql = "ALTER TABLE $tblIndex DROP tel_".$row[2];
					$this->db->SQLexecute($sql);
				}
				catch (Exception $e)
				{
					
				}
				 
			}
		}
		
		$sql = "UPDATE $this->table SET orderBy = orderBy -1 WHERE id_telbaza = $telId  AND orderBy > $pos";
		If (!$this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}
		
		return parent::deleteAction();
	}
	function resetDatabaseAction()
	{
		$flds = "usp_klici=0,neusp_klici=0,status=0,status_rec=0,usp_day=0,usp_month=0,usp_year	=0,usp_min=0,usp_hour=0,usp_utime=0,neusp_day=0,neusp_month=0,neusp_year=0,neusp_min=0,neusp_hour=0,neusp_utime=0,proj_reserved=0,proj_status=0,proj_status_rec=0";
		$sql = "UPDATE ".$_POST['telTable']." SET $flds";
		$this->db->SQLexecute($sql);
		return "{success:true}";
	}
	
	function exampleAction()
	{
		header( "Content-Type: text/csv" );
   		header( "Content-Disposition: attachment; filename=\"example.csv\";" );
   		echo "tdisable;oms;telephone;region;town;zip;name;address\n";
	}
	
	
}

class labelDefineManipulator extends GridDataManipulator
{
	public function fetchSelect()
	{
		$telTable = $_POST['telTable'];
		$idTel = $_POST['id_telname'];
		
		$sql = "SELECT * FROM $this->table WHERE id_telname = $idTel";
		$res = $this->db->SQLexecute($sql);
		while ($row = $this->db->fetchAssoc($res)){
				$labels[$row['id_var']][$row['is_addon']][$row['reg_code']] = $row['reg_label'];
			}
		
		//fetch oms group by!
		$this->arr = array();
		$resGroups = $this->db->SQLexecute("SELECT oms as value FROM $telTable GROUP BY oms");
		while ($row = $this->db->fetchAssoc($resGroups)){
			$this->arr[] = array('id_telname'=>$idTel,'id_var'=>1,'is_addon'=>0,'reg_code'=>$row['value'],'varLabel'=>'oms','reg_label' => $labels[1][0][$row['value']] );
			}
		//fetch region group by!
		$resGroups = $this->db->SQLexecute("SELECT region as value FROM $telTable GROUP BY region");
		while ($row = $this->db->fetchAssoc($resGroups)){
			$this->arr[] = array('id_telname'=>$idTel,'id_var'=>3,'is_addon'=>0,'reg_code'=>$row['value'],'varLabel'=>'region','reg_label' => $labels[3][0][$row['value']]  );
			}
		//fetch region group by!
		$resGroups = $this->db->SQLexecute("SELECT zip as value FROM $telTable GROUP BY zip");
		while ($row = $this->db->fetchAssoc($resGroups)){
			$this->arr[] = array('id_telname'=>$idTel,'id_var'=>5,'is_addon'=>0,'reg_code'=>$row['value'],'varLabel'=>'zip','reg_label' => $labels[5][0][$row['value']]  );
			}
		//we need all other fields that are int to show them here too
		$sql = "SELECT id,name FROM _TelephoneTablesAddon WHERE id_telbaza=$idTel AND (type=4 OR type=5) AND use_as_labels=1 ORDER BY orderBy";
		$res = $this->db->SQLexecute($sql);
		while ($rowRR = $this->db->fetchAssoc($res) )
		{
			
				$col = 'tel_'.$rowRR['name'];
				$resGroups = $this->db->SQLexecute("SELECT $col as value FROM $telTable GROUP BY $col");
				while ($row = $this->db->fetchAssoc($resGroups)){
					$this->arr[] = array('id_telname'=>$idTel,'id_var'=>$rowRR['id'],'is_addon'=>1,'reg_code'=>$row['value'],'varLabel'=>$col,'reg_label' => $labels[$rowRR['id']][1][$row['value']]  );
					}
		}
		
		
	}
	public function updateAction()
	{
		$idteName = $_POST['id_telname'];
		$idVar = $_POST['id_var'];
		$isAddon = $_POST['is_addon'];
		$reg_code = $_POST['reg_code'];
		$reg_label = $_POST['reg_label'];
		
		$sql = "INSERT INTO $this->table VALUES($idteName,$isAddon,$idVar,$reg_code,'$reg_label') ON DUPLICATE KEY UPDATE reg_label = '$reg_label'";
		If (!$this->db->SQLexecute($sql)) {return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';	}
		
		return '{success:true,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
	}
	
}

class telManagmentFormManipulator extends FormDataManipulator
{
    public function setSampleRulesAction()
    {
        $_POST['podatki']['sample_parameter'] = mysql_real_escape_string($_POST['podatki']['sample_parameter']);
        $_POST['podatki']['rules_by_id'] = mysql_real_escape_string($_POST['podatki']['rules_by_id']);
        
        try
        {
            $sql = "UPDATE ". $_POST['database'] . "." . $_POST['RMtable'] . " SET " . $_POST['field'] . " =  '0' WHERE " . $_POST['field'] . " = '" . $_POST['podatki']['sample_parameter'] . "'" ;
            $this->db->SQLexecute($sql);
            
            $sql = "UPDATE ". $_POST['database'] . "." . $_POST['RMtable'] . " SET " . $_POST['field'] . " =  '" . $_POST['podatki']['sample_parameter'] . "' WHERE zip IN(" . $_POST['podatki']['rules_by_id'] . ")";
            $this->db->SQLexecute($sql);
        }
        catch(Exception $e)
            {return '{success:true,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}'; }
    
        
        return '{success:true,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
     

    }
}

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

$tableName = $_POST['RMtable'];
$tableAddon = $tableName.'Addon';

if($_POST['RMcomp']=='tree')
{
	$manipulator = new telManagmentManipulator($db,$tableName);
	$manipulator->tableAddon = $tableAddon;
}
else if($_POST['RMcomp']=='form')
{
    $manipulator = new telManagmentFormManipulator($db,$tableName);
    $manipulator->tableAddon = $tableAddon;
}
else 
{
	if($_POST['RMcomp']=='labelGrid')
	{
		$manipulator = new labelDefineManipulator($db,$tableName);
	}
	else
	{
		$manipulator = new telFieldEditManipulator($db,$tableName);
		$manipulator->tableAddon = $tableAddon;
	}
}
$comm = $_REQUEST['action'].'Action';
if(method_exists($manipulator,$comm))
	echo $manipulator->$comm();
else 
{
	
	echo '{success:false,error:"Unknown action!"}';	
	
}


?>
