<?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_Model_DrawRaffles extends XenForo_Model
{
	public function drawRaffles()
	{
		error_reporting(E_ALL);
		$conditions['raffle_name'] = '';
		$conditions['user_id'] = '';
		$entries_model = $this->_getRafflesEntriesModel();
		$raffles_model = $this->_getRaffleModel();
		$user_model = $this->_getUserModel();
		$admin_timezone = $user_model->getUserById(XenForo_Application::getOptions()->raffles_raffle_admin);
		date_default_timezone_set($admin_timezone['timezone']);
		$raffles = $raffles_model->drawActiveRaffles(time());
		foreach($raffles as $raffle)
		{
			$ok_run = true;
			$conditions['raffle_name'] = '';
			$conditions['user_id'] = '';
			$entry_count = $entries_model->countDistinctUserEntries($raffle['raffle_id']);

			if($entry_count > 0 && $entry_count < $raffle['numprizes'] && !$raffle['multiple'])
			{
				$ok_run = false;
				$winner_info = new XenForo_Phrase('raffles_not_enough');
				$raffles_model->raffleWinnerUpdate($raffle['raffle_id'],$winner_info);
			}else if($entry_count == 0){
				$ok_run = false;
				$winner_info = new XenForo_Phrase('raffles_not_enough');
				$raffles_model->raffleWinnerUpdate($raffle['raffle_id'],$winner_info);
			}

			if($ok_run)
			{
				if($raffle['inthread'] && $raffle['posterid'])
				{
					$poster_info = $user_model->getUserById($raffle['posterid']);
				}

				if($raffle['custpm'] && $raffle['pmid'])
				{
					$pmauthor_info = $user_model->getUserById($raffle['pmid']);
				}

				$winner_count = 0;
				$winner_ids = '';
				$winner_list = '';
		
				while($winner_count < $raffle['numprizes'])
				{
					$winner_draw = $raffles_model->getRaffleWinner($raffle['raffle_id']);

					if(!$raffle['multiple'] && $winner_list)
					{
						while(in_array($winner_draw['user_id'], explode(",",$winner_ids)))
						{
							$winner_draw = $raffles_model->getRaffleWinner($raffle['raffle_id']);
						}
					}

					if(!$winner_draw['user_id'])
					{
						throw new XenForo_Exception(new XenForo_Phrase('raffles_no_winner'), true);
					}else{
						$winner_count = $winner_count + 1;
						$winner = $user_model->getUserById($winner_draw['user_id']);
						if(!$winner)
						{

						}
					}

					if($raffle['numprizes'] == 1 && $winner['user_id'])
					{	
						if(!XenForo_Application::getOptions()->raffles_display_tickets)
						{
							$winner_info = $winner['username'];
						}else{
							$winner_info = $winner['username'] . " (" . new XenForo_Phrase('raffles_ticketnumber') . ": " . $winner_draw['entry_id'] . ")";
						}

						$raffles_model->raffleWinnerUpdate($raffle['raffle_id'],$winner_info);

						if($raffle['inthread'] && $raffle['tsubject'])
						{
							$thread_subject = str_replace('{1}',$raffle['name'],$raffle['tsubject']);
							$thread_subject = str_replace('{2}',$winner['username'],$thread_subject);
						}

						if($raffle['inthread'] && $raffle['tcontent'])
						{
							$thread_message = str_ireplace('{1}', $raffle['name'], $raffle['tcontent']);
							$thread_message = str_ireplace('{2}',$winner['username'],$thread_message);
							$thread_message = str_ireplace('{3}',$admin_timezone['username'],$thread_message);
							$thread_message = str_ireplace('{4}',$poster_info['username'],$thread_message);
						}

						if($raffle['custpm'] && $raffle['psubject'])
						{
							$pm_subject = str_replace('{1}',$raffle['name'],$raffle['psubject']);
							$pm_subject = str_replace('{2}',$winner['username'],$pm_subject);
						}

						if($raffle['custpm'] && $raffle['pcontent'])
						{
							$pm_message = str_ireplace('{1}', $raffle['name'], $raffle['pcontent']);
							$pm_message = str_ireplace('{2}',$winner['username'],$pm_message);
							$pm_message = str_ireplace('{3}',$admin_timezone['username'],$pm_message);
							$pm_message = str_ireplace('{4}',$pmauthor_info['username'],$pm_message);
						}

						if($raffle['custpm'] && $winner['user_id'] <> $pmauthor_info['user_id'])
						{
							$pmid = Snog_Raffles_Helper_DataWriter::createConversation($pmauthor_info, array($winner['user_id']), $pm_subject, $pm_message);
						}

						if($raffle['inthread'])
						{
							$pstid = Snog_Raffles_Helper_DataWriter::createThread($poster_info, $raffle['node_id'], $thread_subject, $thread_message);
						}

						$winner_list = $winner_info;
					}else{
						if($winner['user_id'])
						{
							if(!XenForo_Application::getOptions()->raffles_display_tickets)
							{
								$winner_info = $winner['username'];
							}else{
								$winner_info = $winner['username'] . " (" . new XenForo_Phrase('raffles_ticketnumber') . ": " . $winner_draw['entry_id'] . ")";
							}

							if($winner_list)
							{
								$winner_list .= ", " . $winner_info;
								$winner_ids .= "," . $winner['user_id'];
							}else{
								$winner_list = $winner_info;
								$winner_ids .= $winner['user_id'];
							}

							if($winner_count == $raffle['numprizes'])
							{
								$raffles_model->raffleWinnerUpdate($raffle['raffle_id'],$winner_list);

								if($raffle['inthread'] && $raffle['tsubject'])
								{
									$thread_subject = str_replace('{1}',$raffle['name'],$raffle['tsubject']);
									$thread_subject = str_replace('{2}',$winner_list,$thread_subject);
								}

								if($raffle['inthread'] && $raffle['tcontent'])
								{
									$thread_message = str_ireplace('{1}', $raffle['name'], $raffle['tcontent']);
									$thread_message = str_ireplace('{2}',$winner_list,$thread_message);
									$thread_message = str_ireplace('{3}',$admin_timezone['username'],$thread_message);
									$thread_message = str_ireplace('{4}',$poster_info['username'],$thread_message);
								}

								if($raffle['inthread'])
								{
									$pstid = Snog_Raffles_Helper_DataWriter::createThread($poster_info, $raffle['node_id'], $thread_subject, $thread_message);
								}
							}

							if($raffle['custpm'] && $raffle['psubject'])
							{
								$pm_subject = str_replace('{1}',$raffle['name'],$raffle['psubject']);
								$pm_subject = str_replace('{2}',$winner['username'],$pm_subject);
							}

							if($raffle['custpm'] && $raffle['pcontent'])
							{
								$pm_message = str_ireplace('{1}', $raffle['name'], $raffle['pcontent']);
								$pm_message = str_ireplace('{2}',$winner['username'],$pm_message);
								$pm_message = str_ireplace('{3}',$admin_timezone['username'],$pm_message);
								$pm_message = str_ireplace('{4}',$pmauthor_info['username'],$pm_message);
							}

							if($raffle['custpm'])
							{
								$pmid = Snog_Raffles_Helper_DataWriter::createConversation($pmauthor_info, array($winner['user_id']), $pm_subject, $pm_message);
							}
						}
					}
				}
			}
		}
	}

	protected function _getRaffleModel()
	{
		return $this->getModelFromCache('Snog_Raffles_Model_Raffle');
	}

	protected function _getRafflesEntriesModel()
	{
		return $this->getModelFromCache('Snog_Raffles_Model_Entries');
	}

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