<?php

define('BALLS_COUNT', 22);
define('TICKET_COST', 100);
define('TICKET_COUNT', 100);
define('SUPER_JACKPOT', 100000);

include($phpbb_root_path . 'rpg/function_rpg.'.$phpEx);

function factN($m, $n)
{
	$retvalue = 1;
	for ($i = $m; $i <= $n; $i++)
	{
		$retvalue *= $i;
	}
	return $retvalue;
}

function gen_rand_no()
{
	srand((double)microtime()*1000000);
	$pick_list = array();
	for($i = 0; $i < 5; $i++)
	{
		$pick_no = rand(1, BALLS_COUNT);
		if ($i > 0)
		{
			while (true)
			{
				$found = false;
				for($j = 0; $j < $i; $j++)
				{
					if ($pick_list[$j] == $pick_no)
					{
						$found = true;
						break;
					}
				}
				if (! ($found) )
				{
					break;
				}
				$pick_no = rand(1, BALLS_COUNT);
			}
		}
		$pick_list[] = $pick_no;
	}
	return $pick_list;
}

if ( !defined('IN_PHPBB') )
{
	die("Hacking attempt");
	exit;
}

$returnurl = '<br /><br /><a href="rpg.php?action=gamble">返回上一頁</a>';

if ( CheckRefresh(1, intval($userdata['uid']), 10) )
{
	message_die(GENERAL_MESSAGE, '為了避免系統負荷過重，請間隔 10 秒再下注，請不要按重新整理!!' . $returnurl);
}

$template->set_filenames(array(
	'menu' => 'rpg_header.tpl',
	'body' => 'rpg_gamble.tpl')
);

// 取得個人資料
$profiledata = get_userdata(intval($userdata['uid']));

