<?php
/*======================================================================*\
|| #################################################################### ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright © 2015 Jim Dudek AKA Nhawk/Snog                        # ||
|| # All Rights Reserved.                                             # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ---------------------------------------------------------------- # ||
|| # License: NULLXF99999999999                                       # ||
|| # ---------------------------------------------------------------- # ||
|| # You are not allowed to use this file on your server unless       # ||
|| # you have purchased the raffle system from snogssite.com.         # ||
|| # ---------------------------------------------------------------- # ||
|| #################################################################### ||
\*======================================================================*/

class Snog_Raffles_Controllerpublic_Index extends XenForo_ControllerPublic_Abstract
{
	public function actionIndex()
	{
		$visitor = XenForo_Visitor::getInstance();
		
		if (!$visitor->hasPermission('raffles', 'viewRaffles'))
		{
			return $this->responseNoPermission();
		}

		$admin_timezone = $this->_getUserModel()->getUserById(XenForo_Application::getOptions()->raffles_raffle_admin);
		date_default_timezone_set($admin_timezone['timezone']);
		$raffles = $this->_getRafflesRaffleModel()->getActiveRaffles(time(),$visitor);
		$raffle_count = 0;
		foreach ($raffles as &$raffle)
		{
			if($raffle['stop_timestamp'] <= time() && !$raffle['winner']) $raffle['waiting'] = true;
			if($raffle['winner']) $raffle['drawn'] = true;
			$raffle['description'] = XenForo_Helper_String::wholeWordTrim($raffle['description'], XenForo_Application::getOptions()->raffles_preview_length);
			$formatter = XenForo_BbCode_Formatter_Base::create();
			$parser = new XenForo_BbCode_Parser($formatter);
			$raffle['description'] = $parser->render($raffle['description']); 

			// CHECK FOR DIFFERENT USERGROUP LIMITS
			if($raffle['grouplimits'])
			{
				// BUILD DIFFERENT LIMIT USERGROUP ARRAY
				$firststage = explode(',',$raffle['grouplimits']);
				$check_group = '';
				foreach($firststage as $key=>$stage)
				{
					$secondstage = explode('|',$stage);
					if($check_group)
					{
						$check_group .= ',' . $secondstage[0];
					}else{
						$check_group = $secondstage[0];
					}
				}

				foreach($firststage as $key=>$stage)
				{
					$secondstage = explode('|',$stage);
					if($this->is_a_rafflegroup($secondstage[0],$raffle['usergroups']) && $this->is_in_group($visitor,$check_group))
					{
						$raffle['entries'] = $secondstage[1];
					}
				}
			}

			// DECODE TIME PERIOD FOR ENTRY LIMIT
			if($raffle['timeperiod'] && $raffle['intime'])
			{
				$time_length = $raffle['timeperiod'];
				$days_text = '';
				$hours_text = '';
				$minutes_text = '';
				$seconds_text = '';
				$time_message = '';
				$days = intval(floor($time_length / 86400)); 
				$time_length = $time_length % 86400; 
				$hours = intval(floor($time_length / 3600)); 
				$time_length = $time_length % 3600; 
				$minutes = intval(floor($time_length / 60)); 
				$seconds = $time_length % 60; 
				if($minutes == 60)
				{ 
					$hours = $hours+1; 
					$minutes = 0; 
				}
				if($days > 1) 
				{
					$day_text = new XenForo_Phrase('days');
				}else{
					$day_text = new XenForo_Phrase('day');
				}

				if($hours > 1) 
				{
					$hours_text = new XenForo_Phrase('hours');
				}else{
					$hours_text = new XenForo_Phrase('raffles_hour');
				}
 
				if($minutes > 1) 
				{
					$minutes_text = new XenForo_Phrase('raffles_minutes');
				}else{
					$minutes_text = new XenForo_Phrase('raffles_minute');
				}

				if($seconds > 1) 
				{
					$seconds_text = new XenForo_Phrase('raffles_seconds');
				}else{
					$seconds_text = new XenForo_Phrase('raffles_second');
				}

				if($days > 0) $time_message .= $days . ' ' . $day_text . " ";
				if($hours > 0) $time_message .= $hours . ' ' . $hours_text . " ";
				if($minutes > 0) $time_message .= $minutes . ' ' . $minutes_text . " ";
				if($seconds > 0 && $days == 0 && $hours == 0 && $minutes == 0) $time_message .=  $seconds . ' ' . $seconds_text;
				$raffle['time_decoded'] = $time_message;
			}
			if(XenForo_Application::$externalDataUrl <> 'data') $raffle['image'] = str_replace('data',XenForo_Application::$externalDataUrl,$raffle['image']);
			$raffle_count++;
		}
		if(!$raffle_count) $raffles['none'] = true;
		$viewParams = array(
			'raffles' => $raffles,
			'currency' => XenForo_Application::getOptions()->raffles_currency
		);

		return $this->responseView('Snog_Raffles_ViewPublic_Index', 'raffles_index', $viewParams);
	}
	
	protected function _getRafflesRaffleModel()
	{
		return $this->getModelFromCache('Snog_Raffles_Model_Raffle');
	}

	public static function getSessionActivityDetailsForList(array $activities)
	{
		return new XenForo_Phrase('raffles_viewing_index');
	}

	protected function _getUserModel()
	{
		return $this->getModelFromCache('XenForo_Model_User');
	}

	public static function is_a_rafflegroup($checkgroups,$rafflegroups)
	{
		if(!$rafflegroups) return false;
		$member_groups = explode(',',$checkgroups);
		$raffle_groups = explode(',',$rafflegroups);

		foreach ($member_groups AS $groupId)
		{
			// IS GROUP IN USERGROUPS
			if (in_array($groupId, $raffle_groups))
			{
				return true;
			}
		}

		// USERGROUP IS OK
		return false;
	}

	public static function is_in_group($visitor,$rafflegroups)
	{
		if(!$rafflegroups) return false;
		$member_secondary_groups = explode(',',$visitor['secondary_group_ids']);
		$raffle_groups = explode(',',$rafflegroups);

		// ADD PRIMARY GROUP TO CHECK
		$member_secondary_groups[] = $visitor['user_group_id'];

		foreach ($member_secondary_groups AS $groupId)
		{
			// IS GROUP IN USERGROUPS
			if (in_array($groupId, $raffle_groups))
			{
				return true;
			}
		}

		// USERGROUP IS OK
		return false;
	}
}