<?php

Lib::loadClass('BaseModel');


class BaseDao {

	var $_db;
	var $_table;
	var $_save_hist_id;
	var $_save_id;

	function __construct($db, $table) {
		$this->_db = $db;
		$this->_table = $table;
		$this->_save_hist_id = 0;
		$this->_save_id = 0;
	}

	function get_by_id( $id ) {
		$null = null;
		$id = (int)$id;
		if ($id <= 0) return $null;
		$sql = "select t.*
			from `" . $this->_table . "` as t
			where t.`ID`='" . $id . "'
		";
		$res = DB::query($sql);
		if ($h = DB::fetch_assoc($res)) {
			$model = new BaseModel($this);
			$model->setDataFromDB($h);
			return $model;
		}
		return $null;
	}

	/**
	 * Save $model into DB.
	 * @returns boolean or integer - created record ID.
	 */
	function save($model) {
		$ret = false;

		$this->_save_hist_id = 0;
		$this->_save_id = 0;

		if ($model->get('ID') > 0) {

			$this->_save_id = $model->get('ID');

			$sql_data = array();
			$data = $model->changes_to_array();
			if (!empty($data)) {
				$data['A_RECORD_UPDATE_DATE'] = date('Y-m-d-H:i');
				$data['A_RECORD_UPDATE_AUTHOR'] =  User::getName();
				foreach ($data as $k_field => $v_value) {
					$sql_data []= "`" . $k_field . "`='" . $v_value . "'";
				}
				$sql = "update `" . $this->_table . "` set " . implode(", ", $sql_data) . " where `ID`='" . $model->get('ID') . "'; ";
				$this->_db->query($sql);
				if ($this->_db->affected_rows() > 0) {
					$ret = true;
				}
			} else {
				$ret = true;
			}
		}
		else {
			$sql_data = array();
			$data = $model->to_array();
			$data['A_RECORD_CREATE_DATE'] = date('Y-m-d-H:i');
			$data['A_RECORD_CREATE_AUTHOR'] =  User::getName();
			foreach ($data as $k_field => $v_value) {
				if (!empty($v_value)) {
					$sql_data["`" . $k_field . "`"] = "'" . $v_value . "'";
				}
			}
			$sql = "insert into `" . $this->_table . "` (" . implode(", ", array_keys($sql_data)) . ") values (" . implode(", ", array_values($sql_data)) . "); ";
			$this->_db->query($sql);
			$this->_save_id = $this->_db->insert_id();
			if ($this->_save_id > 0) {
				$ret = $this->_save_id;
			}
		}

		{// update _HIST if anything changed/created
			if ($this->_save_id > 0 && !empty($data)) {
				$sql_data = array();
				foreach ($data as $key => $val) {
					$sql_data["`" . $key . "`"] = "'" . $val . "'";
				}
				$sql_data["`ID_USERS2`"] = "'" . $this->_save_id . "'";
				$sql_hist = "insert into `" . $this->_table . "_HIST` (" . implode(", ", array_keys($sql_data)) . ") values (" . implode(", ", array_values($sql_data)) . "); ";
				$this->_db->query($sql_hist);
				$this->_save_hist_id = $this->_db->insert_id();
			}
		}

		return $ret;
	}

	public function get_saved_id() {
		return $this->_save_id;
	}

	public function get_saved_hist_id() {
		return $this->_save_hist_id;
	}

}