$rpg_gamble_result = "";
// $rpg_gamble_result = "now: " . time() . " nowtime:" . $nowtime . " lasttime:" . $lasttime;
// 亂數投注
if ( isset($HTTP_POST_VARS['submit']) )
{
	$tickets = intval($HTTP_POST_VARS['tickets']);
	if (($tickets > 0) && ($tickets <= TICKET_COUNT) && ($profiledata['user_money'] >= $tickets * TICKET_COST))
	{
		$jackno = gen_rand_no();
		$serv_jackpot = $board_config['rpg_jackpot'];
		if ($serv_jackpot < SUPER_JACKPOT)
		{
			$serv_jackpot = SUPER_JACKPOT;
		}
		$user_jackpot = 0;
		$star3 = 0;
		$star4 = 0;
		$star5 = 0;
		$rpg_gamble_result .= '<table class="forumline" width="80%" cellspacing="1" cellpadding="3" border="0">
		<tr><th class="thHead" colspan="7" height="25" nowrap="nowrap">頭彩號碼: ' . implode(' ', $jackno) . '</th></tr><tr>
		<td align="center" class="catLeft"><b><span class="gen">#</span></b></td>
		<td class="catRight" align="center" colspan="5"><b><span class="gen">選號結果</span></b></td>
		<td class="catRight" align="center"><b><span class="gen">對獎結果</span></b></td></tr>';
		for ($i = 0; $i < $tickets; $i++)
		{
			$rpg_gamble_result .= '<tr><td class="row3" align="center"><span class="gensmall">' . ($i + 1) . '</span></td>';
			$buyno = gen_rand_no();
			$star = 0;
			for ($j = 0; $j < 5; $j++)
			{
				for ($k = 0; $k < 5; $k++)
				{
					if ($buyno[$j] == $jackno[$k])
					{
						$star++;
						break;
					}
				}
				if ($k < 5)
				{
					$rpg_gamble_result .= '<td align="center" bgcolor=#FFBBBB><span class="gensmall">' . $buyno[$j] . '</span></td>';
				}
				else
				{
					$rpg_gamble_result .= '<td align="center"><span class="gensmall">' . $buyno[$j] . '</span></td>';
				}
			}
			switch ($star)
			{
				case 3:
					$rpg_gamble_result .= '<td><span class="gensmall"> 三星 - 1,000元</span></td>';
					$user_jackpot += 1000;
					$star3 += 1;
					break;
				case 4:
					$rpg_gamble_result .= '<td><span class="gensmall"> 四星 - 5,000元</span></td>';
					$user_jackpot += 5000;
					$star4 += 1;
					break;
				case 5:
					$rpg_gamble_result .= '<td><span class="gensmall">頭彩 - ' . number_format($serv_jackpot) . '元</span></td>';
					$user_jackpot += $serv_jackpot;
					$star5 += 1;
					$sql = "INSERT INTO xoops_pbb_rpg_jackpot values ('" . $profiledata['uname'] . "', " . $serv_jackpot . ", " . time() . ")";
					if( !$db->sql_query($sql) )
					{
						message_die(GENERAL_ERROR, "無法更新頭彩列表!!", "", __LINE__, __FILE__, $sql);
					}
					$serv_jackpot = SUPER_JACKPOT;
					break;
			}
			$rpg_gamble_result .= '</tr>';
		}
		$rpg_gamble_result .= '<tr><td class="row3" colspan="7"><span class="gensmall">投注金額: ' . $tickets * TICKET_COST . '<br />中獎獎金: ' . $user_jackpot .
		                      '<br />獎金分佈: 三星 ' . $star3 . ' 注　四星 ' . $star4 . ' 注　頭彩 ' . $star5 . ' 注<br /><b>';
		if ($user_jackpot >= $tickets * TICKET_COST)
		{
			$rpg_gamble_result .= '恭禧您!!本次投注賺了 ' . ($user_jackpot - $tickets * TICKET_COST);
		}
		else
		{
			$rpg_gamble_result .= '真可憐!!本次投注賠了 ' . ($tickets * TICKET_COST - $user_jackpot);
		}
		$rpg_gamble_result .= ' 元</b></span></td></tr></table>';

		$sql = "UPDATE " . CONFIG_TABLE . " SET config_value = config_value + " . ($tickets * TICKET_COST) . " - " . $user_jackpot . " WHERE config_name = 'rpg_jackpot'";
		if( !$db->sql_query($sql) )
		{
			message_die(GENERAL_ERROR, "無法更新頭彩獎金!!", "", __LINE__, __FILE__, $sql);
		}
		$sql = "UPDATE " . CONFIG_TABLE . " SET config_value = " . SUPER_JACKPOT . " WHERE config_name = 'rpg_jackpot' and config_value < " . SUPER_JACKPOT;
		if( !$db->sql_query($sql) )
		{
			message_die(GENERAL_ERROR, "無法更新頭彩初始獎金!!", "", __LINE__, __FILE__, $sql);
		}
		$sql = "UPDATE " . USERS_TABLE . " SET user_money = user_money - " . ($tickets * TICKET_COST) . " + " . $user_jackpot . " WHERE uid = " . intval($userdata['uid']);
		if( !$db->sql_query($sql) )
		{
			message_die(GENERAL_ERROR, "無法更新會員的水怪貨幣!!", "", __LINE__, __FILE__, $sql);
		}
		$profiledata = get_userdata(intval($userdata['uid']));
		$sql = 'SELECT * FROM xoops_pbb_config where config_name = "rpg_jackpot"';
		if( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, '無法取得頭彩彩金!!', '', __LINE__, __FILE__, $sql);
		}
		if ( $row = $db->sql_fetchrow($result) )
		{
			$board_config['rpg_jackpot'] = $row['config_value'];
		}
	}
	else
	{
		$rpg_gamble_result = "1. 彩券張數輸入錯誤!!<br />2. 彩券不得大於" . TICKET_COUNT . "張!!<br />3. 金額不足!!";
	}
}

