<?php
/*****************************************************************************
 *   Lottery (/inc/plugins/myplaza/lottery.php)
 *     - MyPlaza for MyBB 1.2
 *    By ZiNgA BuRgA, 2007-2008
 * 
 * Adds a lottery system!
 *****************************************************************************/

if(!defined("IN_MYBB"))
	die("This file cannot be accessed directly.");

function lottery_lang()
{
	global $mybb, $lang;
	switch($mybb->settings['bblanguage'])
	{
		default:
			$lang->invalid_numbers = 'Invalid numbers supplied.';
	}
}

function lottery_lang_admin()
{
	global $mybb, $lang;
	switch($mybb->settings['bblanguage'])
	{
		default:
			$lang->lottery_name = 'Lottery';
			$lang->lottery_description = 'Adds a lottery system!';
			
			$lang->item_lottery_ticket_name = 'Lottery Ticket';
			$lang->item_lottery_ticket_desc = 'Gives a chance to win in the lottery.';
			
			$lang->setting_lottery_max_num = 'Maximum selectable number';
			$lang->setting_lottery_max_num_desc = 'This is the upper range for each number in the lottery.';
			
			$lang->setting_lottery_numbers = 'Number of numbers';
			$lang->setting_lottery_numbers_desc = 'This is the number of lottery numbers to select.';
			
			$lang->setting_lottery_secondaries = 'Number of secondary numbers';
			$lang->setting_lottery_secondaries_desc = 'This is the number of secondary lottery numbers to select.  Secondary numbers can have special purposes - ie act as supplimentaries.  Note that primary numbers are always checked first - ie 6 primary matches is considered &quot;higher&quot; than 5 primary plus 1 secondary.';
			
			$lang->setting_lottery_draw_frequency = 'Hours between each drawing';
			$lang->setting_lottery_draw_frequency_desc = 'How often (in hours) the lottery is run.';
			
			$lang->setting_lottery_winrate = 'Win Payouts Rate';
			$lang->setting_lottery_winrate_desc = 'All winning payouts are multiplied by this number.';
			
			$lang->setting_lottery_usepot = 'Use Lottery Pot';
			$lang->setting_lottery_usepot_desc = 'If yes, the cost of each ticket goes towards the pot of the lottery.';
			
			$lang->setting_lottery_allow_systems = 'Allow System Games';
			$lang->setting_lottery_allow_systems_desc = 'If yes, allows users to select more numbers than the maximum selectable numbers, at, perhaps, higher prices.';
			
			$lang->lottery_options = 'Lottery Options';
			$lang->lottery_tickets = 'Lottery Tickets';
			$lang->tickets_deleted = 'Tickets deleted.';
			$lang->tickets_username = 'Holder';
			$lang->tickets_numbers = 'Selected Numbers';
			$lang->tickets_date = 'Purchase Date';
			$lang->tickets_del = 'Del';
			
			$lang->numbers_pruned = 'Old lottery numbers pruned.';
			$lang->winnings_updated = 'Winning combinations updated.';
			
			$lang->lottery_winnings = 'Lottery Winnings';
			$lang->winning_num_primary = 'No. Pmy Matches';
			$lang->winning_num_secondary = 'No. 2\'ary Matches';
			$lang->winning_payout = 'Payout';
			$lang->winning_potrate = 'Pot Contribution';
			
			$lang->match_numbers_must_be_positive = 'You must enter positive values for the number of matching numbers';
			$lang->add_winning = 'Add Winning Combination';
			
			$lang->are_you_sure_delete = 'Are you sure you wish to delete this?';
			$lang->update = 'Update';
			$lang->add = 'Add';
			$lang->delete = 'Delete';
			
			
			$lang->lottery_options_main = 'What would you like to do?
			<ul>
			 <li><a href="%1$slaction=tickets">View Purchased Tickets</a></li>
			 <li><a href="%1$slaction=winnings">Modify Winning Combinations</a></li>
			 <li><a href="%1$slaction=systems">Modify System Game Combinations</a></li>
			 <li><a href="%1$slaction=settings">Modify Lottery Settings</a></li>
			 <li><a href="%2$s">Edit Lottery Ticket item</a></li>
			</ul>';
	}
}

