<?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.					  # ||
|| # ---------------------------------------------------------------- # ||
|| #################################################################### ||
\*======================================================================*/

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

if (!$vbulletin->userinfo['userid'] OR 
	!$vbulletin->options['dbtech_vbshop_lottery_enabled']/* OR
	!VBSHOP::$permissions['canbank']*/
)
{
	// No permission to use bank
	print_no_permission();
}

// Add to the navbits
$navbits['vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=lottery'] = $pagetitle = $vbphrase['dbtech_vbshop_lotteries'];

// #############################################################################
if ($_REQUEST['action'] == 'lottery' OR empty($_REQUEST['action']))
{
	
	$lotterybits = '';
	foreach ((array)VBSHOP::$cache['lottery'] as $lotteryid => $lottery)
	{
		if (!$lottery['active'])
		{
			// Skip inactive lotteries
			continue;
		}
		
		if (!$currency = VBSHOP::$cache['currency'][$lottery['currencyid']])
		{
			// Skip invalid currencies
			continue;
		}
		
		$prizes = array();
		foreach ($lottery['prizes'] as $key => $prizeinfo)
		{
			if (!VBSHOP::$cache['lotteryprize'][$prizeinfo['prizeid']] OR 
				!$prizeinfo['prize'] OR
				!VBSHOP::$cache['currency'][$prizeinfo['currencyid']]
			)
			{
				// Gtfo
				continue;
			}
			
			// Add it to the final prize array
			$prizes["$key"] = $key . '. <b>' . VBSHOP::$cache['lotteryprize']["$prizeinfo[prizeid]"]['title'] . '</b> - <i>' . $prizeinfo['prize'] . ' ' . VBSHOP::$cache['currency']["$prizeinfo[currencyid]"]['title'] . '</i>';
		}
		
		// Convert some variables
		$lottery['description'] = nl2br($lottery['description']);
		$lottery['prevdraw'] 	= ($lottery['prevdraw'] ? vbdate($vbulletin->options['dateformat'], $lottery['prevdraw']) . ' ' . vbdate($vbulletin->options['timeformat'], $lottery['prevdraw']) : 'N/A');
		$lottery['nextdraw'] 	= vbdate($vbulletin->options['dateformat'], $lottery['nextdraw']) . ' ' . vbdate($vbulletin->options['timeformat'], $lottery['nextdraw']);
		$lottery['prizes'] 		= implode('<br />', $prizes);
		
		// Whether we can buy a ticket
		$show['buyticket']		= ($vbulletin->userinfo[$currency['pointscolumn']] >= $lottery['ticketprice']);
		
		// Do shop bits
		$templater = vB_Template::create('dbtech_vbshop_lottery_lotterybit');
			$templater->register('lottery', $lottery);
		$lotterybits .= $templater->render();				
	}
	
	$page_templater = vB_Template::create('dbtech_vbshop_lottery');
		$page_templater->register('pagetitle', 		$pagetitle);
		$page_templater->register('lotterybits', 	$lotterybits);
	$HTML = $page_templater->render();	
}