// 包牌
if ( isset($HTTP_POST_VARS['playcustno']) )
{
	$mark_list = ( !empty($HTTP_POST_VARS['mark']) ) ? $HTTP_POST_VARS['mark'] : 0;
	if ( isset($mark_list) && !is_array($mark_list) )
	{
		$mark_list = array();
	}
	$counter = count($mark_list);
	if ( $counter >= 5 )
	{
		$ticketneeded = floor(factN($counter-4, $counter) / factN(1, 5));
		if ($ticketneeded > TICKET_COUNT)
		{
			$ticketneeded = TICKET_COUNT;
		}
		if ($ticketneeded * TICKET_COST > $profiledata['user_money'])
		{
			message_die(GENERAL_MESSAGE, '金額不足，無法投注，您總共需要 $' . $ticketneeded * TICKET_COST .
							' 以便投注 ' . $ticketneeded . ' 組號碼!!' . $returnurl);
		}

		$jackno = gen_rand_no();
		$serv_jackpot = $board_config['rpg_jackpot'];
		if ($serv_jackpot < SUPER_JACKPOT)
		{
			$serv_jackpot = SUPER_JACKPOT;
		}
		$user_jackpot = 0;
		$star3 = 0;
		$star4 = 0;
		$star5 = 0;
		$rpg_gamble_result .= '<table class="forumline" width="80%" cellspacing="1" cellpadding="3" border="0">
		<tr><th class="thHead" colspan="7" height="25" nowrap="nowrap">頭彩號碼: ' . implode(' ', $jackno) . '</th></tr><tr>
		<td align="center" class="catLeft"><b><span class="gen">#</span></b></td>
		<td class="catRight" align="center" colspan="5"><b><span class="gen">選號結果</span></b></td>
		<td class="catRight" align="center"><b><span class="gen">對獎結果</span></b></td></tr>';
		$totalcount = 1;
		for ($a = 0; ($a <= $counter - 5) && ($totalcount <= TICKET_COUNT); $a++)
		{
			for ($b=$a + 1; ($b <= $counter - 4) && ($totalcount <= TICKET_COUNT); $b++)
			{
				for ($c=$b + 1; ($c <= $counter - 3) && ($totalcount <= TICKET_COUNT); $c++)
				{
					for ($d = $c + 1; ($d <= $counter - 2) && ($totalcount <= TICKET_COUNT); $d++)
					{
						for ($e = $d + 1; ($e <= $counter - 1) && ($totalcount <= TICKET_COUNT); $e++)
						{
							$star = 0;
							$rpg_gamble_result .= '<tr><td class="row3" align="center"><span class="gensmall">' . ($totalcount) . '</span></td>';
							if ( ($mark_list[$a] == $jackno[0]) || ($mark_list[$a] == $jackno[1]) || ($mark_list[$a] == $jackno[2]) ||
								($mark_list[$a] == $jackno[3]) || ($mark_list[$a] == $jackno[4]) )
							{
								$rpg_gamble_result .= '<td align="center" bgcolor=#FFBBBB><span class="gensmall">' . $mark_list[$a] . '</span></td>';
								$star++;
							}
							else
							{
								$rpg_gamble_result .= '<td align="center"><span class="gensmall">' . $mark_list[$a] . '</span></td>';
							}
							if ( ($mark_list[$b] == $jackno[0]) || ($mark_list[$b] == $jackno[1]) || ($mark_list[$b] == $jackno[2]) ||
								($mark_list[$b] == $jackno[3]) || ($mark_list[$b] == $jackno[4]) )
							{
								$rpg_gamble_result .= '<td align="center" bgcolor=#FFBBBB><span class="gensmall">' . $mark_list[$b] . '</span></td>';
								$star++;
							}
							else
							{
								$rpg_gamble_result .= '<td align="center"><span class="gensmall">' . $mark_list[$b] . '</span></td>';
							}
							if ( ($mark_list[$c] == $jackno[0]) || ($mark_list[$c] == $jackno[1]) || ($mark_list[$c] == $jackno[2]) ||
								($mark_list[$c] == $jackno[3]) || ($mark_list[$c] == $jackno[4]) )
							{
								$rpg_gamble_result .= '<td align="center" bgcolor=#FFBBBB><span class="gensmall">' . $mark_list[$c] . '</span></td>';
								$star++;
							}
							else
							{
								$rpg_gamble_result .= '<td align="center"><span class="gensmall">' . $mark_list[$c] . '</span></td>';
							}
							if ( ($mark_list[$d] == $jackno[0]) || ($mark_list[$d] == $jackno[1]) || ($mark_list[$d] == $jackno[2]) ||
								($mark_list[$d] == $jackno[3]) || ($mark_list[$d] == $jackno[4]) )
							{
								$rpg_gamble_result .= '<td align="center" bgcolor=#FFBBBB><span class="gensmall">' . $mark_list[$d] . '</span></td>';
								$star++;
							}
							else
							{
								$rpg_gamble_result .= '<td align="center"><span class="gensmall">' . $mark_list[$d] . '</span></td>';
							}
							if ( ($mark_list[$e] == $jackno[0]) || ($mark_list[$e] == $jackno[1]) || ($mark_list[$e] == $jackno[2]) ||
								($mark_list[$e] == $jackno[3]) || ($mark_list[$e] == $jackno[4]) )
							{
								$rpg_gamble_result .= '<td align="center" bgcolor=#FFBBBB><span class="gensmall">' . $mark_list[$e] . '</span></td>';
								$star++;
							}
							else
							{
								$rpg_gamble_result .= '<td align="center"><span class="gensmall">' . $mark_list[$e] . '</span></td>';
							}

							switch ($star)
							{
								case 3:
									$rpg_gamble_result .= '<td><span class="gensmall">三星 - 1,000元</span></td>';
									$user_jackpot += 1000;
									$star3++;
									break;
								case 4:
									$rpg_gamble_result .= '<td><span class="gensmall">四星 - 5,000元</span></td>';
									$user_jackpot += 5000;
									$star4++;
									break;
								case 5:
									$rpg_gamble_result .= '<td><span class="gensmall">頭彩 - ' . number_format($serv_jackpot) . '元</span></td>';
									$user_jackpot += $serv_jackpot;
									$star5++;
									$sql = "INSERT INTO xoops_pbb_rpg_jackpot values ('" . $profiledata['uname'] . "', " . $serv_jackpot . ", " . time() . ")";
									if( !$db->sql_query($sql) )
									{
										message_die(GENERAL_ERROR, "無法更新頭彩列表!!", "", __LINE__, __FILE__, $sql);
									}
									$serv_jackpot = SUPER_JACKPOT;
									break;
							}
							$rpg_gamble_result .= '</tr>';
							$totalcount++;
						}
					}
				}
			}
		}
		$totalcount--;
		$rpg_gamble_result .= '<tr><td class="row3" colspan="7"><span class="gensmall">投注金額: ' . ($totalcount * TICKET_COST) . '<br />中獎獎金: ' . $user_jackpot .
		                      '<br />獎金分佈: 三星 ' . $star3 . ' 注　四星 ' . $star4 . ' 注　頭彩 ' . $star5 . ' 注<br /><b>';
		if ($user_jackpot >= $totalcount * TICKET_COST)
		{
			$rpg_gamble_result .= '恭禧您!!本次投注賺了 ' . ($user_jackpot - $totalcount * TICKET_COST);
		}
		else
		{
			$rpg_gamble_result .= '真可憐!!本次投注賠了 ' . ($totalcount * TICKET_COST - $user_jackpot);
		}
		$rpg_gamble_result .= ' 元</b></span></td></tr></table>';

		$sql = "UPDATE " . CONFIG_TABLE . " SET config_value = config_value + " . ($totalcount * TICKET_COST) . " - " . $user_jackpot . " WHERE config_name = 'rpg_jackpot'";
		if( !$db->sql_query($sql) )
		{
			message_die(GENERAL_ERROR, "無法更新頭彩獎金!!", "", __LINE__, __FILE__, $sql);
		}
		$sql = "UPDATE " . CONFIG_TABLE . " SET config_value = " . SUPER_JACKPOT . " WHERE config_name = 'rpg_jackpot' and config_value < " . SUPER_JACKPOT;
		if( !$db->sql_query($sql) )
		{
			message_die(GENERAL_ERROR, "無法更新頭彩初始獎金!!", "", __LINE__, __FILE__, $sql);
		}
		$sql = "UPDATE " . USERS_TABLE . " SET user_money = user_money - " . ($totalcount * TICKET_COST) . " + " . $user_jackpot . " WHERE uid = " . intval($userdata['uid']);
		if( !$db->sql_query($sql) )
		{
			message_die(GENERAL_ERROR, "無法更新會員的水怪貨幣!!", "", __LINE__, __FILE__, $sql);
		}
		$profiledata = get_userdata(intval($userdata['uid']));
		$sql = 'SELECT * FROM xoops_pbb_config where config_name = "rpg_jackpot"';
		if( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, '無法取得頭彩彩金!!', '', __LINE__, __FILE__, $sql);
		}
		if ( $row = $db->sql_fetchrow($result) )
		{
			$board_config['rpg_jackpot'] = $row['config_value'];
		}
	}
	else
	{
		$rpg_gamble_result = "請選擇 5 個號碼以上";
	}
}

