<?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_steal_enabled'])
{
	// No permission to steal
	print_no_permission();
}

// Ensure this is an array
VBSHOP::verify_purchases($vbulletin->userinfo);

foreach ($vbulletin->userinfo['dbtech_vbshop_purchase'] as $purchaseid => $purchase)
{
	if (!$purchase['active'])
	{
		// Inactive item
		continue;
	}
	
	// Shorthand
	$item = VBSHOP::$cache[$purchase['feature']][$purchase['featureid']];
	
	if (!in_array($item['itemtypeid'], array('stealmore', 'stealchance')))
	{
		// Skip this item
		continue;
	}
	
	// Set what field we're modifying
	$field = ($item['itemtypeid'] == 'stealmore' ? 'amount' : 'chance');
	
	// Update the field
	$vbulletin->options['dbtech_vbshop_steal_' . $field] += doubleval($item['code']['value']);
}

// Ensure this is never above 100
$vbulletin->options['dbtech_vbshop_steal_amount'] = doubleval($vbulletin->options['dbtech_vbshop_steal_amount'] > $vbulletin->options['dbtech_vbshop_maxsteal_amount'] ? 
	$vbulletin->options['dbtech_vbshop_maxsteal_amount'] :
	$vbulletin->options['dbtech_vbshop_steal_amount']
);
$vbulletin->options['dbtech_vbshop_steal_chance'] = doubleval($vbulletin->options['dbtech_vbshop_steal_chance'] > $vbulletin->options['dbtech_vbshop_maxsteal_chance'] ?
	$vbulletin->options['dbtech_vbshop_maxsteal_chance'] :
	$vbulletin->options['dbtech_vbshop_steal_chance']
);

// #############################################################################
if ($_REQUEST['action'] == 'steal' OR empty($_REQUEST['action']))
{
	// Add to the navbits
	$navbits[''] = $pagetitle = $vbphrase['dbtech_vbshop_steal'];
	
	foreach (VBSHOP::$cache['currency'] as $currencyid => $currency)
	{
		if (!$currency['active'])
		{
			// Can't bank this
			continue;
		}
		
		if (!$currency['cansteal'])
		{
			// Can't bank this
			continue;
		}
		
		// Create the archive template
		$templater = vB_Template::create('option');
			$templater->register('optionvalue', 	$currencyid);
			$templater->register('optiontitle', 	$currency['title']);
		$currencies .= $templater->render();	
	}
	
	if (!$currencies)
	{
		// No stealable currencies
		print_no_permission();
	}
	
	// Create the archive template
	$page_templater = vB_Template::create('dbtech_vbshop_steal');
		$page_templater->register('pagetitle', 	$pagetitle);
		$page_templater->register('currencies', $currencies);
	$HTML = $page_templater->render();
}