// #############################################################################
if ($_REQUEST['action'] == 'buyticket')
{
	$lotteryid = $vbulletin->input->clean_gpc('r', 'lotteryid', TYPE_UINT);
	if (!$lottery = VBSHOP::$cache['lottery'][$lotteryid])
	{
		// Invalid lottery id
		eval(standard_error(fetch_error('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_lottery'], $lotteryid)));
	}
	
	if (!$currency = VBSHOP::$cache['currency'][$lottery['currencyid']])
	{
		// Skip invalid currencies
		eval(standard_error(fetch_error('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_currency'], $lottery['currencyid'])));
	}
	
	if ($lottery['nextdraw'] < TIMENOW)
	{
		// Nothing to buy for
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_no_upcoming_raffles'])));
	}
	
	if ($vbulletin->userinfo[$currency['pointscolumn']] < $lottery['ticketprice'])
	{
		// Cannot afford ticket
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_cannot_afford_ticket'])));
	}
	
	$numbers = '';
	for ($i = 1; $i <= $lottery['numbers']['total']; $i++)
	{
		// Create the number option template
		$templater = vB_Template::create('option');
			$templater->register('optionvalue', 	$i);
			$templater->register('optiontitle', 	$i);
		$numbers .= $templater->render();
	}	
	
	$numberselects = '';
	for ($i = 1; $i <= $lottery['numbers']['main']; $i++)
	{
		// Create the number select template
		$templater = vB_Template::create('dbtech_vbshop_lottery_buyticket_numberselects');
			$templater->register('i', 		$i);
			$templater->register('numbers', $numbers);
		$numberselects .= $templater->render();
	}
	
	$prizes = array();
	foreach ($lottery['prizes'] as $key => $prizeinfo)
	{
		if (!VBSHOP::$cache['lotteryprize'][$prizeinfo['prizeid']] OR 
			!$prizeinfo['prize'] OR
			!VBSHOP::$cache['currency'][$prizeinfo['currencyid']]
		)
		{
			// Gtfo
			continue;
		}
		
		// Add it to the final prize array
		$prizes["$key"] = $key . '. <b>' . VBSHOP::$cache['lotteryprize']["$prizeinfo[prizeid]"]['title'] . '</b> - <i>' . $prizeinfo['prize'] . ' ' . VBSHOP::$cache['currency']["$prizeinfo[currencyid]"]['title'] . '</i>';
	}
	
	// Convert some variables
	$lottery['description'] = nl2br($lottery['description']);
	$lottery['prizes'] 		= implode('<br />', $prizes);	

	// Add to the navbits
	$navbits[''] = $pagetitle = construct_phrase($vbphrase['dbtech_vbshop_buying_ticket_lottery_x'], $lottery['title']);
	
	$page_templater = vB_Template::create('dbtech_vbshop_lottery_buyticket');
		$page_templater->register('pagetitle', 		$pagetitle);
		$page_templater->register('lottery', 		$lottery);
		$page_templater->register('currency', 		$currency);
		$page_templater->register('numberselects', 	$numberselects);
	$HTML = $page_templater->render();	
}

// #############################################################################
if ($_POST['action'] == 'dobuyticket')
{
	$lotteryid = $vbulletin->input->clean_gpc('p', 'lotteryid', TYPE_UINT);
	if (!$lottery = VBSHOP::$cache['lottery'][$lotteryid])
	{
		// Invalid lottery id
		eval(standard_error(fetch_error('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_lottery'], $lotteryid)));
	}
	
	if (!$currency = VBSHOP::$cache['currency'][$lottery['currencyid']])
	{
		// Skip invalid currencies
		eval(standard_error(fetch_error('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_currency'], $lottery['currencyid'])));
	}
	
	if ($lottery['nextdraw'] < TIMENOW)
	{
		// Nothing to buy for
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_no_upcoming_raffles'])));
	}
	
	if ($vbulletin->userinfo[$currency['pointscolumn']] < $lottery['ticketprice'])
	{
		// Cannot afford ticket
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_cannot_afford_ticket'])));
	}
	
	// Grab the number from the URL
	$numbers = $vbulletin->input->clean_gpc('p', 'numbers', TYPE_ARRAY_UINT);
	
	$usednumbers = array();
	for ($i = 1; $i <= $lottery['numbers']['main']; $i++)
	{
		if ($usednumbers[$numbers[$i]])
		{
			// Used same number several times
			eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_cannot_reuse_numbers'])));
		}
		
		if ($numbers[$i] > $lottery['numbers']['total'])
		{
			// Too large number
			eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_too_large_number'])));
		}
		
		// Used number
		$usednumbers[$numbers[$i]] = true;
	}

	$remaining = $db->query_first_slave("
		SELECT " . $currency['pointscolumn'] . " AS points 
		FROM " . TABLE_PREFIX . $currency['pointstable'] . "
		WHERE userid = " . intval($vbulletin->userinfo['userid'])
	);
	
	if ($remaining['points'] < $lottery['ticketprice'])
	{
		// Cannot afford ticket
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_cannot_afford_ticket'])));
	}

	// We're done with the error checking
	$db->query_write("
		UPDATE " . TABLE_PREFIX . $currency['pointstable'] . "
		SET " . $currency['pointscolumn'] . " = " . $currency['pointscolumn'] . " - " . doubleval($lottery['ticketprice']) . "
		WHERE userid = " . intval($vbulletin->userinfo['userid'])
	);

	$info = array(
		'lotteryid' 	=> $lottery['lotteryid'],
		'numbers' 		=> trim(serialize($numbers)),
		'currencyid' 	=> $lottery['currencyid'],
		'price' 		=> $lottery['ticketprice']
	);
	
	// init data manager
	$dm =& VBSHOP::initDataManager('Transactionlog', $vbulletin, ERRTYPE_ARRAY);
		$dm->set('userid', 		$vbulletin->userinfo['userid']);
		$dm->set('recipient', 	$vbulletin->userinfo['userid']);
		$dm->set('ipaddress', 	IPADDRESS);
		$dm->set('action', 		'lotteryticket');
		$dm->set('info', 		$info);
	$dm->save();
	unset($dm);	

	// Insert ticket
	$db->query_write("
		INSERT INTO " . TABLE_PREFIX . "dbtech_vbshop_lotteryticket
			(lotteryid, userid, lotterydraw, numbers)
		VALUES (
			" . $db->sql_prepare($lottery['lotteryid']) . ",
			" . $db->sql_prepare($vbulletin->userinfo['userid']) . ",
			" . $db->sql_prepare($lottery['nextdraw']) . ",
			" . $db->sql_prepare(trim(serialize($numbers))) . "
		)
	");

	// Success phrase
	$vbulletin->url = 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=lottery&action=view&lotteryid=' . $lottery['lotteryid'];
	eval(print_standard_redirect('redirect_dbtech_vbshop_updatethanks'));
}

