<?php
include_once($DB_PATH.'\MyDB.class.inc');

class DatabaseBroker extends DB{

	var $lang;
	var $MetaData = array();
	var $transaction = FALSE;
	var $good = FALSE;

	function __construct($name = 'MyDatabaseBroker') {
		global $HOME_PATH;
		//$this->RootRegistry($name);
		$this->lang = $HOME_PATH;
//		$this->MyDB_Sql();
		parent::__construct();
	}


//-------------------------
	function begin() {
		$this->transaction = TRUE;
		return $this->query('BEGIN');
	}

	function commit() {
		$this->transaction = FALSE;
		$this->good = TRUE;
		return $this->query('COMMIT');
	}

	function rollback() {
		$this->transaction = FALSE;
		$this->good = FALSE;
		return $this->query('ROLLBACK');
	}
	function setDBError(&$object) {
		if(!empty($this->Errno)) {
			$object->_error = "Error while accessing database.<br>Please, try again";
			$rollback = $this->rollback();
			return FALSE;
		}
		return TRUE;
	}
//--------------

	function incrementField($table,$field,$id,&$object,$value=1) {
		$object->{$field} = $this->nextvalue($table,$field,$id,$value);
	}

	function getID($table,$values,&$Obj) {
		$Obj->id = $values['id'] = $this->nextid($table.'_sequence');
		$this->insert($table,$values);
	}

	function SelectAll($tables,$fields='*',$conditions='') {
		$this->select($tables,$fields,$conditions);
		if($this->next_record()) return removeIntegerKeysFromArray($this->Record);
	}

	function SelectAny($query) {
		$array=array();
		$this->query($query);
		while($this->next_record()) $array[] = removeIntegerKeysFromArray($this->Record);
		return $array;
	}

	function SelectArray($tables,$fields='*',$conditions='',$orderby=0, $limit=0, $groupby=0, $array = array(),$type='CND_HOMOGENIC',$parameters=array('relation' => '=', 'operation' => 'and')) {
		$this->select($tables,$fields,$conditions,$orderby,$limit,$groupby,$type,$parameters);
		while($this->next_record()) $array[] = removeIntegerKeysFromArray($this->Record);
		return $array;
	}

	function SelectList($name,$tables,$fields='*',$conditions='',$orderby=0, $limit=0, $groupby=0, $array = array()) {
		$this->select($tables,$fields,$conditions,$orderby,$limit,$groupby);
		while($this->next_record()) $array[] = $this->f($name);
		return $array;
	}

	function SelectLang($tables,$fields='*',$conditions='',$orderby=0, $limit=0, $groupby=0, $array = array()) {
		$this->select($tables,$fields,$conditions,$orderby,$limit,$groupby);
		while($this->next_record()) $array[$this->f('name')][$this->f('var')] = $this->f('value');
		return $array;
	}

	function SelectSingle($tables,$fields='*',$conditions='') {
		$this->select($tables,$fields,$conditions);
		while($this->next_record()) return current(removeIntegerKeysFromArray($this->Record));
	}

/*	function SelectGuide($tables,$fields='*',$conditions='',$array = array()) {
		$this->select($tables,$fields,$conditions);
		while($this->next_record()) $array[$this->f('id')] = $this->f('name');
		return $array;
	}*/

	function SelectGuide($tables,$fields='*',$conditions='',$short = false,$sort = 'id',$array = array()) {
		$this->select($tables,$fields,$conditions,'g.'.$sort.' ASC');
		while($this->next_record()) $array[trim($this->f($short? 'shortname' : 'id'))] = $this->f('name');
		return $array;
	}


	function correctFields($values=array(),$array = array()) {
		is_array($values) or $values = array();
		foreach($values as $key => $value) if(!empty($value) || $value == '0') $array[$key] = $value;
		return $array;
	}

