<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

class lc_comments_list
{
	public function __construct()
	{
		Factory::load('lc_comments.comment');
	}
	
	public function getCommentsByItem($item)
	{
		$comments=TCache::get('comments_list_by_item_id_'.$item->id);
		
		if (!is_array($comments)) {
			$result=Db::i()->select(
				"SELECT *
				FROM ?_comments c
				WHERE item_id=?
				ORDER BY left_key", $item->id
			);
			//проверка структуры комментариев.
			if ($result && access('admin')
				&& $error=$item->checkStructure()
			) {
				LabCMS::i()->setMessage(
					_m('Нарушена структура комментариев. ').$error, false, true
				);
			}
			$comments=$this->_setCommentsFromArray($result);
			
			TCache::set($comments, 'comments_list_by_item_id_'.$item->id, array('comments_item_id_'.$item->id));
		}
		
		

		$this->setCommentsUserData($comments);
		$this->_setObjects($comments, $item);
		return $comments;
	}
	
	protected function _setUsers(&$comments)
	{
		$users=array();
		foreach ($comments as $comment) {
			if ($comment->user_id) $users[]=$comment->user_id;
		}
		if ($users) $users=User::i()->getUsersByIds($users);
		
		foreach ($comments as $comment) {
			if ($comment->user_id) {
				$comment->user=$users[$comment->user_id];
			} else {
				$comment->user=User::getUser();
				$comment->user->set(array('login'=>$comment->login, 'email'=>$comment->email));
			}
		}
		
		unset($users);
	}
	
	protected function _setCommentsFromArray($result, $item=null)
	{
		$comments=array();
		if ($result) {
			while ($data=array_shift($result)) {
				$data['text_html']=getbb($data['text']);
				$data['ip']=inet_ntop($data['ip']);
				$comment=Factory::create('lc_comments.comment');
				$comment->set($data);
				if ($item) $comment->item=$item;
				$comments[]=$comment;
			}
		}
		
		return $comments;
	}
	
	protected function _setObjects(&$comments, $item=null, $user=null)
	{
		if ($item || $user) {
			foreach ($comments as $key=>$comment) {
				if ($item) $comment->item=$item;
				if ($user) $comment->item->user=$user;
			}
		}
		$this->_setUsers($comments);
		if (!$item) $this->_setItems($comments);
		return $comments;
	}
	
	protected function _setItems(&$comments)
	{
		$items=array();
		foreach ($comments as $comment) {
			$items[]=$comment->item_id;
		}
		$item=Factory::create('lc_comments.item');
		if ($items=$item->getItemsByIds($items)) {
			foreach ($comments as $comment) {
				$comment->item=$items[$comment->item_id];
			}
		}
	}
	
	public function setCommentsUserData(&$comments)
	{
		if (User::i()->isGuest()) return;
		if (config::get('module.lc_comments.rating_enable') && $comments) {
			$voter=Rating_Generic::init();
			$voter->setModuleId(LabCMS::i()->getModuleIdByName('lc_comments'));
			foreach ($comments as $comment) {
				$ids[]=$comment->id;
			}
			if ($votes=$voter->getUserItemVotes($ids)) {
				foreach ($comments as $comment) {
					$comment->voted=$votes[$comment->id];
				}
			}
		}
		
	}
	
	public function getCommentsByAbused()
	{
		$result=Db::i()->select(
			"SELECT * FROM ?_comments_items ci
			JOIN ?_comments c ON ci.item_id=c.item_id
			WHERE abuse IS NOT NULL
			ORDER BY left_key"
		);
		if ($result) {
			$comments=$this->_setCommentsFromArray($result);
			$this->setCommentsUserData($comments);
			$this->_setObjects($comments);
			return $comments;
		}
	}
	
	public function getAbusedCounter()
	{
		return Db::i()->selectCell(
			"SELECT COUNT(comment_id) FROM ?_comments_items ci
			JOIN ?_comments c ON ci.item_id=c.item_id
			WHERE abuse IS NOT NULL"
		);
	}
	
	public function getCommentsByModeration()
	{
		$result=Db::i()->select(
			"SELECT * FROM ?_comments_items ci
			JOIN ?_comments c ON ci.item_id=c.item_id
			WHERE `status`=2
			ORDER BY left_key"
		);
		if ($result) {
			$comments=$this->_setCommentsFromArray($result);
			$this->setCommentsUserData($comments);
			$this->_setObjects($comments);
			return $comments;
		}
	}
	
	public function getModerationCounter()
	{
		//TODO убрать магические числа
		return Db::i()->selectCell(
			"SELECT COUNT(comment_id) FROM ?_comments_items ci
			JOIN ?_comments c ON ci.item_id=c.item_id
			WHERE `status`=2"
		);
	}
	
	public function updateAbusedComments($data)
	{
		if (!empty($data)) foreach ($data as $comment_id=>$action) {
			$cmt=Factory::create('lc_comments.comment', $comment_id);
			if ($action=='del' || $action=='ok') {
				if ($action=='del') $cmt->delete();
				$cmt->resetAbuse();
			}
		}
	}
	
	public function updatePremoderatedComments($data)
	{
		if (!empty($data)) foreach ($data as $comment_id=>$action) {
			$cmt=Factory::create('lc_comments.comment', $comment_id);
			if ($action=='del' || $action=='ok') {
				if ($action=='del') $cmt->deleteBranch();
				$cmt->unhide();
			}
		}
	}
	
	public function deleteOldComments()
	{
		$modules=Db::i()->selectCol(
			"SELECT module_id FROM ?_comments_items
			WHERE module_id NOT IN
			(SELECT module_id FROM ?_modules)"
		);
		
		if ($modules) {
			Db::i()->query(
				"DELETE FROM ?_comments WHERE item_id IN(SELECT ?_comments_items WHERE module_id IN(?a))", $modules
			);
			
			Db::i()->query(
				"DELETE FROM ?_comments_items WHERE module_id IN(?a)", $modules
			);
		}
	}
	
	public function getCommentsCounters($items, $type=1)
	{
		return Db::i()->selectCol(
			"SELECT `key` AS ARRAY_KEY, counter
			FROM ?_comments_items
			WHERE `key` IN (?a) AND `type`=? AND module_id=?",
			(array)$items, $type, LabCMS::i()->getModuleId()
		);
	}
	
	public function getNewComments($item, $comment_id)
	{
		$result=Db::i()->select(
			"SELECT * FROM ?_comments 
			WHERE {comment_id>? AND }item_id=?",
			$comment_id?$comment_id:DBSIMPLE_SKIP, $item->id
		);
		
		if ($result) return $this->_setCommentsFromArray($result);
	}
	
	public function getLastComments($item)
	{
		$result=Db::i()->select(
			"SELECT *
			FROM ?_comments
			WHERE 1=1
			{AND item_id=?}
			ORDER BY left_key DESC
			{LIMIT ?d}",
			$item?$item->id:DBSIMPLE_SKIP,
			$item?DBSIMPLE_SKIP:50
		);
		
		if ($result) {
			$comments=$this->_setCommentsFromArray($result);
			$this->setCommentsUserData($comments);
			$this->_setObjects($comments);
			return $comments;
		}
	}
}