// #############################################################################
if ($_REQUEST['action'] == 'view')
{
	$lotteryid = $vbulletin->input->clean_gpc('r', 'lotteryid', TYPE_UINT);
	if (!$lottery = VBSHOP::$cache['lottery'][$lotteryid])
	{
		// Invalid lottery id
		eval(standard_error(fetch_error('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_lottery'], $lotteryid)));
	}
	
	if (!$currency = VBSHOP::$cache['currency'][$lottery['currencyid']])
	{
		// Skip invalid currencies
		eval(standard_error(fetch_error('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_currency'], $lottery['currencyid'])));
	}

	$previousdraws = '';
	$upcomingdraw = array();
	
	$usertickets = $db->query_read_slave("
		SELECT *
		FROM " . TABLE_PREFIX . "dbtech_vbshop_lotteryticket
		WHERE lotteryid = " . intval($lottery['lotteryid']) . "
			AND userid = " . intval($vbulletin->userinfo['userid']) . "
	");
	while ($ticket = $db->fetch_array($usertickets))
	{
		// Get the numbers selected
		$numbers = @unserialize($ticket['numbers']);
		
		if ($ticket['lotterydraw'] > TIMENOW)
		{
			// Upcoming draw
			$upcomingdraw[] = implode('-', $numbers);
		}
	}
	
	if ($lottery['prevdraw'])
	{
		$ourtickets = array();
		$prevdraws = array();
		$usertickets = $db->query_read_slave("
			SELECT *
			FROM " . TABLE_PREFIX . "dbtech_vbshop_lotteryticket
			WHERE lotteryid = " . intval($lottery['lotteryid']) . "
				AND lotterydraw <= " . intval($lottery['prevdraw']) . "
		");
		while ($ticket = $db->fetch_array($usertickets))
		{
			$ourtickets[$ticket['lotterydraw']] = array();
			if ($ticket['userid'] == $vbulletin->userinfo['userid'])
			{
				// Get the numbers selected
				$numbers = @unserialize($ticket['numbers']);
				
				// Upcoming draw
				$ourtickets[$ticket['lotterydraw']][] = implode('-', $numbers) . ($ticket['prizeid'] ? ' - <b>' . VBSHOP::$cache['lotteryprize'][$lottery['prizes'][$ticket['prizeid']]['prizeid']]['title'] . '!</b>' : '');
			}

			if (!is_array($prevdraws[$ticket['lotterydraw']]))
			{
				// Ensure we display previous draws with no winners
				$prevdraws[$ticket['lotterydraw']] = array();
			}
			
			if ($ticket['prizeid'])
			{
				// Store all previous draws and their winners
				$prevdraws[$ticket['lotterydraw']][$ticket['prizeid']]++;
			}
		}
		
		krsort($prevdraws);
		foreach ($prevdraws as $drawdate => $prizelist)
		{
			$prizes = array();
			foreach ($lottery['prizes'] as $key => $prizeinfo)
			{
				if (!VBSHOP::$cache['lotteryprize'][$prizeinfo['prizeid']] OR 
					!$prizeinfo['prize'] OR
					!VBSHOP::$cache['currency'][$prizeinfo['currencyid']]
				)
				{
					// Gtfo
					continue;
				}
				
				// Add it to the final prize array
				$prizes["$key"] = $key . '. <b>' . VBSHOP::$cache['lotteryprize']["$prizeinfo[prizeid]"]['title'] . '</b> - <i>' . $prizeinfo['prize'] . ' 
					' . VBSHOP::$cache['currency']["$prizeinfo[currencyid]"]['title'] . '</i> - ' . intval($prizelist[$key]) . ' ' . $vbphrase['dbtech_vbshop_winners'];
			}
			
			// Create the number option template
			$templater = vB_Template::create('dbtech_vbshop_lottery_info_prevdraw');
				$templater->register('drawdate', 	vbdate($vbulletin->options['dateformat'], $drawdate) . ' ' . vbdate($vbulletin->options['timeformat'], $drawdate));
				$templater->register('prizes', 		implode('<br />', $prizes));
				$templater->register('ourtickets', 	implode('<br />', $ourtickets[$drawdate]));
			$previousdraws .= $templater->render();
		}
	}
	
	$prizes = array();
	foreach ($lottery['prizes'] as $key => $prizeinfo)
	{
		if (!VBSHOP::$cache['lotteryprize'][$prizeinfo['prizeid']] OR 
			!$prizeinfo['prize'] OR
			!VBSHOP::$cache['currency'][$prizeinfo['currencyid']]
		)
		{
			// Gtfo
			continue;
		}
		
		// Add it to the final prize array
		$prizes["$key"] = $key . '. <b>' . VBSHOP::$cache['lotteryprize']["$prizeinfo[prizeid]"]['title'] . '</b> - <i>' . $prizeinfo['prize'] . ' ' . VBSHOP::$cache['currency']["$prizeinfo[currencyid]"]['title'] . '</i>';
	}
	
	// Convert some variables
	$lottery['description'] = nl2br($lottery['description']);
	$lottery['prevdraw'] 	= ($lottery['prevdraw'] ? vbdate($vbulletin->options['dateformat'], $lottery['prevdraw']) . ' ' . vbdate($vbulletin->options['timeformat'], $lottery['prevdraw']) : 'N/A');
	$lottery['nextdraw'] 	= vbdate($vbulletin->options['dateformat'], $lottery['nextdraw']) . ' ' . vbdate($vbulletin->options['timeformat'], $lottery['nextdraw']);
	$lottery['prizes'] 		= implode('<br />', $prizes);
	
	// Add to the navbits
	$navbits[''] = $pagetitle = construct_phrase($vbphrase['dbtech_vbshop_viewing_info_lottery_x'], $lottery['title']);
	
	$page_templater = vB_Template::create('dbtech_vbshop_lottery_info');
		$page_templater->register('pagetitle', 		$pagetitle);
		$page_templater->register('lottery', 		$lottery);
		$page_templater->register('currency', 		$currency);
		$page_templater->register('previousdraws', 	$previousdraws);
		$page_templater->register('upcomingdraw', 	implode('<br />', $upcomingdraw));
	$HTML = $page_templater->render();	
}

// draw cp nav bar
VBSHOP::setNavClass('lottery');