<?php

/**
* Model for moderators.
*
* @package ModEss
*/
class ModEss_Model_Moderator extends XFCP_ModEss_Model_Moderator
{
	/**
	 * Gets all matching content moderators for the specified node ids.
	 *
	 * @param array $nodeIds
	 *
	 * @return array Format: [user id] => info
	 */
	public function getForumModerators(array $nodeIds)
	{
		if (!$nodeIds)
		{
			return array();
		}
		
		$db = $this->_getDb();
		$options = XenForo_Application::get('options');
		$order = $options->modess_show_forum_moderators_order;
		
		if ($order == 'last_activity')
			$orderBy = 'activity.view_date DESC, user.last_activity DESC';
		else if ($order == 'username_desc')
			$orderBy = 'user.username DESC';
		else
			$orderBy = 'user.username ASC';
		
		if ($options->modess_exclude_non_staff_forum_moderators)
			$isStaff = ' AND user.is_staff = 1';
		else
			$isStaff = '';
		
		return $this->fetchAllKeyed(
			'
				SELECT moderator_content.*, user.*, IF (activity.view_date IS NULL, user.last_activity, activity.view_date) AS last_activity
				FROM xf_moderator_content AS moderator_content
				INNER JOIN xf_user AS user ON (user.user_id = moderator_content.user_id' . $isStaff . ')
				LEFT JOIN xf_session_activity AS activity ON (activity.user_id = moderator_content.user_id)
				WHERE moderator_content.content_type = ' . $this->_getDb()->quote('node') . ' AND moderator_content.content_id IN (' . $db->quote($nodeIds) . ')
				ORDER BY ' . $orderBy. '
			'
		, 'username');
	}
	
	/**
	 * Gets all matching super and content moderators for the specified node ids.
	 *
	 * @param array $nodeIds
	 *
	 * @return array Format: [user id] => info
	 */
	public function getSuperAndForumModerators(array $nodeIds)
	{
		if (!$nodeIds)
		{
			return array();
		}
		
		$db = $this->_getDb();
		$options = XenForo_Application::get('options');
		$order = $options->modess_show_forum_moderators_order;
		
		if ($order == 'last_activity')
			$orderBy = 'activity.view_date DESC, user.last_activity DESC';
		else if ($order == 'username_desc')
			$orderBy = 'user.username DESC';
		else
			$orderBy = 'user.username ASC';
		
		if ($options->modess_exclude_non_staff_forum_moderators)
			$isStaff = ' AND user.is_staff = 1';
		else
			$isStaff = '';
		
		return $this->fetchAllKeyed(
			'
				SELECT moderator.*, user.*, IF (activity.view_date IS NULL, user.last_activity, activity.view_date) AS last_activity
				FROM xf_moderator AS moderator
				INNER JOIN xf_user AS user ON (user.user_id = moderator.user_id' . $isStaff . ')
				LEFT JOIN xf_moderator_content AS moderator_content ON (moderator_content.user_id = moderator.user_id)
				LEFT JOIN xf_session_activity AS activity ON (activity.user_id = moderator.user_id)
				WHERE moderator.is_super_moderator = 1 OR (moderator_content.content_type = ' . $db->quote('node') . ' AND moderator_content.content_id IN (' . $db->quote($nodeIds) . '))
				ORDER BY ' . $orderBy. '
			'
		, 'username');
	}
}