<?

class lc_chat
{
	public function lc_main()
	{
		if (!access('read')) return LabCMS::i()->error('Вы не можете просматривать чат.');
		$max=Db::i()->selectCell("SELECT id FROM ?_lc_chat ORDER BY id DESC LIMIT 50, 1");
		if ($max) Db::i()->query("DELETE FROM ?_lc_chat WHERE id <? AND moderator=0", $max);
		$this->_setUserOnline();
		LabCMS::i()->setModuleTemplate('main.tpl');
	}
	
	public function lc_post()
	{
		User::checkToken();
		if (trim($_POST['msg']) && access('write'))
		{
			if (!$post=$this->_checkPost($_POST['msg'])) return false;
			if (!$this->_post(User::i()->login, $post)) return $this->error('Ошибка добавления сообщения');
		}
		return $this->lc_get();
	}
	
	public function lc_get()
	{
		if (!access('read')) return $this->error("Недостаточно прав для просмотра сообщений");
		return array('posts'=>$this->_get($_POST['id']));
	}
	
	public function lc_getOnliners()
	{
		if (!access('read')) return LabCMS::i()->error('Вы не можете просматривать чат.');
		$this->_setUserOnline();
		$users=Db::i()->selectCol("SELECT user_id AS ARRAY_KEY, login FROM ?_lc_chat_online WHERE `time`<NOW()-INTERVAL 2 MINUTE");
		if ($users)
		{
			foreach($users as $user_id=>$login)
			{
				$this->_postInfoMessage($login.' вышел из чата.');
			}
			Db::i()->query("DELETE FROM ?_lc_chat_online WHERE user_id IN (?a)", array_keys($users));
		}
		$onliners=Db::i()->select("SELECT login, user_id FROM ?_lc_chat_online ORDER BY login");
		return array('onliners'=>$onliners);
	}

	protected function _postInfoMessage($mess)
	{
		Db::i()->query("INSERT INTO ?_lc_chat (text, info) VALUES(?, 1)", $mess);
	}
	
	protected function _setUserOnline()
	{
		$new=Db::i()->query("INSERT INTO ?_lc_chat_online (login, user_id, `time`) VALUES(?, ?, NOW())
		ON DUPLICATE KEY UPDATE `time`=NOW()", User::i()->login, User::i()->id);
		if ($new==1) $this->_postInfoMessage(User::i()->login.' вошел в чат');
	}
	
	protected function _get($id)
	{
		return Db::i()->select("SELECT * FROM ?_lc_chat {WHERE id>?} AND moderator=0 ORDER BY id", $id);
	}
	
	protected function _post($login, $post)
	{
		//добавляем сообщение
		return Db::i()->query("INSERT INTO ?_lc_chat (login, text, `time`) VALUES(?, ?, NOW())", $login, $post);
	}
	
	protected function _checkPost($post)
	{
		return getbb($post);
	}
	
	protected function error($msg, $lang=false)
	{
		return LabCMS::i()->error($msg, $lang);
	}
	
	static function assign($key, $var=null)
	{
		if (is_array($key)) Tpl::i()->assign($key);
		else Tpl::i()->assign($key, $var);
	}
	
	function setTpl($tpl='')
	{
		if ($tpl) LabCMS::i()->setModuleTemplate($tpl.".tpl");
		else LabCMS::i()->setModuleTemplate("");
	}
}