<?php

/**
 * API:
 *   get($field_name) - source field value
 *   get_item($id) - get item by ID
 */
class Data_Source {

	var $_db;
	var $_tbl;// sql table name, TODO: or zasob ID
	var $_default_sql_limit;
	var $_fields_type;// array of fields ( name => type )
	var $_fields_perm;// array of field perm ( name => perm )
	var $_cols = array();
	var $_vCols = array();// setVirtualCols - TODO: use Typespecial
	var $_col_types = array();// TODO: array( col_name => TYPE )
	var $_sql_where;// sql where
	var $_sql_limit;
	var $_sql_offset;
	var $_sql_left_join;// TODO: left join in table
	var $_isAccessFltrAllowed = null;
	private $_geomFields = array();

	function __construct($db = null) {
		if ($db) {
			$this->_db = DB::getDB($db);
		} else {
			$this->_db = DB::getDB();
		}
		$this->_default_sql_limit = 10;

		$this->_geomFields = array('the_geom');
	}

	function set_table($tbl) {// TODO: RMME
		$this->setTable($tbl);
	}

	public function setTable($tbl) {
		$this->_tbl = $tbl;
		$this->_fields_type = array();
		$this->_fields_perm = array();
	}

	function get_cols() {
		// TODO: cache in session
		if (empty($this->_cols)) {
			if (!$this->_tbl) {
				return $this->_tbl;
			}
			$sql = "show fields from `{$this->_tbl}` ; ";
			$res = $this->_db->query($sql);
			while ($r = $this->_db->fetch($res)) {
				$this->_cols[$r->Field] = $r->Field;
				$this->_col_types[$r->Field] = $r->Type . ';' . $r->Default;
			}
		}
		return $this->_cols;
	}

	function set_cols($cols) {// TODO: RMME
		$this->setCols($cols);
	}

	function setCols($cols) {
		foreach ($cols as $v_field_name) {
			$this->_cols[$v_field_name] = $v_field_name;
		}
	}

	public function setColTypes($types) {
		$this->_col_types = $types;
		// TableAcl->getTypes():  $this->_types[$fieldName] = array('type'=>$h[1], 'null'=>('YES' == $h[2]), 'default'=>$h[4]);
	}

	public function getColDefault($fieldName) {
		if (array_key_exists($fieldName, $this->_types)) {
			if (!empty($this->_types[$fieldName]['default'])) {
				return $this->_types[$fieldName]['default'];
			}
		}
		return '';
	}

	function setVirtualCols($cols) {
		foreach ($cols as $v_field_name) {
			$this->_vCols[$v_field_name] = $v_field_name;
		}
	}

	public function setFieldGroupWrite($fieldName, $fieldExists = false) {
		if ($fieldExists) {
			$this->_fieldGroupWrite = $fieldName;
			$this->_cols[$fieldName] = $fieldName;
		}
	}

	public function setFieldGroupRead($fieldName, $fieldExists = false) {
		if ($fieldExists) {
			$this->_fieldGroupRead = $fieldName;
			$this->_cols[$fieldName] = $fieldName;
		}
	}