// 取得頭彩列表
$jackpotlist1 = "";
$sql = 'SELECT * FROM xoops_pbb_rpg_jackpot ORDER BY jackpot_date DESC LIMIT 0, 10';
if( !($result = $db->sql_query($sql)) )
{
	message_die(GENERAL_ERROR, '無法取得頭彩列表!!', '', __LINE__, __FILE__, $sql);
}
if ( $row = $db->sql_fetchrow($result) )
{
	$i = 1;
	$jackpotlist1 = '<table class="forumline" width="80%" cellspacing="1" cellpadding="3" border="0">
		<tr><td align="center" class="catLeft"><b><span class="gen">#</span></b></td>
		<td align="center" class="catLeft"><b><span class="gen">得獎會員</span></b></td>
		<td align="center" class="catLeft"><b><span class="gen">頭彩金額</span></b></td>
		<td align="center" class="catLeft"><b><span class="gen">得獎日期</span></b></td></tr>';
	do
	{
		$jackpotlist1 .= '<tr><td class="row3" align="center"><span class="gensmall">' . $i .
					'</span></td><td><span class="gensmall">' . $row['uname'] .
					'</span></td><td align="right"><span class="gensmall">' . number_format($row['user_jackpot']) .
					'</span></td><td align="center"><span class="gensmall">' .
					create_date($userdata['user_dateformat'], $row['jackpot_date'], $board_config['board_timezone']) .
					'</span></td></tr>';
		$i++;
	}
	while ( $row = $db->sql_fetchrow($result) );
	$jackpotlist1 .= '</table>';
}