// #############################################################################
if ($_POST['action'] == 'dosteal')
{
	$vbulletin->input->clean_array_gpc('p', array(
		'username' 		=> TYPE_STR,
		'currencyid' 	=> TYPE_UINT,
	));
	
	if (!$currency = VBSHOP::$cache['currency'][$vbulletin->GPC['currencyid']])
	{
		// Woups, immune
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', construct_phrase($vbphrase['dbtech_vbshop_invalid_x'], $vbphrase['dbtech_vbshop_currency'], $vbulletin->GPC['currencyid']))));
	}
		
	if (!$currency['active'])
	{
		// Woups, immune
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', construct_phrase($vbphrase['dbtech_vbshop_invalid_x'], $vbphrase['dbtech_vbshop_currency'], $vbulletin->GPC['currencyid']))));
	}
		
	if (!$currency['cansteal'])
	{
		// Woups, immune
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', construct_phrase($vbphrase['dbtech_vbshop_invalid_x'], $vbphrase['dbtech_vbshop_currency'], $vbulletin->GPC['currencyid']))));
	}
		
	// Stealing from
	if (!$existing = $db->query_first_slave("
		SELECT *
		FROM " . TABLE_PREFIX . "user
		WHERE username = " . $db->sql_prepare(htmlspecialchars_uni($vbulletin->GPC['username']))
	))
	{
		eval(standard_error(fetch_error('invalid_user_specified')));
	}
	
	// Is the user immune?
	require_once(DIR . '/includes/adminfunctions.php');
	require_once(DIR . '/includes/adminfunctions_options.php');
	$bitfielddefs =& fetch_bitfield_definitions('nocache|dbtech_vbshop_immunity');
	foreach ($bitfielddefs AS $key => $val)
	{
		if ($key == 'dbtech_vbshop_theft' AND ((int)$existing['dbtech_vbshop_immunity'] & (int)$val))
		{
			// Woups, immune
			eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_recipient_immune'])));
		}
	}
	
	if (mt_rand(1, 100) <= $vbulletin->options['dbtech_vbshop_steal_chance'])
	{
		// Success
		
		// Grab our points value
		$userpoints = $db->query_first_slave("
			SELECT " . $currency['pointscolumn'] . " AS points
			FROM " . TABLE_PREFIX . $currency['pointstable'] . "
			WHERE userid = " . $existing['userid']
		);
		
		// Grab bank value
		$userpoints2 = $db->query_first_slave("
			SELECT points AS points_bank
			FROM " . TABLE_PREFIX . "dbtech_vbshop_bank
			WHERE userid = " . $existing['userid'] . "
				AND currencyid = " . $currency['currencyid']
		);
		
		if (is_array($userpoints2))
		{
			// Merge the two
			$userpoints = array_merge($userpoints, $userpoints2);
		}
		
		// The amount of money we gained
		$gain = array(
			'bank' 		=> 0,
			'wallet' 	=> 0,
			'total' 	=> 0,
		);
	
		if ($userpoints['points_bank'] > doubleval($currency['stealprotect']) AND doubleval($currency['stealprotect']) > -1)
		{
			// We stole from a person's bank
			$gain['bank'] = round(doubleval((($userpoints['points_bank'] - doubleval($currency['stealprotect'])) / 100) * $vbulletin->options['dbtech_vbshop_steal_chance']), 2);
			$gain['total'] += $gain['bank'];
		}
	
		if ($userpoints['points'] > 0)
		{
			// We stole from a person's wallet
			$gain['wallet'] = round(doubleval((($userpoints['points']) / 100) * $vbulletin->options['dbtech_vbshop_steal_chance']), 2);
			$gain['total'] += $gain['wallet'];
		}
	
		// Update ze moneys!
		if ($gain['bank'] > 0)
		{
			$db->query_write("
				UPDATE " . TABLE_PREFIX . "dbtech_vbshop_bank
				SET points = points - " . $gain['bank'] . "
				WHERE userid = " . $existing['userid'] . "
					AND currencyid = " . $currency['currencyid']
			);
		}
	
		if ($gain['wallet'] > 0)
		{
			$db->query_write("
				UPDATE " . TABLE_PREFIX . $currency['pointstable'] . "
				SET " . $currency['pointscolumn'] . " = " . $currency['pointscolumn'] . " - " . $gain['wallet'] . "
				WHERE userid = " . $existing['userid']
			);
		}
		
		if ($gain['total'] > 0)
		{
			$db->query_write("
				UPDATE " . TABLE_PREFIX . $currency['pointstable'] . "
				SET " . $currency['pointscolumn'] . " = " . $currency['pointscolumn'] . " + " . $gain['total'] . "
				WHERE userid = " . $vbulletin->userinfo['userid']
			);
		}
		
		$info = array(
			'currencyid' 	=> $currency['currencyid'],
			'gain' 			=> $gain,
		);

		// init data manager
		$dm =& VBSHOP::initDataManager('Transactionlog', $vbulletin, ERRTYPE_ARRAY);
			$dm->set('userid', 		$vbulletin->userinfo['userid']);
			$dm->set('recipient', 	$existing['userid']);
			$dm->set('ipaddress', 	IPADDRESS);
			$dm->set('action', 		'stealsuccess');
			$dm->set('info', 		$info);
		$dm->save();
		unset($dm);		
	
		$title = construct_phrase($vbphrase['dbtech_vbshop_steal_success_from_x'], $vbulletin->userinfo['username']);
		$message = construct_phrase($vbphrase['dbtech_vbshop_steal_success_from_x_message'], $vbulletin->userinfo['username'], $gain['bank'], $gain['wallet'], $currency['title']);
		$report = construct_phrase($vbphrase['dbtech_vbshop_steal_success_report'], $gain['bank'], $gain['wallet'], $currency['title']);
	}
	else
	{
		// Fail
		
		// Grab our points value
		$userpoints = $db->query_first_slave("
			SELECT " . $currency['pointscolumn'] . " AS points
			FROM " . TABLE_PREFIX . $currency['pointstable'] . "
			WHERE userid = " . $vbulletin->userinfo['userid']
		);
		
		// Grab bank value
		$userpoints2 = $db->query_first_slave("
			SELECT points AS points_bank
			FROM " . TABLE_PREFIX . "dbtech_vbshop_bank
			WHERE userid = " . $vbulletin->userinfo['userid'] . "
				AND currencyid = " . $currency['currencyid']
		);
		
		// Merge the two
		$userpoints = array_merge((array)$userpoints, (array)$userpoints2);
		
		// The amount of money we gained
		$loss = array(
			'bank' 		=> 0,
			'wallet' 	=> 0,
			'total' 	=> 0,
		);
		
		if ($userpoints['points_bank'] > 0)
		{
			// We stole from a person's bank
			$loss['bank'] = round(doubleval((($userpoints['points_bank']) / 100) * doubleval($vbulletin->options['dbtech_vbshop_steal_lose'])), 2);
			$loss['total'] += $loss['bank'];
		}
	
		if ($userpoints['points'] > 0)
		{
			// We stole from a person's wallet
			$loss['wallet'] = round(doubleval((($userpoints['points']) / 100) * doubleval($vbulletin->options['dbtech_vbshop_steal_lose'])), 2);
			$loss['total'] += $loss['wallet'];
		}
		
		// Update ze moneys!
		if ($loss['bank'] > 0)
		{
			$db->query_write("
				UPDATE " . TABLE_PREFIX . "dbtech_vbshop_bank
				SET points = points - " . $loss['bank'] . "
				WHERE userid = " . $vbulletin->userinfo['userid'] . "
					AND currencyid = " . $currency['currencyid']
			);
		}
	
		if ($loss['wallet'] > 0)
		{
			$db->query_write("
				UPDATE " . TABLE_PREFIX . $currency['pointstable'] . "
				SET " . $currency['pointscolumn'] . " = " . $currency['pointscolumn'] . " - " . $loss['wallet'] . "
				WHERE userid = " . $vbulletin->userinfo['userid']
			);
		}
		
		/*
		if ($loss['total'] > 0)
		{
			$db->query_write("
				UPDATE " . TABLE_PREFIX . $currency['pointstable'] . "
				SET " . $currency['pointscolumn'] . " = " . $currency['pointscolumn'] . " + " . $loss['total'] . "
				WHERE userid = " . $existing['userid']
			);
		}
		*/
		
		$info = array(
			'currencyid' 	=> $currency['currencyid'],
			'loss' 			=> $loss,
		);

		// init data manager
		$dm =& VBSHOP::initDataManager('Transactionlog', $vbulletin, ERRTYPE_ARRAY);
			$dm->set('userid', 		$vbulletin->userinfo['userid']);
			$dm->set('recipient', 	$existing['userid']);
			$dm->set('ipaddress', 	IPADDRESS);
			$dm->set('action', 		'stealfail');
			$dm->set('info', 		$info);
		$dm->save();
		unset($dm);		
	
		$title = construct_phrase($vbphrase['dbtech_vbshop_steal_fail_from_x'], $vbulletin->userinfo['username']);
		$message = construct_phrase($vbphrase['dbtech_vbshop_steal_fail_from_x_message'], $vbulletin->userinfo['username']);
		$report = construct_phrase($vbphrase['dbtech_vbshop_steal_fail_report'], $loss['total'], $currency['title']);
	}
	
	if ($vbulletin->options['dbtech_vbshop_enablepm_steal'])
	{
		// Send PM
		$result = VBSHOP::sendPM(
			$existing['userid'],
			$title,
			$message
		);
		if (is_array($result))
		{
			$errstr = '<ol>';
			foreach ($result as $errormsg)
			{
				$errstr .= "<li>$errormsg</li>";
			}
			$errstr .= '</ol>';
			eval(standard_error(fetch_error('dbtech_vbshop_error_x', $errstr)));		
		}
	}
	
	// Add to the navbits
	$navbits[''] = $pagetitle = $vbphrase['dbtech_vbshop_steal'];
	
	$page_templater = vB_Template::create('dbtech_vbshop_steal_report');
		$page_templater->register('pagetitle', 	$pagetitle);
		$page_templater->register('report', 	$report);
	$HTML = $page_templater->render();		
}

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