<?php
/*======================================================================*\
|| #################################################################### ||
|| # Country Flags for XenForo                                        # ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright © 2015 Snog. All Rights Reserved.                      # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ---------------------------------------------------------------- # ||
|| #                     http://snogssite.com                         # ||
|| #################################################################### ||
\*======================================================================*/

class Snog_CountryFlags_Model_Thread extends XFCP_Snog_CountryFlags_Model_Thread
{
	public function prepareThreadConditions(array $conditions, array &$fetchOptions)
	{
		$parentResult = parent::prepareThreadConditions($conditions, $fetchOptions);

		$visitor = XenForo_Visitor::getInstance();

		if(array_key_exists('snog_flag',$conditions) && $conditions['snog_flag'] > '' && $conditions['snog_flag'] !== 'ALL')
		{
			if($visitor['is_admin'] || $visitor['is_moderator'])
			{
				$parentResult = $parentResult . " AND (user.snog_flag = '" . $conditions['snog_flag'] . "')";
			}else{
				if($visitor['user_id'] <= 0)
				{
					$parentResult = $parentResult . " AND (user.snog_flag = '" . $conditions['snog_flag'] . "') AND (privacy.snog_flag_view = 'everyone')";
				}else{
					$parentResult = $parentResult . " AND (user.snog_flag = '" . $conditions['snog_flag'] . "') AND (privacy.snog_flag_view = 'everyone' OR privacy.snog_flag_view = 'members')";
				}
			}
		}

		return $parentResult;
	}

	public function prepareThreadFetchOptions(array $fetchOptions)
	{
		$userOptions = parent::prepareThreadFetchOptions($fetchOptions);

		$userOptions['selectFields'] .= ',
				privacy.snog_flag_view';

		$userOptions['joinTables'] .= '
				LEFT JOIN xf_user_privacy AS privacy ON
					(privacy.user_id = thread.user_id)';

		return $userOptions;
	}

	public function countThreads(array $conditions)
	{
		if(array_key_exists('snog_flag',$conditions) && $conditions['snog_flag'] > '' && $conditions['snog_flag'] !== 'ALL')
		{
			$fetchOptions = array();
			$whereConditions = $this->prepareThreadConditions($conditions, $fetchOptions);
			$sqlClauses['joinTables'] = '
				LEFT JOIN xf_user AS user ON (user.user_id = thread.user_id)';
			$sqlClauses['joinTables'] .= '
				LEFT JOIN xf_user_privacy AS privacy ON (privacy.user_id = thread.user_id)';

			return $this->_getDb()->fetchOne('
				SELECT COUNT(*)
				FROM xf_thread AS thread
				' . $sqlClauses['joinTables'] . '
				WHERE ' . $whereConditions . '
			');
		}else{
			return parent::countThreads($conditions);
		}
	}
}