<?php
/*======================================================================*\
|| #################################################################### ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2013 Fillip Hannisdal AKA Revan/NeoRevan/Belazor 	  # ||
|| # All Rights Reserved. 											  # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ---------------------------------------------------------------- # ||
|| # You are not allowed to use this on your server unless the files  # ||
|| # you downloaded were done so with permission.					  # ||
|| # ---------------------------------------------------------------- # ||
|| #################################################################### ||
\*======================================================================*/

if (!is_object($vbulletin->db))
{
	exit;
}

// ########################################################################
// ######################### START MAIN SCRIPT ############################
// ########################################################################

if (defined('IN_CONTROL_PANEL'))
{
	define('ECHO_CRON_LOG', true);
}

foreach ((array)VBSHOP::$cache['lottery'] as $lotteryid => $lottery)
{
	if ($lottery['nextdraw'] > TIMENOW)
	{
		// Not drawing yet
		continue;
	}
	
	if ($lottery['nextdraw'] == $lottery['prevdraw'])
	{
		// This is a non-recurring lottery
		continue;
	}
	
	$drawnnumbers = array(
		'main' 	=> array(),
		'bonus' => array(),
	);
	foreach (array('main', 'bonus') as $key)
	{
		$usednumbers = array();
		for ($i = 1; $i <= $lottery['numbers'][$key]; $i++)
		{
			$retry = true;
			while ($retry)
			{
				$num = mt_rand(1, $lottery['numbers']['total']);
				$retry = (bool)$usednumbers[$num];
			}
			
			// Used number
			$usednumbers[$num] = true;
			$drawnnumbers[$key][$i] = $num;
		}
		
		sort($drawnnumbers[$key], SORT_NUMERIC);
	}
	
	$usertickets = $vbulletin->db->query_read_slave("
		SELECT *
		FROM " . TABLE_PREFIX . "dbtech_vbshop_lotteryticket
		WHERE lotteryid = " . intval($lottery['lotteryid']) . "
			AND lotterydraw = " . intval($lottery['nextdraw']) . "
			AND prizeid = 0
	");
	while ($ticket = $vbulletin->db->fetch_array($usertickets))
	{
		$matchednumbers = array(
			'main' 	=> 0,
			'bonus' => 0,
		);
		
		// Get the numbers selected
		$numbers = @unserialize($ticket['numbers']);
		
		foreach ($numbers as $num)
		{
			foreach (array('main', 'bonus') as $key)
			{
				if (in_array($num, $drawnnumbers[$key]))
				{
					// We matched a number, woo
					$matchednumbers[$key]++;
				}
			}
		}
		
		foreach ($lottery['prizes'] as $key => $prizeinfo)
		{
			if (!VBSHOP::$cache['lotteryprize'][$prizeinfo['prizeid']] OR 
				!$prizeinfo['prize'] OR
				!VBSHOP::$cache['currency'][$prizeinfo['currencyid']]
			)
			{
				// Gtfo
				continue;
			}
			
			$prize = VBSHOP::$cache['lotteryprize'][$prizeinfo['prizeid']];
			
			if ($matchednumbers['main'] >= $prize['numbers']['main'] AND
				$matchednumbers['bonus'] >= $prize['numbers']['bonus'])
			{
				// Winrar
				$vbulletin->db->query_write("
					UPDATE " . TABLE_PREFIX . "dbtech_vbshop_lotteryticket
					SET prizeid = " . intval($key) . "
					WHERE lotteryticketid = " . intval($ticket['lotteryticketid'])
				);
				
				// Can't have more prizes
				break;
			}
		}
	}
	
	$prizes = array();
	$winners = array();
	$usertickets = $vbulletin->db->query_read_slave("
		SELECT *
		FROM " . TABLE_PREFIX . "dbtech_vbshop_lotteryticket
		WHERE lotteryid = " . intval($lottery['lotteryid']) . "
			AND lotterydraw = " . intval($lottery['nextdraw']) . "
			AND prizeid > 0
	");
	while ($ticket = $vbulletin->db->fetch_array($usertickets))
	{
		$prizes[$ticket['prizeid']]++;
		$winners[$ticket['prizeid']][] = $ticket['userid'];
	}
	
	if (count($winners))
	{
		foreach ($prizes as $prizeid => $count)
		{
			$payout = ceil($lottery['prizes'][$prizeid]['prize'] / $count);
			$currency = VBSHOP::$cache['currency'][$lottery['prizes'][$prizeid]['currencyid']];
			
			foreach ($winners[$prizeid] as $userid)
			{
				// We're done with the error checking
				$vbulletin->db->query_write("
					UPDATE " . TABLE_PREFIX . $currency['pointstable'] . "
					SET " . $currency['pointscolumn'] . " = " . $currency['pointscolumn'] . " + " . doubleval($payout) . "
					WHERE userid = " . intval($userid)
				);
			
				$info = array(
					'lotteryid' 	=> $lottery['lotteryid'],
					'currencyid' 	=> $currency['currencyid'],
					'winnings' 		=> $payout,
					'prizeid' 		=> $lottery['prizes'][$prizeid]['prizeid']
				);
				
				// init data manager
				$dm =& VBSHOP::initDataManager('Transactionlog', $vbulletin, ERRTYPE_ARRAY);
					$dm->set('userid', 		$userid);
					$dm->set('recipient', 	$userid);
					$dm->set('ipaddress', 	IPADDRESS);
					$dm->set('action', 		'lotteryprize');
					$dm->set('info', 		$info);
				$dm->save();
				unset($dm);	
			}
		}
		
	}
	
	if (!$existing = VBSHOP::$cache['lottery']["$lotteryid"])
	{
		// Doesn't exist anymore
		continue;
	}
	
	$newdrawnnumbers = $existing['drawnnumbers'];
	$newdrawnnumbers[$existing['nextdraw']] = $drawnnumbers;
	
	// init data manager
	$dm =& VBSHOP::initDataManager('Lottery', $vbulletin, ERRTYPE_SILENT);
		$dm->set_existing($existing);
		$dm->set('drawnnumbers', $newdrawnnumbers);
		$dm->set('prevdraw', $existing['nextdraw']);
		$dm->set('nextdraw', ($existing['nextdraw'] + (86400 * $existing['drawinterval'])));
	$dm->save();
	unset($dm);
}

log_cron_action('Lottery Processed', $nextitem);