$jackpotlist2 = "";
$sql = 'SELECT * FROM xoops_pbb_rpg_jackpot ORDER BY user_jackpot DESC LIMIT 0, 10';
if( !($result = $db->sql_query($sql)) )
{
	message_die(GENERAL_ERROR, '無法取得頭彩列表!!', '', __LINE__, __FILE__, $sql);
}
if ( $row = $db->sql_fetchrow($result) )
{
	$i = 1;
	$jackpotlist2 = '<table class="forumline" width="80%" cellspacing="1" cellpadding="3" border="0">
		<tr><td align="center" class="catLeft"><b><span class="gen">#</span></b></td>
		<td align="center" class="catLeft"><b><span class="gen">得獎會員</span></b></td>
		<td align="center" class="catLeft"><b><span class="gen">頭彩金額</span></b></td>
		<td align="center" class="catLeft"><b><span class="gen">得獎日期</span></b></td></tr>';
	do
	{
		$jackpotlist2 .= '<tr><td class="row3" align="center"><span class="gensmall">' . $i .
					'</span></td><td><span class="gensmall">' . $row['uname'] .
					'</span></td><td align="right"><span class="gensmall">' . number_format($row['user_jackpot']) .
					'</span></td><td align="center"><span class="gensmall">' .
					create_date($userdata['user_dateformat'], $row['jackpot_date'], $board_config['board_timezone']) .
					'</span></td></tr>';
		$i++;
	}
	while ( $row = $db->sql_fetchrow($result) );
	$jackpotlist2 .= '</table>';
}