	function _get_sql_cols() {
		$sql_cols = "t.*";
		if (!empty($this->_cols)) {
			$sql_cols_arr = array();
			foreach ($this->_cols as $k_field => $v_field_label) {
				if ($this->isGeomField($k_field)) {
					$sqlFld = "AsWKT(t.`{$k_field}`) as {$k_field}";
				} else {
					$sqlFld = "t.`{$k_field}`";
				}
				$sql_cols_arr[] = $sqlFld;
			}
			$sql_cols = implode(", ", $sql_cols_arr);
		}
if(V::get('DBG_DS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql_cols (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql_cols);echo'</pre>'."\n\n";}
		return $sql_cols;
	}

	public function setAccessFltrAllowed($isAccessFltrAllowed) {
		$this->_isAccessFltrAllowed = $isAccessFltrAllowed;
	}

	public function isAccessFltrAllowed() {
		if (false === $this->_isAccessFltrAllowed) {
			return false;
		}
		else if ( !empty($this->_fieldGroupWrite)
			&& !empty($this->_fieldGroupRead)
			&& array_key_exists('A_ADM_COMPANY', $this->_cols)
			&& array_key_exists('A_CLASSIFIED', $this->_cols)
		) {
			return true;
		}
	}

	function getSpecialFilters() {
		$fltrs = array();

		if (array_key_exists('A_PROBLEM', $this->_cols)) {
			$fltrs['Problemy'] = new stdClass();
			$fltrs['Problemy']->icon = 'icon-warning-sign';
			$fltrs['Problemy']->btns = array();
			$fltrs['Problemy']->btns['PROBLEMY'] = (object)array('value'=>'PROBLEM');
			$fltrs['Problemy']->btns['OSTRZEZENIA'] = (object)array('value'=>'WARNING');
			$fltrs['Problemy']->btns['BEZ_PROBLEM.'] = (object)array('value'=>'NORMAL');
		}
		if (array_key_exists('A_STATUS', $this->_cols)) {
			$fltrs['Status'] = new stdClass();
			$fltrs['Status']->icon = 'icon-question-sign';
			$fltrs['Status']->btns = array();
			$fltrs['Status']->btns['OCZEKUJACY'] = (object)array('value'=>'WAITING');
			$fltrs['Status']->btns['AKTYWNI'] = (object)array('value'=>'AKTYWNI');
		}
		if (array_key_exists('L_APPOITMENT_DATE', $this->_cols)) {
			$fltrs['Spotkania'] = new stdClass();
			$fltrs['Spotkania']->icon = 'icon-calendar';
			$fltrs['Spotkania']->btns = array();
			$fltrs['Spotkania']->btns['STARE'] = (object)array('value'=>'OLD');
			$fltrs['Spotkania']->btns['ZARAZ'] = (object)array('value'=>'NOW');
			$fltrs['Spotkania']->btns['DZISIAJ'] = (object)array('value'=>'TODAY');
			$fltrs['Spotkania']->btns['BRAK'] = (object)array('value'=>'BRAK');
		}
		if ($this->isAccessFltrAllowed()) {
			$fltrs['Access'] = new stdClass();
			$fltrs['Access']->icon = 'icon-lock';
			$fltrs['Access']->btns = array();
			$fltrs['Access']->btns['UKRYJ'] = (object)array('value'=>'HIDE');
		}
		return $fltrs;
	}

	function _parseSpecialFilter($fltr, $value) {
		$sqlFltr = "";

		switch ($fltr) {
			case 'Problemy':
				if (array_key_exists('A_PROBLEM', $this->_cols)) {
					switch ($value) {
						case 'PROBLEM':
							$sqlFltr = " t.`A_PROBLEM`!='' ";
							break;
						case 'WARNING':
							$sqlFltr = " t.`A_PROBLEM`='WARNING' ";
							break;
						case 'NORMAL':
							$sqlFltr = " t.`A_PROBLEM`='' ";
							break;
					}
				}
				break;
			case 'Status':
				if (array_key_exists('A_STATUS', $this->_cols)) {
					switch ($value) {
						case 'WAITING':
							$sqlFltr = " t.`A_STATUS`='WAITING' ";
							break;
						case 'AKTYWNI':
							$sqlFltr = " t.`A_STATUS` in('NORMAL', 'WARNING') ";
			// TODO: $_SESSION['USERS_FILTER_STATUS_SQL']="and (( $thiss->DETECT_TABLE_NAME.A_STATUS='NORMAL' or $thiss->DETECT_TABLE_NAME.A_STATUS='WARNING'  ) or ( $thiss->DETECT_TABLE_NAME.A_STATUS='OFF_SOFT' and $thiss->DETECT_TABLE_NAME.A_PROBLEM_DESC not like '%odla%fizy%' and $thiss->DETECT_TABLE_NAME.A_PROBLEM!='' ) or ( $thiss->DETECT_TABLE_NAME.A_STATUS='OFF_SOFT' and $thiss->DETECT_TABLE_NAME.A_PROBLEM='' )) ";
			// if ($thiss->DETECT_TABLE_NAME == 'KSIEG_DOKUMENTY') $_SESSION['USERS_FILTER_STATUS_SQL']="and ( $thiss->DETECT_TABLE_NAME.A_STATUS='NORMAL' or $thiss->DETECT_TABLE_NAME.A_STATUS='WARNING'  )  ";
							break;
					}
				}
				break;
			case 'Spotkania':
				if (array_key_exists('L_APPOITMENT_DATE', $this->_cols)) {
					switch ($value) {
						case 'OLD':
							$sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<UNIX_TIMESTAMP(now()) and t.`L_APPOITMENT_DATE`!='' ";
							break;
						case 'NOW':
							$sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<UNIX_TIMESTAMP(now())+3600 and UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)>UNIX_TIMESTAMP(now())-3600 ";
							break;
						case 'TODAY':
							$start = mktime(0,0,0, date("m"), date("d"), date("Y"));
							$end = mktime(0,0,0, date("m"), date("d") + 1, date("Y"));
							$sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)>'{$start}' and UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<'{$end}' ";
							break;
						case 'TOMORROW':
							$start = mktime(0,0,0, date("m"), date("d") + 1, date("Y"));
							$end = mktime(0,0,0, date("m"), date("d") + 2, date("Y"));
							$sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)>'{$start}' and UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<'{$end}' ";
							break;
						case 'YESTERDAY':
							$start = mktime(0,0,0, date("m"), date("d") - 1, date("Y"));
							$end = mktime(0,0,0, date("m"), date("d") - 2, date("Y"));
							$sqlFltr = " UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)>'{$start}' and UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`)<'{$end}' ";
							break;
						case 'BRAK':
							$start = mktime(0,0,0, date("m"), date("d") - 1, date("Y"));
							$end = mktime(0,0,0, date("m"), date("d") - 2, date("Y"));
							$sqlFltr = " t.`L_APPOITMENT_DATE`='' ";
							break;
					}
				}
				break;
			case 'Access':
				if ($this->isAccessFltrAllowed()) {
					$usrAclGroups = User::getLdapGroupsNames();
					$usrAclGroups[] = '';
					$sqlUsrAclGroups = "'" . implode("','", $usrAclGroups) . "'";
					$sqlFltr = "
						t.`{$this->_fieldGroupWrite}` in({$sqlUsrAclGroups})
						and t.`{$this->_fieldGroupRead}` in({$sqlUsrAclGroups})
					";
				}
				break;
			default:
		}

/*
			//USERS_FILTER_PROBLEM
			// 	PROBLEMY			https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=PROBLEM
			//	OSTRZEZENIA		https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=WARNING
			//	BEZ_PROBLEM.	https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=NORMAL
			//	KASUJ-FILTR		https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_PROBLEM&USERS_FILTER_PROBLEM=

			//USERS_FILTER_STATUS
			//	OCZEKUJACY	https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_STATUS&USERS_FILTER_STATUS=WAITING
			//	AKTYWNI			https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_STATUS&USERS_FILTER_STATUS=AKTYWNI
			//	KASUJ-FILTR	https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_STATUS&USERS_FILTER_STATUS=

			//USERS_FILTER_APPOINTMENT
			//	A_STARE		https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=OLD
			//	A_ZARAZ		https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=NOW
			//	A_DZISIAJ	https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=TODAY
			//	APP_ALL		https://biuro.biall-net.pl/SE/se-dev/index.php?FUNCTION_INIT=USERS_FILTER_APPOINTMENT&USERS_FILTER_APPOINTMENT=

			// btn class: active, disabled
			{// USERS_FILTER_PROBLEM
				var groupHtml = $('<div class="btn-group"></div>');
				$('<button class="btn btn-mini" title="Problemy"><i class="icon-warning-sign"></i></button>').appendTo(groupHtml);
				$('<button class="btn btn-mini">PROBLEMY</button>').appendTo(groupHtml);
				$('<button class="btn btn-mini">OSTRZEZENIA</button>').appendTo(groupHtml);
				$('<button class="btn btn-mini active">BEZ_PROBLEM.</button>').appendTo(groupHtml);
				$('<button class="btn btn-mini disabled" title="Kasuj filtr"><i class="icon-remove"></i></button>').appendTo(groupHtml);
				groupHtml.appendTo(_headSpecialFilter);
			}
			{// USERS_FILTER_STATUS
				var groupHtml = $('<div class="btn-group"></div>');
				$('<button class="btn btn-mini" title="Status"><i class="icon-question-sign"></i></button>').appendTo(groupHtml);
				$('<button class="btn btn-mini">OCZEKUJACY</button>').appendTo(groupHtml);
				$('<button class="btn btn-mini">AKTYWNI</button>').appendTo(groupHtml);
				$('<button class="btn btn-mini disabled" title="Kasuj filtr"><i class="icon-remove"></i></button>').appendTo(groupHtml);
				groupHtml.appendTo(_headSpecialFilter);
			}
			{// USERS_FILTER_APPOINTMENT
				var groupHtml = $('<div class="btn-group"></div>');
				$('<button class="btn btn-mini" title="Spotkania"><i class="icon-calendar"></i></button>').appendTo(groupHtml);
				$('<button class="btn btn-mini">A_STARE</button>').appendTo(groupHtml);
				$('<button class="btn btn-mini">A_ZARAZ</button>').appendTo(groupHtml);
				$('<button class="btn btn-mini active">A_DZISIAJ</button>').appendTo(groupHtml);
				$('<button class="btn btn-mini disabled" title="Kasuj filtr"><i class="icon-remove"></i></button>').appendTo(groupHtml);// To samo co KASUJ-FILTR
				groupHtml.appendTo(_headSpecialFilter);
			}
 */

