<?php

require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/BeanBase.class.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/ViewTypeFactory.class.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/Utils.class.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/DataTypeFactory.class.php';
require_once dirname(dirname(__FILE__)) . '/core/UserField.class.php';

/**
 * @brief operate user_field_detail table
 *
 */
class User_FieldDetailBean extends Xoonips_BeanBase {
	/**
	 * Constructor
	 **/
	public function User_FieldDetailBean($dirname, $trustDirname) {
		$this->Xoonips_BeanBase($dirname, $trustDirname);
		$this->setTableName('field_detail', true);
	}

	/**
	 * insert new user field
	 *
	 * @param  $info: user field info
	 * @return boolean  true:success,false:failed
	 */
	public function insert($info, &$insertId) {
		$sql = "INSERT INTO $this->table (released, preselect, table_name, column_name, group_id, weight, name, xml,"
			. ' view_type_id, data_type_id, data_length, data_decimal_places, default_value, list, essential, list_display, '
			. ' list_sort_key, list_width, detail_display, registry_user, edit_user, target_user, scope_search, nondisplay, update_id)';
		$sql .= " VALUES ("
			. Xoonips_Utils::convertSQLNum($info['released']) . ','
			. Xoonips_Utils::convertSQLNum($info['preselect']) . ','
			. Xoonips_Utils::convertSQLStr($info['table_name']) . ','
			. Xoonips_Utils::convertSQLStr($info['column_name']) . ','
			. Xoonips_Utils::convertSQLNum($info['group_id']) . ','
			. Xoonips_Utils::convertSQLNum($info['weight']) . ','
			. Xoonips_Utils::convertSQLStr($info['name']) . ','
			. Xoonips_Utils::convertSQLStr($info['xml']) . ','
			. Xoonips_Utils::convertSQLNum($info['view_type_id']) . ','
			. Xoonips_Utils::convertSQLNum($info['data_type_id']) . ','
			. Xoonips_Utils::convertSQLNum($info['data_length']) . ','
			. Xoonips_Utils::convertSQLNum($info['data_decimal_places']) . ','
			. Xoonips_Utils::convertSQLStr($info['default_value']) . ','
			. Xoonips_Utils::convertSQLStr($info['list']) . ','
			. Xoonips_Utils::convertSQLNum($info['essential']) . ','
			. Xoonips_Utils::convertSQLNum($info['list_display']) . ','
			. Xoonips_Utils::convertSQLNum($info['list_sort_key']) . ','
			. Xoonips_Utils::convertSQLNum($info['list_width']) . ','
			. Xoonips_Utils::convertSQLNum($info['detail_display']) . ','
			. Xoonips_Utils::convertSQLNum($info['registry_user']) . ','
			. Xoonips_Utils::convertSQLNum($info['edit_user']) . ','
			. Xoonips_Utils::convertSQLNum($info['target_user']) . ','
			. Xoonips_Utils::convertSQLNum($info['scope_search']) . ','
			. Xoonips_Utils::convertSQLNum($info['nondisplay']) . ','
			. Xoonips_Utils::convertSQLNum($info['update_id']) . ')';
		$result = $this->execute($sql);
		if (!$result) {
			return false;
		}
		$insertId = $this->getInsertId();
		return true;
	}

	/**
	 *
	 * get user field list
	 *
	 * @return user field list
	 */
	public function getReleasedDetail() {
		$ret = array();
		$sql = 'SELECT * FROM ' . $this->table . " WHERE update_id IS NULL AND released='1'";
		$result = $this->execute($sql);
		if (!$result) {
			return $ret;
		}
		while ($row = $this->fetchArray($result)) {
			$ret[] = $row;
		}
		$this->freeRecordSet($result);
		return $ret;
	}

	/**
	 * update table_name
	 *
	 * @param  $detail_id
	 * @return boolean  true:success,false:failed
	 */
	public function updateTableName($detailId) {
		$table_name = $this->modulePrefix('extend') . $detailId;
		$sql = "UPDATE $this->table SET table_name='$table_name' WHERE user_detail_id=$detailId"
			. " AND table_name LIKE '$this->dirname" . "_extend%' " ;
		$result = $this->execute($sql);
		if (!$result) {
			return false;
		}
		return true;
	}

	/**
	 * do copy by obj
	 *
	 * @param  $detailObj, $map
	 * @return boolean true:success,false:failed
	 */
	public function copyByObj($detailObj, &$map, $update, $import) {

		// insert copy
		foreach ($detailObj as $detail) {

			$detail['released'] = $import ? $detail['released'] : 0;
			$detail['group_id'] = $map['group'][$detail['group_id']];
			$detail['update_id'] = $update ? $detail['user_detail_id'] : NULL;

			$insertId = null;
			if (!$this->insert($detail, $insertId)) return false;
			$map['detail'][$detail['user_detail_id']] = $insertId;

			if ($update) continue;
			if (!$this->updateTableName($insertId)) return false;
		}
		return true;
	}

	/**
	 * create extend table
	 *
	 * @param  $detail
	 * @return boolean true:success,false:failed
	 */
	public function createExtendTable($detailObj) {

		foreach ($detailObj as $detail) {

			// view type to confirm create item extend table, except (id, title, keyword, file upload, create date,
			// last update, create user, change log, index, relation item, preview)
			$viewtypeObj = Xoonips_ViewTypeFactory::getInstance($this->dirname, $this->trustDirname)->getViewType($detail['view_type_id']);
			$tmp = strPos($detail['table_name'], $this->dirname . '_extend');
			if (!$viewtypeObj->mustCreateItemExtendTable() || strPos($detail['table_name'], $this->dirname . '_extend') === false) {
				continue;
			}

			// check table exsit
			$tableName = $this->prefix($this->modulePrefix('extend') . $detail['user_detail_id']);
			$result = $this->execute("SHOW TABLES LIKE '$tableName'");
			if (!$result) return false;
			while ($row = $this->fetchArray($result)) {
				continue;
			}

			// data type to confirm create 'value' column
			$field = new User_UserField();
			$field->setLen($detail['data_length']);
			$field->setDecimalPlaces($detail['data_decimal_places']);
			$field->setDefault($detail['default_value']);
			$field->setEssential($detail['essential']);
			$datatypeObj = Xoonips_DataTypeFactory::getInstance($this->dirname, $this->trustDirname)->getDataType($detail['data_type_id']);
			$valueSql = $datatypeObj->getValueSql($field);

			$createSql = " CREATE TABLE $tableName ("
  				. " uid int(10) unsigned NOT NULL default '0',"
  				. " group_id int(10) unsigned default '0',"
				. ' value ' . $valueSql[0] . ','
				. " occurrence_number smallint(3) unsigned NOT NULL default '1',"
				. ' PRIMARY KEY (uid, group_id, occurrence_number),'
				. ' KEY value (value' . $valueSql[1] . ')'
				. ') ENGINE=InnoDB;';
			$createRes = $this->execute($createSql);
			if (!$createRes) return false;
		}
		return true;
	}

	/**
	 *
	 * get field xml
	 *
	 * @param int $fieldId : field id
	 * @return  string $ret : field name
	 */
	public function getFieldXml($fieldId) {
		$ret = '';
		$sql = 'SELECT xml FROM ' . $this->table . " WHERE user_detail_id=$fieldId";
		$result = $this->execute($sql);
		if (!$result) {
			return $ret;
		}
		while ($row = $this->fetchArray($result)) {
			$ret = $row['xml'];
		}
		$this->freeRecordSet($result);
		return $ret;
	}
	
}