$moneylist = "";
$sql = 'SELECT uname, (user_money+user_bank) as money_total, user_money, user_bank, posts FROM xoops_users ORDER BY 2 DESC LIMIT 0, 10';
if( !($result = $db->sql_query($sql)) )
{
	message_die(GENERAL_ERROR, '無法取得富豪列表!!', '', __LINE__, __FILE__, $sql);
}
if ( $row = $db->sql_fetchrow($result) )
{
	$i = 1;
	$moneylist = '<table class="forumline" width="80%" cellspacing="1" cellpadding="3" border="0">
		<tr><td align="center" class="catLeft"><b><span class="gen">#</span></b></td>
		<td align="center" class="catLeft"><b><span class="gen">富豪名稱</span></b></td>
		<td align="center" class="catLeft"><b><span class="gen">現金</span></b></td>
		<td align="center" class="catLeft"><b><span class="gen">銀行存款</span></b></td>
		<td align="center" class="catLeft"><b><span class="gen">財產總額</span></b></td>
		<td align="center" class="catLeft"><b><span class="gen">發表篇數</span></b></td></tr>';
	do
	{
		$moneylist .= '<tr><td class="row3" align="center"><span class="gensmall">' . $i .
				'</span></td><td><span class="gensmall">' . $row['uname'] .
				'</span></td><td align="right"><span class="gensmall">' . number_format($row['user_money']) .
				'</span></td><td align="right"><span class="gensmall">' . number_format($row['user_bank']) .
				'</span></td><td align="right"><span class="gensmall">' . number_format($row['money_total']) .
				'</span></td><td align="right"><span class="gensmall">' . $row['posts'] .
				'</span></td></tr>';
		$i++;
	}
	while ( $row = $db->sql_fetchrow($result) );
	$moneylist .= '</table>';
}

// 產生自選號碼
$custnolist = '<table><tr>';
if ( isset($HTTP_POST_VARS['playcustno']) )
{
	for ($i = 1; $i <= BALLS_COUNT; $i++)
	{
		if (($i > 1) && ($i % 5 == 1))
		{
			$custnolist .= '</tr><tr>';
		}
		$oldnumber = false;
		for ($j = 0; $j < $counter; $j++)
		{
			if ($i == $mark_list[$j])
			{
				$oldnumber = true;
				break;
			}
		}
		if ($oldnumber)
		{
			$custnolist .= '<td><input type="checkbox" name="mark[]2" value="' . $i . '" checked />' . $i . '&nbsp;&nbsp;</td>';
		}
		else
		{
			$custnolist .= '<td><input type="checkbox" name="mark[]2" value="' . $i . '" />' . $i . '&nbsp;&nbsp;</td>';
		}
	}
}
else
{
	for ($i = 1; $i <= BALLS_COUNT; $i++)
	{
		if (($i > 1) && ($i % 5 == 1))
		{
			$custnolist .= '</tr><tr>';
		}
		$custnolist .= '<td><input type="checkbox" name="mark[]2" value="' . $i . '" />' . $i . '&nbsp;&nbsp;</td>';
	}
}
$custnolist .= '</tr></table>';

// 產生資料頁面
$page_title = "水怪大陸 RPG 首頁";
include($phpbb_root_path . 'includes/page_header.'.$phpEx);

$template->assign_vars(array(
	'USERNAME' => $profiledata['uname'],
	'AVATAR_IMG' => GetAvatar($profiledata),
	'RPG_MONEY' => number_format($profiledata['user_money']),
	'RPG_JACKPOT_LIST1' => $jackpotlist1,
	'RPG_JACKPOT_LIST2' => $jackpotlist2,
	'RPG_MONEY_LIST' => $moneylist,
	'RPG_JACKPOT_CUSTNO' => $custnolist,
	'RPG_JACKPOT' => number_format($board_config['rpg_jackpot']),
	'RPG_GAMBLE_RESULT' => $rpg_gamble_result,
	'L_NOWMENU' => '樂透致富中心') );

$template->pparse('menu');
$template->pparse('body');

include($phpbb_root_path . 'includes/page_tail.'.$phpEx);

?>