<?php

class Andy_NewPosts_ControllerPublic_Forum extends XFCP_Andy_NewPosts_ControllerPublic_Forum
{
	public function actionIndex()
	{
		// get parent		
		$parent = parent::actionIndex();
		
		//return $parent;	
		
		// get user group permissions
		if (!XenForo_Visitor::getInstance()->hasPermission('newPostsGroupID', 'newPostsID'))
		{
			return $parent;
		}	
		
		// return if rss
		if ($this->_routeMatch->getResponseType() == 'rss')	
		{
			return $parent;
		}
		
		// get options from Admin CP -> Options -> Sidebar Positions -> New Posts Position
		$newPostsPosition = XenForo_Application::get('options')->newPostsPosition;
		
		// return if newPostsPosition is 0
		if ($newPostsPosition == 0)	
		{
			return $parent;
		}
		
		//########################################
		// new posts results
		// see code in FindNew.php 
		//########################################

		$threadModel = $this->_getThreadModel();
		$this->getModelFromCache('XenForo_Model_Search');

		$userId = XenForo_Visitor::getUserId();
		$visitor = XenForo_Visitor::getInstance();

		$limitOptions = array(
			'limit' => XenForo_Application::get('options')->maximumSearchResults
		);

		$days = $this->_input->filterSingle('days', XenForo_Input::UINT);
		$recent = $this->_input->filterSingle('recent', XenForo_Input::UINT);
		$watched = $this->_input->filterSingle('watched', XenForo_Input::UINT);

		if ($userId && !$days && !$recent)
		{
			$threadIds = $threadModel->getUnreadThreadIds($userId, $limitOptions, $watched);

			$searchType = 'new-posts';
		}
		else
		{
			if ($days < 1)
			{
				$days = max(7, XenForo_Application::get('options')->readMarkingDataLifetime);
			}

			$fetchOptions = $limitOptions + array(
				'order' => 'last_post_date',
				'orderDirection' => 'desc',
				'watchUserId' => $userId,
				'forumWatchUserId' => $userId,
				'join' => XenForo_Model_Thread::FETCH_FORUM_OPTIONS
			);

			$threadIds = array_keys($threadModel->getThreads(array(
				'last_post_date' => array('>', XenForo_Application::$time - 86400 * $days),
				'not_discussion_type' => 'redirect',
				'deleted' => false,
				'moderated' => false,
				'find_new' => true,
				'watch_only' => $watched
			), $fetchOptions));

			$searchType = 'recent-posts';
		}

		$threads = $threadModel->getThreadsByIds(
			$threadIds,
			array(
				'join' =>
					XenForo_Model_Thread::FETCH_FORUM |
					XenForo_Model_Thread::FETCH_USER,
				'permissionCombinationId' => $visitor['permission_combination_id']
			)
		);
		foreach ($threads AS $key => $thread)
		{
			$thread['permissions'] = XenForo_Permission::unserializePermissions($thread['node_permission_cache']);

			if (!$threadModel->canViewThreadAndContainer($thread, $thread, $null, $thread['permissions'])
				|| $visitor->isIgnoring($thread['user_id'])
			)
			{
				unset($threads[$key]);
			}
		}

		// declare varaible
		$results = array();
		
		foreach ($threadIds AS $threadId)
		{
			if (isset($threads[$threadId]))
			{
				$results[] = $threadId;
			}
		}		
		
		// return if empty reults
		if (empty($results))
		{
			return $parent;
		}
	
		//########################################
		// get limit
		//########################################

		// get options from Admin CP -> Options -> New Posts -> Limit
		$limit = XenForo_Application::get('options')->newPostsLimit;	
		
		//########################################
		// limit to these thread results
		//########################################
		
		// define variable;
		$whereclause1 = '';
		
		// create whereclause of viewable nodes
		$whereclause1 = 'AND (xf_thread.thread_id = ' . implode(' OR xf_thread.thread_id = ', $results);
		$whereclause1 = $whereclause1 . ')';		
		
		//########################################
		// exclude forums
		//########################################	
		
		// define variable;
		$whereclause2 = '';			
		
		// get options from Admin CP -> Options -> New Posts -> Exclude Forums
		$excludeForums = XenForo_Application::get('options')->newPostsExcludeForums;
		
		if ($excludeForums != '')
		{
			// remove trailing comma
			$excludeForums = rtrim($excludeForums, ',');				
			
			$nodeIds = explode(',', $excludeForums);		
			
			// create whereclause of excluded forums
			$whereclause2 = 'AND (xf_thread.node_id <> ' . implode(' AND xf_thread.node_id <> ', $nodeIds);
			$whereclause2 = $whereclause2 . ')';
		}
		
		//########################################
		// get newPosts
		//########################################			

		// get database
		$db = XenForo_Application::get('db');
				
		// run query		
		$newPosts = $db->fetchAll("
		SELECT xf_thread.thread_id, 
		xf_thread.title,
		xf_thread_user_post.post_count AS user_post_count, 
		xf_node.node_id,
		xf_node.title AS nodeTitle, 
		xf_post.message,
		xf_user.avatar_date,
		xf_user.user_id
		FROM xf_thread
		INNER JOIN xf_node ON xf_node.node_id = xf_thread.node_id
		INNER JOIN xf_post ON xf_post.post_id = xf_thread.first_post_id		
		INNER JOIN xf_user ON xf_user.user_id = xf_thread.user_id	
		LEFT JOIN xf_thread_user_post AS xf_thread_user_post
		ON (xf_thread_user_post.thread_id = xf_thread.thread_id
		AND xf_thread_user_post.user_id = " . $userId . ")					
		WHERE xf_thread.discussion_state = 'visible'
		AND xf_thread.discussion_type <> 'redirect'
		$whereclause1
		$whereclause2
		ORDER BY xf_thread.last_post_date DESC
		LIMIT " . $limit . "
		");
		
		// declare variables
		$newPostsNew = array();
		$i = 0;		
		
		// add to multidimensional array
		foreach ($newPosts as $k => $v)
		{ 
			// prepare array
			$forumArray = array('forum' => array(
				'node_id' => $v['node_id'],
				'title' => $v['nodeTitle']
			));
			
			// prepare array
			$hasPreviewArray = array('hasPreview' => true);			

			// merge arrays
			$newPostsNew[] = array_merge($newPosts[$i], $forumArray, $hasPreviewArray);				
			
			$i = $i + 1;
		}
		
		// rename variable
		$newPosts = $newPostsNew;			

		// prepare viewParams
		if ($parent instanceOf XenForo_ControllerResponse_View)
		{
			$viewParams = array(
			'newPosts' => $newPosts
			);
			
			// add viewParams to parent params
			$parent->params += $viewParams;
		}	
		
		// return parent
		return $parent;	
	}
}