<?php

class Links_Database
{
	//DB
	var $_db;
	var $_table;

	var $_where = NULL;
	var $_order = NULL;

	var $_Links = NULL;

	/**
	 * Constructor
	 **/
	function __construct($mydirname)
	{
		$this->_db = icms_db_Factory::instance();
		$this->_table = $this->_db->prefix($mydirname .'_'. $this->_class_name);
	}

	function setLinks($Links)
	{
		$this->_Links = $Links;
	}

	function _get_data_by_id($primary_id)
	{
		$this->setWhere($this->_primary_key, $primary_id, '=');
		$data = $this->_get_datas();

		if (count($data) == 1) {
			return $data[0];
		} else {
			return NULL;
		}
	}

	function getDatas()
	{
		return $this->_get_datas();
	}

	function _get_datas($limit = NULL, $offset = NULL)
	{
		$where = empty($this->_where) ? '': " WHERE " . $this->_where;
		$order = empty($this->_order) ? '': " ORDER BY " . $this->_order;
		$sql = "SELECT * FROM ". $this->_table . $where . $order;
//var_dump($sql);
		$result = $this->_db->query($sql, $limit, $offset);
		$datas = array();
		$class_vars = get_class_vars(ucfirst($this->_class_name));
		while ($row = $this->_db->fetchArray($result)) {
			$row_c = array();
			foreach ($class_vars as $key => $val) {
				if (strpos($key, '_') !== 0 AND (!empty($row[$key]) || $row[$key]==0)) {
					$row_c[$key] = $this->_output_filter($row[$key], $key);
				} else if (!empty($row[$key])) {
					$row_c[$key] = NULL;
				}
			}
			$datas[] = $row_c;
		}

		$this->_clear_query();
		return $datas;
	}

	function getCount()
	{
		$where = empty($this->_where) ? '': " WHERE " . $this->_where;
		$sql = "SELECT COUNT(*) FROM ". $this->_table . $where;
	//	var_dump($sql);exit;
		$result = $this->_db->query($sql);
		list($count) = $this->_db->fetchRow($result);

		$this->_clear_query();
		return $count;
	}

	function _delete($primary_id)
	{
		if ($this->_get_data_by_id($primary_id)) {
			$sql = "DELETE FROM ". $this->_table ." WHERE ". $this->_primary_key ."=". $primary_id;
			$this->_db->query($sql) or die('DB error : DELETE'. $this->_class_name);

			return TRUE;
		} else {
			return FALSE;
		}
	}

	function _save($force = FALSE)
	{
		$primary = $this->_primary_key;// TODO ?

		$result = FALSE;
		if (!empty($this->$primary)) {
			$result = $this->_save_update($force);
		} else {
			$result = $this->_save_insert($force);
		}

		return $result;
	}

	function _save_insert($force = FALSE)
	{
		$class_vars = get_class_vars(ucfirst($this->_class_name));

		$fields = '';
		$values = '';
		foreach($class_vars as $key => $val) {
			if (strpos($key, '_') !== 0 AND isset($this->$key)) {
				if (!empty($fields)) $fields .= ", ";
				$fields .= '`'. $key .'`';
				if (!empty($values)) $values .= ", ";
				$values .= "'". mysql_real_escape_string($this->$key) ."'";
			}
		}

		$sql = "INSERT INTO ". $this->_table ." ($fields) VALUES ($values)";
//var_dump($sql);exit;
		if ($force == TRUE) {
			$this->_db->queryF($sql) or die('DB error [F] : INSERT'. $this->_class_name);
		} else {
			$this->_db->query($sql) or die('DB error : INSERT'. $this->_class_name);
		}

		return TRUE;
	}

	function _save_update($force = FALSE)
	{
		$primary = $this->_primary_key;
		$class_vars = get_class_vars(ucfirst($this->_class_name));

		$save_data = '';
		foreach($class_vars as $key => $val) {
			if (strpos($key, '_') !== 0 AND isset($this->$key) AND $key != $primary) {
				if (!empty($save_data)) $save_data .= ", ";
				$save_data .= "`$key`='". mysql_real_escape_string($this->$key) ."'";
			}
		}

		$sql = "UPDATE ". $this->_table ." SET $save_data WHERE $primary=". $this->$primary;
//var_dump($sql);
		if ($force == TRUE) {
			$this->_db->queryF($sql) or die('DB error [F] : UPDATE '. $this->_class_name);
		} else {
			$this->_db->query($sql) or die('DB error : UPDATE '. $this->_class_name);
		}

		return TRUE;
	}

	function setWhere($field, $value, $op = '', $and_or = 'AND')
	{
		if (! empty($this->_where)) {
			$this->_where .= ($and_or == 'AND') ? ' AND ': ' OR ';
		}
		if (!in_array($op, array('=', '<', '>', '<=', '>=', '<>', 'LIKE'))) {
			$op = '';
		}
		$this->_where .= " `". $this->_db->quote($field) ."` ". $op ." '". $this->_db->quote($value) ."' ";
	}

	function _set_order($order)
	{
		$this->_order = $order;
	}

	function _clear_query()
	{
		unset($this->_where);
		unset($this->_order);
	}

	function _get_POST_data()
	{
		$class_vars = get_class_vars(ucfirst($this->_class_name));

		foreach ($class_vars as $key => $val) {
			if (strpos($key, '_') !== 0 AND isset($_POST[$key]) AND empty($this->$key)) { //TODO empty
				$this->$key = $this->_receive_filter($key);
			}
		}
	}

	function _receive_filter($key)
	{
		$rules = explode('|', $this->_rules[$key]);

		if (!empty($rules[0]) && strpos($rules[0], '_') !== 0) {
			switch ($rules[0]) {
				case 'int':
					$data = intval($_POST[$key]);
					break;
				case 'float':
					$data = floatval($_POST[$key]);
					break;
				case 'text':
				case 'varchar':
				default:
					$data = $this->_Links->stripSlashesGPC($_POST[$key]);
					break;
			}
		} else {
			die('No Rule');
		}

		for($i =1; $i < count($rules); $i++) {
			if (strpos($rules[$i], '_in_') === 0) {
				$func = $rules[$i];
				$data = $this->$func($data);
			}
		}

		return $data;
	}

	function _output_filter($data, $key)
	{
		$data_e = '';

		$rules = explode('|', $this->_rules[$key]);

		if (!empty($rules[0]) && strpos($rules[0], '_') !== 0) {
			switch ($rules[0]) {
				case 'int':
					$data_e = intval($data);
					break;
				case 'float':
					$data_e = floatval($data);
					break;
				case 'text':
				case 'varchar':
				default:
					$data_e = htmlspecialchars($data, ENT_QUOTES, _CHARSET);
					break;
			}
		} else {
			$data_e = htmlspecialchars($data, ENT_QUOTES, _CHARSET);
		}

		for($i =1; $i < count($rules); $i++) {
			if (strpos($rules[$i], '_out_') === 0) {
				$func = $rules[$i];
				$data_e = $this->$func($data_e);
			}
		}

		return $data_e;
	}



}