function lottery_info()
{
	global $lang;
	return array(
		"website"		=> "http://myplaza.zingaburga.com",
		"author"		=> "ZiNgA BuRgA",
		"authorsite"	=> "http://zingaburga.com/",
		"version"		=> "1.0",
		"compatibility"	=> array(0.5)
	);
}

function lottery_activate()
{
	// stop people trying to activate this module as a MyBB plugin
	if(!defined("IN_MYPLAZA_ADMIN"))
		cperror('This is not a normal MyBB plugin!  Please upload this file to your /inc/plugins/myplaza directory.');
	
	// write tables
	db_create_table('plaza_lottery_tickets', array(
		'tid' => array('type' => 'int', 'unsigned' => true, 'not_null' => true, 'auto_increment' => true),
		'uid' => array('type' => 'int', 'size' => 5, 'unsigned' => true, 'not_null' => true, 'default' => 0),
		'numbers' => array('type' => 'varchar', 'size' => 150, 'not_null' => true, 'default' => ''),
		'dateline' => array('type' => 'bigint', 'size' => 30, 'not_null' => true, 'unsigned' => true, 'default' => 0)
	), array(
		array('type' => 'primary', 'fields' => 'tid'),
		array('type' => 'key', 'fields' => 'uid'),
		//array('type' => 'key', 'fields' => 'dateline')
	));
	
	db_create_table('plaza_lottery_numbers', array(
		'nid' => array('type' => 'int', 'unsigned' => true, 'not_null' => true, 'auto_increment' => true),
		'numbers' => array('type' => 'varchar', 'size' => 150, 'not_null' => true, 'default' => ''),
		'secondaries' => array('type' => 'varchar', 'size' => 150, 'not_null' => true, 'default' => ''),
		'dateline' => array('type' => 'bigint', 'size' => 30, 'not_null' => true, 'unsigned' => true, 'default' => 0)
	), array(
		array('type' => 'primary', 'fields' => 'nid'),
		array('type' => 'key', 'fields' => 'dateline')
	));
	
	db_create_table('plaza_lottery_winnings', array(
		'wid' => array('type' => 'smallint', 'unsigned' => true, 'not_null' => true, 'auto_increment' => true),
		'winamount' => array('type' => 'decimal', 'size' => '32,16', 'not_null' => true, 'default' => '0'),
		'potrate' => array('type' => 'float', 'size' => 8, 'not_null' => true, 'unsigned' => true, 'default' => '0'),
		'num_primary' => array('type' => 'smallint', 'size' => 5, 'not_null' => true, 'unsigned' => true, 'default' => 0),
		'num_secondary' => array('type' => 'smallint', 'size' => 5, 'not_null' => true, 'unsigned' => true, 'default' => 0)
	), array(
		array('type' => 'primary', 'fields' => 'wid')
	));
	
	// insert some default win combinations
	db_insert_rows('plaza_lottery_winnings', array(
		array(
			'winamount' => 1000000,
			'potrate' => 0.85,
			'num_primary' => 6,
			'num_secondary' => 0
		),
		array(
			'winamount' => 500000,
			'potrate' => 0.1,
			'num_primary' => 5,
			'num_secondary' => 1
		),
		array(
			'winamount' => 200000,
			'potrate' => 0.05,
			'num_primary' => 5,
			'num_secondary' => 0
		),
		array(
			'winamount' => 50000,
			'potrate' => 0,
			'num_primary' => 4,
			'num_secondary' => 2
		),
		array(
			'winamount' => 25000,
			'potrate' => 0,
			'num_primary' => 4,
			'num_secondary' => 1
		),
		array(
			'winamount' => 15000,
			'potrate' => 0,
			'num_primary' => 4,
			'num_secondary' => 0
		),
		array(
			'winamount' => 12000,
			'potrate' => 0,
			'num_primary' => 3,
			'num_secondary' => 2
		),
		array(
			'winamount' => 5000,
			'potrate' => 0,
			'num_primary' => 3,
			'num_secondary' => 1
		),
		array(
			'winamount' => 1000,
			'potrate' => 0,
			'num_primary' => 3,
			'num_secondary' => 0
		),
	));
	cache_update_winnings();
	
	db_create_table('plaza_lottery_systems', array(
		'num_selectable' => array('type' => 'smallint', 'not_null' => true, 'unsigned' => true, 'default' => '0'),
		'premiumrate' => array('type' => 'float', 'size' => 8, 'not_null' => true, 'unsigned' => true, 'default' => '0')
	), array(
		array('type' => 'primary', 'fields' => 'num_selectable')
	));
	
	// by default, allow up to system 20
	$systems = array();
	for($i=6; $i < 21; $i++)
		$systems[] = array('num_selectable' => $i, 'premiumrate' => combin($i, 6));
	
	db_insert_rows('plaza_lottery_systems', $systems);
	
	
	// add our items
	myplaza_add_item(array(
		"idname"		=> 'lottery_ticket',
		"cost"			=> 1,
		"htmlextra"		=> 'This item cannot be purchased from the plaza.'
	));
	
	// add settings
	add_settings(array(
		array(
			"name"			=> 'lottery_max_num',
			"optionscode"	=> 'text',
			"value"			=> 45,
		),
		array(
			"name"			=> 'lottery_numbers',
			"optionscode"	=> 'text',
			"value"			=> 6,
		),
		array(
			"name"			=> 'lottery_secondaries',
			"optionscode"	=> 'text',
			"value"			=> 2,
		),
		array(
			"name"			=> 'lottery_draw_frequency',
			"optionscode"	=> 'text',
			"value"			=> 72,
		),
		array(
			"name"			=> 'lottery_winrate',
			"optionscode"	=> 'text',
			"value"			=> 1,
		),
		array(
			"name"			=> 'lottery_usepot',
			"optionscode"	=> 'yesno',
			"value"			=> MY_NO,
		),
		array(
			"name"			=> 'lottery_allow_systems',
			"optionscode"	=> 'yesno',
			"value"			=> MY_YES,
		)
	));
	
	
	// insert templates
	$new_templates['plaza_lottery'] = '
{$plaza_header}
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="0">
	<tr>
	
<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
	<tr><td class="thead" colspan="2"><strong>{$lang->lottery_new_game}</strong></td></tr>

	<tr>
		<td class="trow1" width="30%">
			<strong>{$lang->amount}:</strong>
		</td><td class="trow1" width="70%">
			<input type="text" class="textbox" name="amount" value="0" />
		</td>
	</tr>

	<tr>
		<td class="trow2" width="30%">
			<strong>{$lang->action}</strong>
		</td><td class="trow2" width="70%">
			<input type="radio" class="radio" name="bankaction" value="deposit" id="bank_deposit" checked="checked" /><label for="bank_deposit">{$lang->deposit}</label> {$depositfee}
			<br /><input type="radio" class="radio" name="bankaction" value="withdraw" id="bank_withdraw" /><label for="bank_withdraw">{$lang->withdraw}</label> {$withdrawfee}
		</td>
	</tr>




<form action="plaza.php" method="post" onsubmit="if(this.elements[4].value&lt;=0){alert(\'{$lang->invalid_amount}\');return false;}">
	<input type="hidden" name="action" value="page" />
	<input type="hidden" name="p" value="bank" />
	<input type="hidden" name="process" value="yes" />
	<input type="hidden" name="postcode" value="{$mybb->post_code}" />
	<table border="0" cellspacing="{$theme[\'borderwidth\']}" cellpadding="{$theme[\'tablespace\']}" class="tborder">
		<tr><td class="thead" colspan="2"><img src="{$mybb->settings[\'bburl\']}/images/myplaza/bank.png" class="plazaitem" alt="" /><strong>{$lang->bank}</strong></td></tr>

		<tr>
			<td class="trow1" width="30%">
				<strong>{$lang->amount}:</strong>
			</td><td class="trow1" width="70%">
				<input type="text" class="textbox" name="amount" value="0" />
			</td>
		</tr>

		<tr>
			<td class="trow2" width="30%">
				<strong>{$lang->action}</strong>
			</td><td class="trow2" width="70%">
				<input type="radio" class="radio" name="bankaction" value="deposit" id="bank_deposit" checked="checked" /><label for="bank_deposit">{$lang->deposit}</label> {$depositfee}
				<br /><input type="radio" class="radio" name="bankaction" value="withdraw" id="bank_withdraw" /><label for="bank_withdraw">{$lang->withdraw}</label> {$withdrawfee}
			</td>
		</tr>

		<tr>
			<td class="trow1" width="30%">
				<strong>{$lang->info}</strong>
			</td><td class="trow1" width="70%">
				{$lang->money_on_hand} {$mymoney}<br />
				{$lang->money_in_bank} {$bankmoney}<br />
				{$lang->bank_interest_rate} {$mybb->settings[\'bank_interest_rate\']}%
				<span id="bank_message" style="font-weight: bold;"></span>
			</td>
		</tr>

		<tr><td class="tfoot" colspan="2" align="center">
		<input type="submit" class="button" value="{$lang->go}" />
		</td></tr>

	</table>
</form>
{$plaza_footer}
';
	
	global $cache;
	$cache->update('myplaza_lottery_info', array('lastrun' => REQUEST_TIME);
}

function lottery_deactivate()
{
	global $db, $cache;
	myplaza_remove_module_items();
	$db->delete_query(MY_TABLE_PREFIX.'settings', "name IN ('lottery_max_num', 'lottery_numbers', 'lottery_secondaries', 'lottery_draw_frequency', 'lottery_winrate', 'lottery_usepot', 'lottery_allow_systems')");
	my_rebuild_settings();
	
	db_drop_tables(array('plaza_lottery_tickets', 'plaza_lottery_numbers', 'plaza_lottery_winnings', 'plaza_lottery_systems'));
	
	
	delete_cache_items('myplaza_lottery_info');
}

function lottery_plugin()
{
	lottery_execute();
}

// calculates the mathematical combinations (same as nCr)
function combin($n, $r)
{
	return factorial($n) / (factorial($r) * factorial($n-$r));
}
// calculates $n!
function factorial($n)
{
	$i = $n;
	while(--$i)
		$n *= $i;
	return $n;
}

function lottery_run($item)
{
	if($item['idname'] != 'lottery_ticket') return false;
	
	global $mybb, $lang, $db, $buyRtnMsg, $buyLogMsg;
	
	if(!is_array($mybb->input['numbers']))
	{
		$buyRtnMsg = $lang->invalid_numbers;
		return false;
	}
	$numbers = array();
	foreach($mybb->input['numbers'] as $num => $val)
	{
		$num = intval($num);
		if($num < 1 || $num > intval($mybb->settings['lottery_max_num']))
		{
			$buyRtnMsg = $lang->invalid_numbers;
			return false;
		}
		
		$numbers[$num] = $num;
	}
	
	// default "system rate"
	$systemrate = 1;
	
	// if the user hasn't selected enough numbers, bail out
	if(count($numbers) < intval($mybb->settings['lottery_numbers']))
	{
		$buyRtnMsg = $lang->invalid_numbers;
		return false;
	}
	if(count($numbers) > intval($mybb->settings['lottery_numbers']))
	{
		// if the user has selected too many numbers, and system games aren't allowed, bail out
		if($mybb->settings['lottery_allow_systems'] == MY_NO)
		{
			$buyRtnMsg = $lang->invalid_numbers;
			return false;
		}
		// otherwise, check if we have a valid system
		$systemrate = $db->fetch_field($db->simple_select('plaza_lottery_systems', 'premiumrate', 'num_selectable='.count($numbers)), 'premiumrate');
		if($systemrate === null)
		{
			$buyRtnMsg = $lang->invalid_numbers;
			return false;
		}
		// check if user has enough money for the system game
		if($systemrate > 1)
		{
			$additional_cost = $item['cost'] * ($systemrate-1);
			if($mybb->user['money'] < $additional_cost && $additional_cost > 0)
			{
				$buyRtnMsg = $lang->insufficient_money;
				return false;
			}
			user_change_money($mybb->user, -$additional_cost);
		}
	}
	
	// add money to the pot (regardless of whether option is set or not)
	$add_pot = $item['cost'];
	if(isset($additional_cost)) $add_pot += $additional_cost;
	global $cache;
	$info = $cache->read('myplaza_lottery_info');
	if(!is_array($info)) $info = array();
	$info['pot'] += $add_pot;
	$cache->update('myplaza_lottery_info', $info);
	
	// all validated, add the ticket
	$db->insert_query(MY_TABLE_PREFIX.'plaza_lottery_tickets', array('uid' => $mybb->user['uid'], 'numbers' => implode(',',$numbers), 'dateline' => REQUEST_TIME));
	
	return true;
}

function lottery_execute()
{
	// this will generate the lottery numbers every period
	global $cache, $db;
	$info = $cache->read('myplaza_lottery_info');
	if(!is_array($info)) return;
	
	$timerange = intval($mybb->settings['lottery_draw_frequency'])*3600;
	if(REQUEST_TIME < $info['lastrun'] + $timerange) return;
	
	// okay, time to generate!
	// we'll generate all necessary numbers - however, we only need to check for the _single_ period _after_ the previous one
	$lottery_numbers = intval($mybb->settings['lottery_numbers']);
	$lottery_max_num = intval($mybb->settings['lottery_max_num']);
	$lottery_secondaries = intval($mybb->settings['lottery_secondaries']);
	
	// do we have a silly admin?
	if(($lottery_numbers + $lottery_secondaries) > $lottery_max_num) return;
	
	@ignore_user_abort(true);
	$number_inserts = array();
	for($t = $info['lastrun'] + $timerange; $t < REQUEST_TIME; $t+=$timerange)
	{
		$numbers = array();   $secondaries = array();
		for($i=0; $i<$lottery_numbers+$lottery_secondaries; $i++)
		{
			// force a unique number generation
			do {
				$n = mt_rand(1, $lottery_max_num);
			} while(isset($numbers[$n]) || isset($secondaries[$n]));
			if($i < $lottery_numbers)
				$numbers[$n] = $n;
			else
				$secondaries[$n] = $n;
		}
		
		// save the first set down
		if(!isset($numbers_check))
		{
			$numbers_check = $numbers;
			$secondaries_check = $secondaries;
		}
		$number_inserts[] = array('numbers' => implode(',',$numbers), 'secondaries' => implode(',',$secondaries), 'dateline' => $t);
	}
	db_shutdown_insert_rows('plaza_lottery_numbers', $number_inserts);
	
	$info['lastrun'] = $t;
	$pot_amount = $info['pot'];
	$info['pot'] = 0;
	$cache->update('myplaza_lottery_info', $info);
	
	// now we'll check the last draw
	$numbers = $numbers_check;
	$secondaries = $secondaries_check;
	unset($number_inserts);
	
	
	$winnings = $cache->read('myplaza_lottery_winnings');
	if(!is_array($winnings))
	{
		$winnings = cache_update_winnings();
	}
	// grab the lowest number of primaries (since most tickets will generally be a loss)
	$min_pmy = end($winnings);
	$min_pmy = $winnings['num_primary'];
	
	// loop through all the tickets
	$query = $db->simple_select(MY_TABLE_PREFIX.'plaza_lottery_tickets', '*');
	while($ticket = $db->fetch_array($query))
	{
		$selected_num = explode(',', $ticket['numbers']);
		$matches = lottery_calc_matches($selected_num, $numbers, $secondaries);
		// since most tickets will be a loss, we'll use this "optimization"
		if($matches['primary_matches'] < $min_pmy) continue;
		foreach($winnings as $winning)
		{
			if($matches['primary_matches'] >= $winning['num_primary'] && $matches['secondary_matches'] >= $winning['num_secondaries'])
			{
				user_change_money($ticket['uid'], $winning['winamount']);
				// calc pot amounts
				//send PM?
				// add to list of winners?
				break;
			}
		}
	}
	
	// so we've finished doing the payouts, clean up
	$db->delete_query(MY_TABLE_PREFIX.'plaza_lottery_tickets');
	@ignore_user_abort(false);
}

// sees how many matches exist
function lottery_calc_matches($selected_num, $primaries, $secondaries)
{
	$ret = array('primary_matches' => 0, 'secondary_matches' => 0);
	foreach($selected_num as $n)
	{
		if(isset($primaries[$n]))
			++$ret['primary_matches'];
		elseif(isset($secondaries[$n]))
			++$ret['secondary_matches'];
	}
	return $ret;
}

function cache_update_winnings($winnings = array())
{
	global $db, $cache;
	if(!is_array($winnings))
	{
		$query = $db->simple_select(MY_TABLE_PREFIX.'plaza_lottery_winnings', '*', '', array('order_by' => 'num_primary DESC, num_secondary DESC'));
		while($w = $db->fetch_array($query))
			$winnings[$w['wid']] = $w;
	}
	$cache->update('myplaza_lottery_winnings', $winnings);
	return $winnings;
}

function lottery_page()
{
	global $mybb, $templates;
	myplaza_standard_buy('lottery', "idname='lottery_ticket'");
	
	
	
	// get cur tickets
	// get prev numbers?
	// get pot?
	// get previous winners?
	// get payouts?
	
	// get system game info
	
	// generate number checkboxes
	
	return $templates->get('lottery_page');
}

function lottery_admin($process)
{
	global $mybb, $lang, $db;
	switch($mybb->input['laction'])
	{
		case 'tickets':
			if($process)
			{
				if(is_array($mybb->input['tickets']))
				{
					$tids = array();
					foreach($mybb->input['tickets'] as $tid => $delete)
					{
						if($delete != '1') continue;
						$tids[intval($tid)] = intval($tid);
					}
					$db->delete_query(MY_TABLE_PREFIX.'plaza_lottery_tickets', 'tid IN ('.implode(',',$tids).')');
				}
				myplaza_cpredirect('action=do_module&module=lottery&moduleaction=options', $lang->tickets_deleted);
			}
			else
			{
				$query = db_select(array(
					array('name' => 'plaza_lottery_tickets', 'alias' => 't'),
					array('name' => 'users', 'alias' => 'u', 'join' => 'left', 'on' => 't.uid=u.uid')
				), 't.*,u.username');
				
				cpheader_myplaza_module();
				starttable();
				tableheader($lang->lottery_tickets, "", 4);
				tablesubheader(array(
					$lang->tickets_username,
					$lang->tickets_numbers,
					$lang->tickets_date,
					$lang->tickets_del
				));
				
				makehiddencode('laction', 'tickets');
				while($ticket = $db->fetch_array($query))
				{
					$bgcolor = getaltbg();
					echo '<tr><td class="',$bgcolor,'" width="30%">',htmlspecialchars_uni($ticket['username']),'</td>
						<td class="',$bgcolor,'" width="40%">',$ticket['numbers'],'</td>
						<td class="',$bgcolor,'" width="30%">',date("jS M Y, G:i", $ticket['dateline']),'</td>
						<td class="',$bgcolor,'" width="1"><input type="checkbox" name="tickets[',$ticket['tid'],']" value="1" /></td></tr>';
				}
				endtable();
				
				cpfooter_myplaza_module();
			}
			
			break;
		case 'prunenos':
			if($process)
			{
				$days = intval($mybb->input['days']);
				$cutoff = REQUEST_TIME - ($days * 3600*24);
				
				$db->delete_query(MY_TABLE_PREFIX.'plaza_lottery_numbers', 'dateline < '.$cutoff);
				myplaza_cpredirect('action=do_module&module=lottery&moduleaction=options', $lang->numbers_pruned);
			}
			else
				die('Hacking attempt - well, not really, but who cares?');
			
			break;
		case 'winnings':
			if($process)
			{
				$wid = intval($mybb->input['wid']);
				switch($mybb->input['wlaction'])
				{
					case 'add':
					case 'edit':
						$update_array = array(
							'winamount' => round(floatval($mybb->input['winamount']), $mybb->settings['myplaza_money_decimals']),
							'potrate' => floatval($mybb->input['potrate']),
							'num_primary' => intval($mybb->input['num_primary']),
							'num_secondary' => intval($mybb->input['num_secondary'])
						);
						
						if($update_array['num_primary'] < 0 || $update_array['num_secondary'] < 0)
							cperror($lang->match_numbers_must_be_positive);
						
						if($mybb->input['wlaction'] == 'add')
							$db->insert_query(MY_TABLE_PREFIX.'plaza_lottery_winnings', $update_array);
						else
							$db->update_query(MY_TABLE_PREFIX.'plaza_lottery_winnings', $update_array, "wid=$wid");
						
						break;
					case 'del':
						$db->delete_query(MY_TABLE_PREFIX.'plaza_lottery_winnings', "wid=$wid");
						break;
					default:
						die('Hacking attempt - well, not really, but who cares?');
					
					cache_update_winnings();
					myplaza_cpredirect('action=do_module&module=lottery&moduleaction=options', $lang->winnings_updated);
				}
			}
			else
			{
				myplaza_cpheader();
				starttable();
				tableheader($lang->lottery_winnings, "", 5);
				tablesubheader(array($lang->winning_num_primary, $lang->winning_num_secondary, $lang->winning_payout, $lang->winning_potrate, '&nbsp'));
				
				$query = $db->simple_select(TABLE_PREFIX.'plaza_lottery_winnings', '*');
				while($winning = $db->fetch_array($query))
				{
					$bgcolor = getaltbg();
					echo '<tr>';
					startform('myplaza.php', '', 'do_module');
					makehiddencode("moduleaction", 'do_options');
					makehiddencode("module", 'lottery');
					makehiddencode("wlaction", 'edit');
					makehiddencode("wid", $winning['wid']);
					echo '
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="num_primary" value="'.$winning['num_primary']).'" size="20" /></td>
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="num_secondary" value="'.$winning['num_secondary']).'" size="20" /></td>
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="winamount" value="'.$winning['winamount']).'" size="20" /></td>
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="potrate" value="'.$winning['potrate']).'" size="20" /></td>
					<td class="'.$bgcolor.'" width="40%">';
					echo makebuttoncode("updatebutton", $lang->update);
					echo makebuttoncode("deletebutton", $lang->delete, 'button', 'if(confirm(\''.$lang->are_you_sure_delete.'\')) location.href = \'myplaza.php?'.SID.'&action=do_module&moduleaction=do_options&module=lottery&wlaction=del&wid='.$winning['wid'].'\';');
					echo '</td>';
					endform();
					echo '</tr>';
				}
				
				// add combination
				tablesubheader($lang->add_winning, '', 5);
				$bgcolor = getaltbg();
				echo '<tr>';
				startform('myplaza.php', '', 'do_module');
				makehiddencode("moduleaction", 'do_options');
				makehiddencode("module", 'lottery');
				makehiddencode("wlaction", 'add');
				echo '
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="num_primary" value="0" size="20" /></td>
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="num_secondary" value="0" size="20" /></td>
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="winamount" value="0" size="20" /></td>
					<td class="'.$bgcolor.'" width="15%"><input type="text" name="potrate" value="0" size="20" /></td>
				<td class="'.$bgcolor.'" width="40%">';
				echo makebuttoncode("addbutton", $lang->add);
				echo '</td>';
				endform();
				echo '</tr>';
				
				
				endtable();
				
				myplaza_cpfooter();
			}
			
			break;
		case 'systems':
		
		
		case 'settings':
			if($process)
			{
				myplaza_process_settings(array('lottery_max_num', 'lottery_numbers', 'lottery_secondaries', 'lottery_draw_frequency', 'lottery_winrate', 'lottery_usepot', 'lottery_allow_systems'));
			}
			else
			{
				cpheader_myplaza_module();
				starttable();
				tableheader($lang->lottery_options, "", 2);
				myplaza_generate_settings_code(array('lottery_max_num', 'lottery_numbers', 'lottery_secondaries', 'lottery_draw_frequency', 'lottery_winrate', 'lottery_usepot', 'lottery_allow_systems'));
				endtable();
				
				cpfooter_myplaza_module();
			}
			
			break;
		default:
			
			$iid = $db->fetch_field($db->simple_select(MY_TABLE_PREFIX.'plaza_items', 'iid', "idname = 'lottery_ticket'"), 'iid');
			cpheader_myplaza_module();
			starttable();
			tableheader($lang->lottery_options, "", 2);
			makelabelcode(sprintf($lang->lottery_options_main, 'myplaza.php?'.SID.'&action=do_module&module=lottery&moduleaction=options&', 'myplaza.php?'.SID.'&action=edititem&iid='.$iid));
			endtable();
			cpfooter_myplaza_module();
	}
}

?>