<?php

define('PAGE_MAGIC', 30);
define('MAX_OWNS', 50);

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

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

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

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

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

// 取得職照類別
$ownclass = array();
$classlv = array();
$ownclass[] = 0;
$sql = 'select position_class, max(position_order) as last_lv from xoops_pbb_rpg_medals where position_class <> 0 and uid = ' . $profiledata['uid'] . ' group by position_class';
if ( $result = $db->sql_query($sql) )
{
	if ( $row = $db->sql_fetchrow($result) )
	{
		do
		{
			$ownclass[] = $row['position_class'];
			$classlv[$row['position_class']] = $row['last_lv'] + 1;
		}
		while ( $row = $db->sql_fetchrow($result) );
	}
}

// 打工
// 新的應徵方式: 沒人作時直接上工，有人作時加入排班
if ( isset($HTTP_GET_VARS['job']) || isset($HTTP_POST_VARS['job']) )
{
	$sql = 'SELECT COUNT(*) as already_work FROM xoops_pbb_rpg_jobs WHERE worker_id = ' . $profiledata['uid'] .
		' AND (start_day + 43200) >= ' . time();
	if ( $result = $db->sql_query($sql) )
	{
		$row = $db->sql_fetchrow($result);
		if ($row['already_work'] > 0)
		{
			$itemerror = '一人不可兼任數職，請將機會讓給別人!!';
		}
	}

	if ( $itemerror == '' )
	{
		$sql = 'SELECT COUNT(*) as already_join FROM xoops_pbb_rpg_joinjobs WHERE uid = ' . $profiledata['uid'];
		if ( $result = $db->sql_query($sql) )
		{
			$row = $db->sql_fetchrow($result);
			if ($row['already_join'] > 0)
			{
				$itemerror = '您已經加入排班了!!';
			}
		}
	}
	if ( $itemerror == '' )
	{
		$jobid = intval(( isset($HTTP_GET_VARS['job']) ) ? $HTTP_GET_VARS['job'] : $HTTP_POST_VARS['job']);
		$sql = 'SELECT * FROM xoops_pbb_rpg_jobs WHERE job_id = ' . $jobid;
		$result = $db->sql_query($sql);
		if ( $row = $db->sql_fetchrow($result) )
		{
			if (($row['start_day'] == 0) && ($row['worker_id'] == 0) )
			{
				// 沒人作，直接上工
				if ($profiledata['user_money'] < $row['apply_fee'])
				{
					$itemerror = '現金不足，繳不出報名費!!';
				}
				else
				{
					$sql = 'update xoops_users set user_money = user_money - ' . $row['apply_fee'] . ' where uid = ' . $profiledata['uid'];
					$db->sql_query($sql);
					$sql = 'update xoops_pbb_rpg_jobs set start_day = ' . time() . ', worker_id = ' . $profiledata['uid'] .
						', worker_name = "' . $profiledata['uname'] . '", job_salary = 0 where job_id = ' . $jobid;
					$db->sql_query($sql);
					$profiledata['user_money'] -= $row['apply_fee'];
				}
			}
			else
			{
				if ($profiledata['user_money'] < $row['apply_fee'])
				{
					$itemerror = '現金不足，繳不出報名費!!';
				}
				else
				{
					$sql = 'update xoops_users set user_money = user_money - ' . $row['apply_fee'] . ' where uid = ' . $profiledata['uid'];
					$db->sql_query($sql);
					$sql = 'insert into xoops_pbb_rpg_joinjobs values (' . $profiledata['uid'] . ', ' . $jobid . ', 3, ' . time() . ')';
					$db->sql_query($sql);
					$profiledata['user_money'] -= $row['apply_fee'];
				}

			}
		}
	}
}

