<?php
/*****************************************************************************
 * Setting.php
 * Contains key class Setting.
 *
 * Kabuki CMS (C) 2013-2015, Aaron van Geffen
 *****************************************************************************/

class Setting
{
	public static $cache = [];

	public static function set($key, $value, $id_user = null)
	{
		$id_user = Registry::get('user')->getUserId();

		if (isset(self::$cache[$id_user], self::$cache[$id_user][$key]))
			unset(self::$cache[$id_user][$key]);

		if (Registry::get('db')->query('
			REPLACE INTO settings
			(id_user, variable, value, time_set)
			VALUES
			({int:id_user}, {string:key}, {string:value}, CURRENT_TIMESTAMP())',
			[
				'id_user' => $id_user,
				'key' => $key,
				'value' => $value,
			]))
		{
			if (!isset(self::$cache[$id_user]))
				self::$cache[$id_user] = [];

			self::$cache[$id_user][$key] = $value;
		}
	}

	public static function get($key, $id_user = null)
	{
		$id_user = Registry::get('user')->getUserId();

		if (isset(self::$cache[$id_user], self::$cache[$id_user][$key]))
			return self::$cache[$id_user][$key];

		$value = Registry::get('db')->queryValue('
			SELECT value
			FROM settings
			WHERE id_user = {int:id_user} AND variable = {string:key}',
			[
				'id_user' => $id_user,
				'key' => $key,
			]);

		if (!$value)
			return false;

		if (!isset(self::$cache[$id_user]))
			self::$cache[$id_user] = [];

		self::$cache[$id_user][$key] = $value;
		return $value;
	}

	public static function remove($key, $id_user = null)
	{
		$id_user = Registry::get('user')->getUserId();

		if (Registry::get('db')->query('
			DELETE FROM settings
			WHERE id_user = {int:id_user} AND variable = {string:key}',
			[
				'id_user' => $id_user,
				'key' => $key,
			]))
		{
			if (isset(self::$cache[$id_user], self::$cache[$id_user][$key]))
				unset(self::$cache[$id_user][$key]);
		}
	}
}