<?php

/**
 * User profile.
 * @use User
 * @require User
 */
class UserProfile {

	public static function load($force = false) {
		if ($force) {
			$_SESSION['USER_PROFILE'] = array();
		}
		if (empty($_SESSION['USER_PROFILE'])) {
			$_SESSION['USER_PROFILE'] = array();
			// load user profile (hidden column, UserBookmarks)
			$sql = "select `ADM_WWW_PROFILE` from `ADMIN_USERS` where `ADM_ACCOUNT`='".User::getName()."' limit 0,1 ";
			$db = DB::getDB();
			$res = $db->query($sql);
			while ($h = $db->fetch($res)) {
				$ADM_WWW_PROFILE = "{$h->ADM_WWW_PROFILE}";
				if (!empty($ADM_WWW_PROFILE)) {
					//echo "<HR>$ADM_WWW_PROFILE WWW-PROFILE**********<BR>";
					eval("\$_SESSION['USER_PROFILE'] = {$ADM_WWW_PROFILE} ;");
				} else {
					$_SESSION['USER_PROFILE'] = array();
				}
			}
		}
		return $_SESSION['USER_PROFILE'];
	}

	public static function set($key, $val) {
		self::load();// profile must be loaded
		$_SESSION['USER_PROFILE'][$key] = $val;
	}

	public static function get($key) {
		self::load();// profile must be loaded
		return V::get($key, '', $_SESSION['USER_PROFILE']);
	}

	public static function getColumn($column_name, $key) {
		self::load();// profile must be loaded
		if (!empty($_SESSION['USER_PROFILE'][$column_name][$key])) {
			return $_SESSION['USER_PROFILE'][$column_name][$key];
		}
		return null;
	}

	public static function setColumn($column_name, $key, $value) {
		self::load();// profile must be loaded
		$_SESSION['USER_PROFILE'][$column_name][$key] = $value;
		self::save();
	}

	public static function removeColumn($column_name, $key) {
		self::load();// profile must be loaded
		unset($_SESSION['USER_PROFILE'][$column_name][$key]);
		self::save();
	}

	public static function save() {
		self::load();// profile must be loaded
		$db = DB::getDB();

		$USER_PROFILE = $_SESSION['USER_PROFILE'];
		reset($USER_PROFILE);
		$VAR = " Array ( ";
		for ( ;(key($USER_PROFILE)); next($USER_PROFILE)) {
			$VAR = $VAR . "\"" .  key($USER_PROFILE) . "\" => Array ( ";
			for ( ;(key($USER_PROFILE[key($USER_PROFILE)])); next($USER_PROFILE[key($USER_PROFILE)])) {
				$VAR = $VAR . " \"" . key($USER_PROFILE[key($USER_PROFILE)]) . "\"=>\"" . $USER_PROFILE[key($USER_PROFILE)][key($USER_PROFILE[key($USER_PROFILE)])] . "\"," ;
			}
			$VAR = $VAR . " ), ";
		}
		$VAR = $VAR . " ) " ;
		$sql = "update `ADMIN_USERS` set `ADM_WWW_PROFILE`='{$VAR}' where  `ADM_ACCOUNT`='".User::getName()."' limit 1 ";
		$res = $db->query($sql);
		if (($affected = $db->affected_rows($res)) != 1) {
			// TODO: error msg
		}
		return $VAR;
	}

}