// 買魔法，技能
if ( isset($HTTP_GET_VARS['buy']) || isset($HTTP_POST_VARS['buy']) )
{
	$sql = 'SELECT COUNT(*) as take_count FROM xoops_pbb_rpg_owns WHERE uid = ' . $profiledata['uid'];
	$result = $db->sql_query($sql);
	if ( $row = $db->sql_fetchrow($result) )
	{
		if ( $row['take_count'] >= MAX_OWNS )
			message_die(GENERAL_MESSAGE, '一個人最多只能攜帶' . MAX_OWNS . '項物品，包含道具、武器、魔法、技能。' . $returnurl);
	}

	$itemid = intval(( isset($HTTP_GET_VARS['buy']) ) ? $HTTP_GET_VARS['buy'] : $HTTP_POST_VARS['buy']);
	$sql = 'select * from xoops_pbb_rpg_items where in_which_store = 3 and item_id = ' . $itemid;
	$result = $db->sql_query($sql);
	if ( $row = $db->sql_fetchrow($result) )
	{
		if ($row['need_level'] > $classlv[$row['need_class']])
			message_die(GENERAL_MESSAGE, '等級不足，無法學習!!' . $returnurl);

		$notinclass = true;
		for ($i = 0; $i < count($ownclass); $i++)
		{
			if (strstr($row['need_class'], strval($ownclass[$i])))
			{
				$notinclass = false;
				break;
			}
		}
		if ($notinclass)
			message_die(GENERAL_MESSAGE, '職業屬性不符，無法學習!!' . $returnurl);

		$sql = '';
		$job_salary = $row['item_price'];
		if ($row['item_spec_price'] > 0)
		{
			if ($profiledata['user_money'] >=
				floor(($profiledata['user_money'] + $profiledata['user_bank']) * $row['item_spec_price'] / 100))
			{
				if ($profiledata['user_money'] < $row['item_price'])
				{
					$itemerror = '現金不足!!';
				}
				else
				{
					$sql = 'update xoops_users set user_money = user_money - ' . $row['item_price'] . ' where uid = ' . intval($userdata['uid']);
				}
			}
			else
			{
				$job_salary = floor(($profiledata['user_money'] + $profiledata['user_bank']) * $row['item_spec_price'] / 100);
				if ($job_salary < $row['item_price'])
				{
					$itemerror = '資產不足!';
				}
				else
				{
					$remainpercent = 100 - $row['item_spec_price'];
					$sql = 'UPDATE xoops_users SET user_money = FLOOR(user_money * ' . $remainpercent .
						' / 100), user_bank = FLOOR(user_bank * ' . $remainpercent .
						' / 100) WHERE uid = ' . intval($userdata['uid']);
					unset($remainpercent);
				}
			}
		}
		else
		{
			if ($profiledata['user_money'] < $row['item_price'])
			{
				$itemerror = '現金不足!!';
			}
			else
			{
				$sql = 'UPDATE xoops_users SET user_money = user_money - ' . $row['item_price'] .
					' WHERE uid = ' . intval($userdata['uid']);
			}
		}
		if ($sql != '')
		{
			if ( !$db->sql_query($sql) )
			{
				message_die(GENERAL_ERROR, '無法進行扣款作業!!', '', __LINE__, __FILE__, $sql);
			}
			$sql = "insert into xoops_pbb_rpg_owns (uid, item_id) values (" . intval($userdata['uid']) . ", $itemid )";
			$db->sql_query($sql);
			$sql = "update xoops_pbb_rpg_jobs set job_salary = job_salary + floor($job_salary * profit_percent / 100) where in_which_store = 3 and (start_day + 43200) >= " . time() . " and worker_id > 0";
			$db->sql_query($sql);
			// UpdateRPGProperties(intval($userdata['uid']));
			$profiledata = get_userdata(intval($userdata['uid']));
		}
		unset($job_salary);
	}
}

// 賣魔法技能
if ( isset($HTTP_GET_VARS['sell']) || isset($HTTP_POST_VARS['sell']) )
{
	$ownid = intval(( isset($HTTP_GET_VARS['sell']) ) ? $HTTP_GET_VARS['sell'] : $HTTP_POST_VARS['sell']);
	$sql = "select * from xoops_pbb_rpg_owns where own_id = $ownid and uid = " . intval($userdata['uid']);
	$result = $db->sql_query($sql);
	if ( $row = $db->sql_fetchrow($result) )
	{
		$itemid = $row['item_id'];
	}
	else
	{
		message_die(GENERAL_MESSAGE, "找不到欲遺忘的魔法技能!! $returnurl");
	}
	$sql = "select * from xoops_pbb_rpg_items where item_id = $itemid";
	$result = $db->sql_query($sql);
	if ( $row = $db->sql_fetchrow($result) )
	{
		$sql = "delete from xoops_pbb_rpg_owns where own_id = $ownid and uid = " . intval($userdata['uid']);
		$db->sql_query($sql);
		$sql = 'update xoops_users set user_money = user_money + ' . floor($row['item_price'] * 0.6) . ' where uid = ' . intval($userdata['uid']);
		$db->sql_query($sql);
		// UpdateRPGProperties(intval($userdata['uid']));
		$profiledata = get_userdata(intval($userdata['uid']));
	}
}

// 取得工作列表
$no_need_to_join = false;
$sql = 'select count(*) as have_join from xoops_pbb_rpg_jobs where worker_id = ' . $profiledata['uid'];
$result = $db->sql_query($sql);
if ($row = $db->sql_fetchrow($result))
{
	$no_need_to_join = $row['have_join'] > 0;
}