	function compareFields($fields=array(),$table) {
		is_array($fields) or $fields = array();
		if(isset($this->MetaData[$table])) $array = $this->MetaData[$table];
		else $array = $this->MetaData[$table] = $this->metadata($table);
		foreach($array as $k => $v) $correct_fields[] = $v['name'];
		foreach($fields as $k => $v) if(!in_array($k,$correct_fields)) unset($fields[$k]);
		return $fields;
	}



// ORIGINAL PROVESS OBJECT
//	function processObject(&$object,$type='save',   $Tables = array(),$deletedidspr = array(), $begin = FALSE) {
	function processObject($object,$type='save',$Tables = array(),$deletedidspr = array(),$begin = FALSE) {
		if(!$begin && $type=='delete') $this->initObject($object);
		if(!$begin) $this->begin();
		$Obj = get_object_vars($object);
		is_array($Obj) or $Obj = array();
	$ObjName = strtolower(get_class($object));
//		$ObjName = get_class($object);
		foreach($Obj as $k => $v)
			switch(gettype($v)) {
				case 'object':
//					if(get_class($v)=='objectslist') $Tables[] = $v;
 			    if(strtolower(get_class($v)) == 'objectslist') $Tables[] = $v;
					else {
						$ObjTable[$k] = $v->id;
					}
				break;
				default: $ObjTable[$k] = $v; break;
			}
		if($type=='save')
			!empty($Obj['id'])?
				$this->update($ObjName,$this->correctFields($this->compareFields($ObjTable,$ObjName)),
							array('id'=>$Obj['id'])) : $this->getID($ObjName,
							$this->correctFields($this->compareFields($ObjTable,$ObjName)),$object);

		foreach($Tables as $k => $v) {
			// Added for deleting objectslists in objectslists in objectslists......			
			$selected=$this->SelectArray( strtolower( get_class($v->type)) ,'id',array('ownerid' => $object->id));

			if(!empty($selected)){
				foreach($selected as $p=>$m){
					$deletedids[]=$m['id'];
				}
			}
			else $deletedids=array();
			if (!empty($deletedidspr)) {
				foreach ($deletedidspr as $z=>$x) $this->delete( strtolower(  get_class($v->type)) ,array('ownerid' => $x));
			}
			else $this->delete(  strtolower(  get_class($v->type)), array('ownerid' => $object->id));
			// End Added for deleting
		//$this->delete(get_class($v->type),array('ownerid' => $object->id));
			if($type=='save')
				foreach($v->data as $key => $obj) {
					$obj->ownerid = $object->id;
					$obj->id = '';
					$this->processObject($obj,'save',array(),$deletedids);
				}
		}
	if($type=='delete') $this->delete($ObjName,array('id' => $object->id));
	}




// ORIGINAL INIT
//	function initObject(&$object,$Temp = array(),$Tables = array()) {
	function initObject($object,$Temp = array(),$Tables = array()) {
		if(!empty($object->id)) {
			$Obj = get_object_vars($object);
//			$ObjName = get_class($object);
  		$ObjName = strtolower(get_class($object));
//			$Obj = removePrivateKeysFromArray($Obj);
			$this->select($ObjName,'*',array('id'=>$Obj['id']));
			while($this->next_record()) $Temp = removeIntegerKeysFromArray($this->Record);
			foreach($Obj as $k => $v)
				switch(gettype($v)) {
					case 'object':
				$object->{$k} = clone $object->{$k};
//						if(get_class($v)=='objectslist') {
				if(strtolower(get_class($v)) == 'objectslist') {
//							$table = get_class($v->type);
				$table = strtolower(get_class($v->type));
							$object->{$k}->data = array();
							$i = 0;
							foreach($this->SelectList('id',$table,'id',array('ownerid'=>$Obj['id'])) as $key => $value) {
//								$data = $v->type;
							$data = clone $v->type;
								$data->id = $value;
								$this->initObject($data);
								$object->{$k}->data[$i] = $data;
							$i++;
							}
						}
						else {
							$object->{$k}->id = isset($Temp[$k])? $Temp[$k] : '';
							!empty($object->{$k}->id) and $this->initObject($object->{$k});
						}	
					break;
					default: if(in_array($k,array_keys($Temp))) $object->{$k} = $Temp[$k]; break;
				}
		}

	}
}
?>