		return $sqlFltr;
	}

	private function isColTypeNumber($colName) {
		if ($colName == 'ID') {
			return true;
		}
		$type = V::get($colName, null, $this->_col_types);
		if(V::get('DBG_DS', 0, $_GET) > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">type['.$colName.'] (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('type'=>$type, '!empty'=>(!empty($type['type']['type']))));echo'</pre>'."\n\n";}
		if (!empty($type['type'])) {
			$sqlType = $type['type'];
			if (substr($sqlType, 0, 3) == 'int'
					|| substr($sqlType, 0, 7) == 'tinyint'
					|| substr($sqlType, 0, 8) == 'smallint'
			) {
				return true;
			}
		}
		return false;
	}

	private function _sqlValueForGeomField($fldName, $fltrValue, $tblPrefix = 't') {
		$sqlFilter = false;
		// example: BBOX:54.40993961633866,18.583889010112824,54.337945760687454,18.397121431987586
		if ('BBOX:' == substr($fltrValue, 0, 5)) {
			$val = substr($fltrValue, 5);
			$valParts = explode(',', $val);
			if (count($valParts) == 4) {
				$isAllNumeric = true;
				foreach ($valParts as $v) {
					if (!is_numeric($v)) $isAllNumeric = false;
				}
				if ($isAllNumeric) {
					$bounds = "POLYGON((
						{$valParts[3]} {$valParts[2]},
						{$valParts[3]} {$valParts[0]},
						{$valParts[1]} {$valParts[0]},
						{$valParts[1]} {$valParts[2]},
						{$valParts[3]} {$valParts[2]}
					))";
					// for mysql 5.6 use ST_Contains() @see http://dev.mysql.com/doc/refman/5.6/en/spatial-relation-functions.html
					$sqlFilter = "Intersects(GeomFromText('{$bounds}'), GeomFromText(AsWKT({$tblPrefix}.`{$fldName}`)))=1";
				}
			}
		}
		return $sqlFilter;
	}

	function _parse_sql_where($params = array()) {
		$sql_where = '';
		// ... parse filters
		$sql_where_and = array();
		foreach ($params as $k => $v) {
			if (strlen($k) > 3 && substr($k, 0, 2) == 'f_') {
				//$v = trim($v, '% ');
				//$sql_where_and []= "t.`" . substr($k, 2) . "` like '%" . DB::_($v) . "%'";
				$fldName = substr($k, 2);
				if ($this->isGeomField($fldName)) {
					$sqlFilter = $this->_sqlValueForGeomField($fldName, $v, 't');
					if ($sqlFilter) $sql_where_and[] = $sqlFilter;
					continue;
				}

				if (substr($v, 0, 1) == '=') {
					$v = $this->_db->_(substr($v, 1));
					if (strlen($v)) $sql_where_and []= "t.`{$fldName}`='{$v}'";
				}
				else if (substr($v, 0, 1) == '!') {
					$v = $this->_db->_(substr($v, 1));
					if (strlen($v)) $sql_where_and []= "t.`{$fldName}` not like '{$v}'";
				}
				else if (substr($v, 0, 2) == '<=') {
					$v = $this->_db->_(substr($v, 2));
					if (strlen($v)) $sql_where_and []= "t.`{$fldName}`<='{$v}'";
				}
				else if (substr($v, 0, 2) == '>=') {
					$v = $this->_db->_(substr($v, 2));
					if (strlen($v)) $sql_where_and []= "t.`{$fldName}`>='{$v}'";
				}
				else if (substr($v, 0, 1) == '<') {
					$v = $this->_db->_(substr($v, 1));
					if (strlen($v)) $sql_where_and []= "t.`{$fldName}`<'{$v}'";
				}
				else if (substr($v, 0, 1) == '>') {
					$v = $this->_db->_(substr($v, 1));
					if (strlen($v)) $sql_where_and []= "t.`{$fldName}`>'{$v}'";
				}
				else if (false !== strpos($v, '%')) {
					$sql_where_and []= "t.`{$fldName}` like '{$v}'";
				}
				else if ($this->isColTypeNumber($fldName)) {
					$v = $this->_db->_($v);
					$sql_where_and []= "t.`{$fldName}`='{$v}'";
				}
				else {
					$searchWords = explode(' ', $v);
					$sqlWhereWords = array();
					if (!empty($searchWords)) {
						foreach ($searchWords as $word) {
							if (!empty($word)) {
								$word = $this->_db->_($word);
								$sqlWhereWords []= "t.`{$fldName}` like '%{$word}%'";
							}
						}
					}
					if (!empty($searchWords)) {
						$sql_where_and []= "(" . implode(" and ", $sqlWhereWords) . ")";
					}
				}
			}
			else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_') {
				$sqlFltr = $this->_parseSpecialFilter(substr($k, 3), $v);
				if (!empty($sqlFltr)) {
					$sql_where_and []= $sqlFltr;
				}
			}
		}
		if (!empty($sql_where_and)) {
			$sql_where = implode(" and ", $sql_where_and);
		}

		if (!$sql_where) $sql_where = "1=1";
		if(V::get('DBG_DS', 0, $_GET) > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql_where (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql_where);echo'</pre>'."\n\n";}
		return $sql_where;
	}

	function get_item($id) {// TODO: RMME
		$this->getItem($id);
	}

	public function getItem($id) {
		$ret = null;
		$sql_cols = $this->_get_sql_cols();
		$id = intval($id);
		$sql = "select {$sql_cols}
			from {$this->_tbl} as t
			where t.`ID`='{$id}'
		";
		$res = $this->_db->query($sql);
		if ($r = $this->_db->fetch($res)) {
			$ret = $r;
		}
		return $ret;
	}

	function get_items($params = array()) {// TODO: RMME
		$this->getItems($params);
	}

	public function getItems($params = array()) {
		$items = array();
		$sql_limit = V::get('limit', $this->_default_sql_limit, $params, 'int');
		$sql_offset = V::get('limitstart', 0, $params, 'int');
		$sql_order_by = V::get('order_by', '', $params);
		if ($sql_order_by) {
			$sql_order_dir = V::get('order_dir', '', $params);

			// prevent from sorting by special columns
			if (!array_key_exists($sql_order_by, $this->_cols)) {
				$sql_order_by = null;
				$sql_order_dir = null;
			}
		}
		if ($sql_order_by) {
			$sql_order_by = "order by t.`{$sql_order_by}`";
			if ($sql_order_dir) {
				$sql_order_by = "{$sql_order_by} {$sql_order_dir}";
			}
		}
		$sql_cols = $this->_get_sql_cols();
		$sql_where = $this->_parse_sql_where($params);
		$sql = "select {$sql_cols}
			from {$this->_tbl} as t
			where {$sql_where}
			{$sql_order_by}
			limit {$sql_limit} offset {$sql_offset}
		";
		if(V::get('DBG_DS', 0, $_GET) > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>'."\n\n";}
		$res = $this->_db->query($sql);
		while ($r = $this->_db->fetch($res)) {
			$items[$r->ID] = $r;
		}
		return $items;
	}

	function get_hist_items($id) {// TODO: RMME
		$this->getHistItems($id);
	}

	public function getHistItems($id, $params = array()) {
		$ret = array();
		$sql_tbl = $this->_tbl . "_HIST";
		$sql_cols = $this->_get_sql_cols();
		$sql_where = "t.`ID_USERS2`='{$id}'";

		$paramNotEmptyFlds = V::get('notEmptyFlds', '', $params);
		if (!empty($paramNotEmptyFlds) && is_array($paramNotEmptyFlds)) {
			$sqlWhereOr = array();
			foreach ($paramNotEmptyFlds as $fldName) {
				if (array_key_exists($fldName, $this->_cols)) {
					$sqlWhereOr[] = "t.`{$fldName}`!='N/S;'";
				}
			}
			if (!empty($sqlWhereOr)) $sql_where .= "\n and (" . implode(" or ", $sqlWhereOr) . ")";
		}

		$sql = "select {$sql_cols}
			from {$sql_tbl} as t
			where {$sql_where}
			order by ID DESC
		";
if(V::get('DBG_DS', 0, $_GET) > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>'."\n\n";}
		$res = $this->_db->query($sql);
		while ($r = $this->_db->fetch($res)) {
			$r->_author = $r->A_RECORD_UPDATE_AUTHOR;
			$r->_created = $r->A_RECORD_UPDATE_DATE;

			if (!$r->_author || $r->_author == 'N/S;') {
				$r->_author = $r->A_RECORD_CREATE_AUTHOR;
			}
			if (!$r->_created || $r->_created == 'N/S;') {
				$r->_created = $r->A_RECORD_CREATE_DATE;
			}

			$ret[$r->ID] = $r;
		}
		return $ret;
	}

	function get_total($params = array()) {// TODO: RMME
		$this->getTotal($params);
	}

	public function getTotal($params = array()) {
		$ret = 0;
		$sql_where = $this->_parse_sql_where($params);
		$sql = "select count(1) as cnt
			from {$this->_tbl} as t
			where {$sql_where}
		";
		$res = $this->_db->query($sql);
		if ($r = $this->_db->fetch($res)) {
			$ret = $r->cnt;
		}
		return $ret;
	}

	function set_sql_where($sql_where) {
		$this->_sql_where = $sql_where;
	}

	function set_field_sql_type($field, $sql_type) {
		$this->_fields_type[$field] = $sql_type;
	}

	function get_field_sql_type($field) {
		if (array_key_exists($field, $this->_fields_type)) {
			return $this->_fields_type[$field];
		}
		return 'varchar(255)';
	}

	function set_field_perm($field, $perm) {
		$this->_fields_perm[$field] = $perm;
	}

	function get_field_perm($field) {
		if (array_key_exists($field, $this->_fields_perm)) {
			return $this->_fields_perm[$field];
		}
		return '';
	}

	function field_allow_write($field_name) {
		return (strpos($this->get_field_perm($field_name), 'W') !== false)? true : false;
	}

	function field_allow_read($field_name) {
		return (strpos($this->get_field_perm($field_name), 'R') !== false)? true : false;
	}

	function field_allow_create($field_name) {
		return (strpos($this->get_field_perm($field_name), 'C') !== false)? true : false;
	}

	public function add_col($col_name, $label = '', $type = 'string') {
		if (!$label) $label = $col_name;
		$this->_cols [$col_name] = $label;
		$this->_col_types [$col_name] = $type;
	}

	public function addCol($col_name) {
		$this->_cols[$col_name] = $col_name;
	}

	function count() {
		$ret = 0;
		$sql_where = ($this->_sql_where)? $this->_sql_where : "1=1";
		$sql = "select count(1) as cnt
			from `{$this->_tbl}`
			where {$sql_where}
		";
		$res = $this->_db->query($sql);
		if ($r = $this->_db->fetch($res)) {
			$ret = $r->cnt;
		}
		return $ret;
	}

	function fetch_list($limit = 10, $offset = 0) {
		$ret = array();
		$this->_sql_limit = $limit;
		$this->_sql_offset = $offset;
		$sql_cols = (!empty($this->_cols))? implode(',', array_keys($this->_cols)) : "*";
		$sql_where = ($this->_sql_where)? $this->_sql_where : "1=1";
		$sql = "
			select {$sql_cols}
			from {$this->_tbl}
			where {$sql_where}
			limit {$this->_sql_limit} offset {$this->_sql_offset}
		";
		$res = $this->_db->query($sql);
		while ($r = $this->_db->fetch($res)) {
			$ret [$r->ID] = $r;
		}
		return $ret;
	}

	function field_check_value($field_name, $val) {
		if (!$this->field_allow_write($field_name)) {
			return false;
		}
		// post verify
		// get type, and check if value is correct
		// TODO: if typespecial use it
		return true;
	}

	function save_item(&$item, $values, $prefix) {
		if (!$item->ID) {
			return null;
		}
		$sql_obj = new stdClass();
		$sql_obj->ID = $item->ID;
		foreach ($values as $k_field_with_prefix => $v_field) {
			if (substr($k_field_with_prefix, 0, strlen($prefix)) != $prefix) {
				continue;
			}
			$k_field = substr($k_field_with_prefix, strlen($prefix));
			if ($this->field_allow_write($k_field)) {
				if ($this->field_check_value($k_field, $v_field)) {
					$sql_obj->$k_field = $v_field;
				}
			}
		}
		$affected = $this->_db->PDATE_OBJ($this->_tbl, $sql_obj);
		return $affected;
	}

	function add_item($values, $prefix) {
		$sql_obj = new stdClass();
		foreach ($values as $k_field_with_prefix => $v_field) {
			if (substr($k_field_with_prefix, 0, strlen($prefix)) != $prefix) {
				continue;
			}
			$k_field = substr($k_field_with_prefix, strlen($prefix));
			if ($this->field_allow_create($k_field)) {
				if ($this->field_check_value($k_field, $v_field)) {
					$sql_obj->$k_field = $v_field;
				}
			}
		}
		$insert_id = $this->_db->ADD_NEW_OBJ($this->_tbl, $sql_obj);
		return $insert_id;
	}

	public function getGeomFields() {
		return $this->_geomFields;
	}

	public function isGeomField($fldName) {
		return in_array($fldName, $this->_geomFields);
	}

	public function updateItem($item) {
		if (!$item->ID) return false;

		$affected = $this->_db->UPDATE_OBJ($this->_tbl, $item);
		return $affected;
	}

	public function getDbErrors() {
		$errors = array();
		if ($this->_db->has_errors()) {
			$errors = $this->_db->get_errors();
		}
		return $errors;
	}

}