if ( !($no_need_to_join) )
{
	$sql = 'select count(*) as have_join from xoops_pbb_rpg_joinjobs where uid = ' . $profiledata['uid'];
	$result = $db->sql_query($sql);
	if ($row = $db->sql_fetchrow($result))
	{
		$no_need_to_join = $row['have_join'] > 0;
	}
}

if ( $no_need_to_join )
{
	$sql = 'select job_id, count(*) as join_count from xoops_pbb_rpg_joinjobs where in_which_store = 3 group by job_id';
	$result = $db->sql_query($sql);
	if ($row = $db->sql_fetchrow($result))
	{
		$join_count = array();
		do
		{
			$join_count[$row['job_id']] = $row['join_count'];
		}
		while ($row = $db->sql_fetchrow($result));
	}
}



$jobslist = '';
$sql = 'select * from xoops_pbb_rpg_jobs where in_which_store = 3 order by apply_fee desc';
$result = $db->sql_query($sql);
if ( $row = $db->sql_fetchrow($result) )
{
	$i = 1;
	$jobslist = '<table class="forumline" width="100%" 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>
			<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
	{
		$jobslist .= '<tr><td class="row3" align="center"><span class="gensmall">' . $i .
				'</span></td><td><span class="gensmall">' . $row['job_name'] .
				'</span></td><td align="right"><span class="gensmall">' . number_format($row['apply_fee']) .
				'</span></td><td align="right"><span class="gensmall">' . $row['profit_percent'] .
				'</span></td><td><span class="gensmall">';
		if ( ((time() > ($row['start_day'] + 43200)) && ($row['start_day'] > 0)) || ($row['start_day'] == 0) )
		{
			$jobslist .= '缺人中</span></td><td></td><td></td>';
			$jobaction = '應徵';
		}
		else
		{
			$jobslist .= $row['worker_name'] . '</span></td><td align="center"><span class="gensmall">' .
					(create_date($userdata['user_dateformat'], ($row['start_day'] + 43200), $board_config['board_timezone'])) .
					'</span></td><td align="right"><span class="gensmall">' . $row['job_salary'] . '</span></td>';
			$jobaction = '排班';
		}
		$jobslist .= '<td align="center"><span class="gensmall">' .
				($no_need_to_join ? (empty($join_count[$row['job_id']]) ? 'N/A' : '排班人數:' . $join_count[$row['job_id']]) : '<a href=rpg.php?action=magic&job=' . $row['job_id'] . '>' . $jobaction . '</a>') .
				'</span></td></tr>';

		// 發薪時間
		if ((time() > ($row['start_day'] + 43200)) && ($row['start_day'] > 0))
		{
			$sql = 'update xoops_users set user_money = user_money + ' . $row['job_salary'] . ' where uid = ' . $row['worker_id'];
			$db->sql_query($sql);
			if ($row['worker_id'] == $profiledata['uid'])
				$profiledata['user_money'] += $row['job_salary'];
			$sql = 'update xoops_pbb_rpg_jobs set start_day = 0, worker_id = null, worker_name = null, job_salary = 0 where job_id = ' . $row['job_id'];
			$db->sql_query($sql);
			$sql = 'select j.uid, u.uname from xoops_pbb_rpg_joinjobs j, xoops_users u where j.job_id = ' . $row['job_id'] .
				' and j.uid = u.uid order by j.join_time limit 0, 1';
			$result2 = $db->sql_query($sql);
			if ( $row2 = $db->sql_fetchrow($result2) )
			{
				$sql = "update xoops_pbb_rpg_jobs set start_day = " . time() . ", worker_id = " . $row2['uid'] .
					", worker_name = '" . $row2['uname'] . "', job_salary = 0 where job_id = " . $row['job_id'];
				$db->sql_query($sql);
				$sql = "delete from xoops_pbb_rpg_joinjobs where uid = " . $row2['uid'];
				$db->sql_query($sql);
			}
		}
		$i++;
	}
	while ( $row = $db->sql_fetchrow($result) );
	$jobslist .= '</table><span class="gensmall">若沒人上工，則直接錄取；若有人上工，可加入排班，但須預繳報名費。<br />到任時，系統會從排班列表中取出下一位排班者接任。已有工作者不得加入排班並連任。(後續無人接任不在此限)</span>';
}

// 計算總頁次
$sql = 'select count(*) as magic_count from xoops_pbb_rpg_items where in_which_store = 3';
if ( $result = $db->sql_query($sql) )
{
   $row = $db->sql_fetchrow($result);
   $page_count = floor(($row['magic_count'] - 1) / PAGE_MAGIC) + 1;
}

