<?php 

class FormDataManipulator
{
	
	function __construct($db,$table) 
	{
		$this->db = $db;
		$this->table = $table;
	}
	
	function loadAction()
	{
		if($_POST['SQL'])
		{
			$sql = $_POST['SQL']." WHERE a.id = ".$_REQUEST['id'];
		}
		else 
			$sql = "SELECT * FROM $this->table WHERE $this->table.id = ".$_REQUEST['id'];

		If (!$res = $this->db->SQLexecute($sql)) {
		
			return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
		
		}else{
		
		    If ($row = $this->db->fetchAssoc($res)) {
		    	
		    	foreach ($row as $key => $val) {
		    		$this->data['podatki['.$key.']']=$val;
		    	}
		    	
		    	
		    	
		    	return '{success: true, data:'.json_encode($this->data).'}';
		    }else{
		    	return '{success: false,error:"no data!"}';
		    }
		
		}
	}
	function submitAction()
	{
		
		$sqlData = array();
		if($_POST['insertTree']) //the form was used with for a insertion in a tree!!! we add the item
		{
			if(!$_POST['podatki']['idLab'])
				return "{success:false, error:'No name entered!' }";
			include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.treeData.php");
			$tmpTree = new TreeDataManipulator($this->db,$this->table);
			$tmpTree->insertItemAction();
			$_POST['id'] = $tmpTree->insertId;
		}
		$podatki = $_POST['podatki'];
		foreach ($podatki as $key=>$pod) 
		{
			if (is_array($pod))
			{
				foreach ($pod as $key1=>$pod1) {
					$sqlData[$key1][$key]="$key = '$pod1'";
				}
				
			}
			else 
			{
				$sqlData[$this->table][$key] = "$key = '$pod'";
			}
		}
		foreach ($sqlData as $tabela => $polja) {
			$sql = 'UPDATE '.$tabela.' SET ' . implode(',',$polja).' WHERE id = '.$_POST['id'];
			If (!$res = $this->db->SQLexecute($sql)) {
		
			return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
				
			}
		}
		return "{success:true}";
		
		
		
	}
	function updateAction()
	{
		$_POST['value'] = addslashes($_POST['value']);
		$idField = $_POST['idField'];
		if(!$idField) $idField = 'id';
		if($_POST['SQLwhere']) $where = " AND ".$_POST['SQLwhere']; 
		
		$sql = 'UPDATE '.$_POST['RMtable']." SET ".$_POST['field']." = '".( ($_POST['RMtrim']) ? trim($_POST['value']) : $_POST['value'] )."' WHERE $idField = ".$_REQUEST['id'].$where;
		If (!$rs = $this->db->SQLexecute($sql)) {
				
					return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
				
				}else{
					
				
				
				return '{success:true}';
			}
	}
}


?>