$start_rec = intval(( isset($HTTP_GET_VARS['start']) ) ? $HTTP_GET_VARS['start'] : $HTTP_POST_VARS['start']);
$itemlist = '';
$sql = "select * from xoops_pbb_rpg_items where in_which_store = 3 order by need_class, need_level limit $start_rec, " . PAGE_MAGIC;
$result = $db->sql_query($sql);
if ( $row = $db->sql_fetchrow($result) )
{
	if ($page_count > 0)
	{
		$itemlist .= '<span class="gensmall"><b>頁次:';
		for ($i = 1; $i <= $page_count ; $i++)
		{
			if ($i == (floor($start_rec / PAGE_MAGIC) + 1) )
			{
				$itemlist .= ' ' . $i;
			}
			else
			{
				$itemlist .= ' <a href="rpg.php?action=magic&start=' . (($i - 1) * PAGE_MAGIC) . '">' . $i . '</a>';
			}
		}
		$itemlist .= '</span>';
	}
	$i = $start_rec + 1;
	$itemlist .= '<table class="forumline" width="100%" 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>
		<td align="center" class="catLeft"><b><span class="gen">學習</span></b></td></tr>';
	do
	{
		$itemlist .= '<tr><td class="row3" align="center"><span class="gensmall">' . $i .
				'</span></td><td><span class="gensmall">' . $row['item_name'] .
				'</span></td><td><span class="gensmall">' . $row['item_description'] .
				'</span></td><td align="right"><span class="gensmall">';
		if ($row['item_spec_price'] > 0)
		{
			$itemlist .= 'max(' . number_format($row['item_price']) . ', ' . $row['item_spec_price'] . '% 財產)';
		}
		else
		{
			$itemlist .= number_format($row['item_price']);
		}
		$itemlist .= '</span></td><td><span class="gensmall">' . GetTypies($row['need_class']) .
				'</span></td><td align="center"><span class="gensmall">' . $row['need_level'] .
				'</span></td><td align="center"><span class="gensmall"><a href=rpg.php?action=magic&start=' . $start_rec . '&buy=' .
				$row['item_id'] . '>學習</a></span></td></tr>';
		$i++;
	}
	while ( $row = $db->sql_fetchrow($result) );
	$itemlist .= '</table>';
}

// 取得攜帶列表
$ownlist = '無';

$sql = 'select o.own_id, i.* from xoops_pbb_rpg_items i, xoops_pbb_rpg_owns o where i.in_which_store = 3 and i.item_id = o.item_id and o.uid = ' . intval($userdata['uid']) . ' order by i.item_id limit 0, 50';
$result = $db->sql_query($sql);
if ( $row = $db->sql_fetchrow($result) )
{
	$i = 1;
	$ownlist = '<table class="forumline" width="100%" cellspacing="1" cellpadding="3" border="0">
		<tr><td align="center" class="catLeft"><b><span class="gen">#</span></b></td>
		<td class="catLeft" align="center" width="10%"><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 class="catLeft" align="center" width="12%"><b><span class="gen">動作</span></b></td></tr>';
	do
	{
		$ownlist .= '<tr><td class="row3" align="center"><span class="gensmall">' . $i .
				'</span></td><td><span class="gensmall">' . $row['item_name'] .
				'</span></td><td><span class="gensmall">' . $row['item_description'] .
				'</span></td><td align="right"><span class="gensmall">' . floor($row['item_price'] * 0.6) .
				'</span></td><td align="center"><span class="gensmall"><a href=rpg.php?action=magic&sell=' .
				$row['own_id'] . '>遺忘</a></span></td></tr>';
		$i++;
	}
	while ( $row = $db->sql_fetchrow($result) );
	$ownlist .= '</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_TYPE_LEVEL' => $profiledata['rpg_medals'],
	'RPG_JOBS_LIST' => $jobslist,
	'RPG_ITEM_LIST' => $itemlist,
	'RPG_OWN_LIST' => $ownlist,
	'RPG_ITEM_ERROR' => $itemerror,
	'L_NOWMENU' => '魔法技能學園') );

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

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

unset($returnurl);
unset($itemerror);
unset($ownclass);
unset($classlv);
unset($notinclass);
unset($jobid);
unset($jobslist);
unset($itemlist);
unset($ownlist);
unset($i);
unset($sql);
unset($page_count);
unset($start_rec);
unset($row);
unset($result);
unset($no_need_to_join);
unset($join_count);
unset($row2);
unset($result2);

?>