<?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_bank_enabled'] OR
	!VBSHOP::$permissions['canbank']
)
{
	// No permission to use bank
	print_no_permission();
}

// #############################################################################
if ($_REQUEST['action'] == 'bank' OR empty($_REQUEST['action']))
{
	$bankamounts = array();
	$lastinterest = 0;
	$bankamounts_q = $db->query_read_slave("
		SELECT *
		FROM " . TABLE_PREFIX . "dbtech_vbshop_bank
		WHERE userid = " . $db->sql_prepare($vbulletin->userinfo['userid'])
	);
	while ($bankamounts_r = $db->fetch_array($bankamounts_q))
	{
		$bankamounts[$bankamounts_r['currencyid']] = $bankamounts_r['points'];
		$lastinterest = ($lastinterest > $bankamounts_r['lastinterest'] ? $lastinterest : $bankamounts_r['lastinterest']);
	}	
	
	// Add to the navbits
	$navbits[''] = $pagetitle = $vbphrase['dbtech_vbshop_bank'];
	
	$currencies = '';
	foreach (VBSHOP::$cache['currency'] as $currencyid => $currency)
	{
		if (!$currency['active'])
		{
			// Can't bank this
			continue;
		}
		
		if (!$currency['canbank'])
		{
			// Can't bank this
			continue;
		}
		
		if (!isset($bankamounts[$currencyid]))
		{
			$db->query_write("
				INSERT IGNORE INTO " . TABLE_PREFIX . "dbtech_vbshop_bank
					(userid, currencyid, points)
				VALUES (
					" . $db->sql_prepare($vbulletin->userinfo['userid']) . ",
					" . $db->sql_prepare($currencyid) . ",
					'0'					
				)
			");
		}
		
		// Ensure this is set
		$currency['stealprotect'] 	= ($currency['stealprotect'] > -1 ? $currency['stealprotect'] : $vbphrase['all']);
		$currency['points'] 		= vb_number_format($bankamounts[$currencyid]);
		
		// Create the archive template
		$templater = vB_Template::create('dbtech_vbshop_bank_currencybit');
			$templater->register('currency', 	$currency);
		$currencies .= $templater->render();	
	}
	
	if (VBSHOP::$isPro AND $vbulletin->options['dbtech_vbshop_manualinterest'])
	{
		if (($lastinterest + 86400) <= TIMENOW)
		{
			$show['collectinterest'] = $vbphrase['dbtech_vbshop_collect_interest'];
		}
		else
		{
			// Handle time remaining
			$remainingtime = VBSHOP::getTimeBreakdown(($lastinterest + 86400) - TIMENOW);
			$show['collectinterest'] = construct_phrase($vbphrase['dbtech_vbshop_collect_interest_x_hours_y_minutes_s_seconds'], $remainingtime['hours'], $remainingtime['minutes'], $remainingtime['seconds']);
			$disabled = ' disabled="disabled" style="color:graytext;"';
		}
	}

	// Create the archive template
	$page_templater = vB_Template::create('dbtech_vbshop_bank');
		$page_templater->register('pagetitle', 	$pagetitle);
		$page_templater->register('currencies', $currencies);
		$page_templater->register('disabled', 	$disabled);
	$HTML = $page_templater->render();	
}


// #############################################################################
if ($_REQUEST['action'] == 'interest' AND VBSHOP::$isPro)
{
	$lastinterest = 0;
	$lastinterest = 0;
	$bankamounts_q = $db->query_read_slave("
		SELECT *
		FROM " . TABLE_PREFIX . "dbtech_vbshop_bank
		WHERE userid = " . $db->sql_prepare($vbulletin->userinfo['userid'])
	);
	while ($bankamounts_r = $db->fetch_array($bankamounts_q))
	{
		$lastinterest = ($lastinterest > $bankamounts_r['lastinterest'] ? $lastinterest : $bankamounts_r['lastinterest']);
	}	
	
	if (!$vbulletin->options['dbtech_vbshop_manualinterest'])
	{
		// Throw error from invalid action
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_invalid_action'])));
	}
	
	if (($lastinterest + 86400) > TIMENOW)
	{
		// Throw error
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_cannot_collect_interest'])));
	}
	
	$users = $vbulletin->db->query_read_slave("
		SELECT *
		FROM " . TABLE_PREFIX . "dbtech_vbshop_bank
		WHERE points > 0
			AND userid = " . intval($vbulletin->userinfo['userid']) . "
	");
	while ($user = $vbulletin->db->fetch_array($users))
	{
		$interest = doubleval(VBSHOP::$cache['currency'][$user['currencyid']]['interest']);
		if ($interest == 0)
		{
			// Not yielding any interest
			continue;
		}
		
		// Convert to multiplicable values
		$interest = ($interest / 100);
		
		$info = array(
			'currencyid' 	=> $user['currencyid'],
			'amount' 		=> round($user['points'] * $interest, 2),
		);
		
		// init data manager
		$dm =& VBSHOP::initDataManager('Transactionlog', $vbulletin, ERRTYPE_ARRAY);
			$dm->set('userid', 		$user['userid']);
			$dm->set('recipient', 	$user['userid']);
			$dm->set('ipaddress', 	IPADDRESS);
			$dm->set('action', 		'interest');
			$dm->set('info', 		$info);
		$dm->save();
		unset($dm);	
	}

	foreach (VBSHOP::$cache['currency'] as $currencyid => $currency)
	{
		$interest = doubleval($currency['interest']);
		if ($interest == 0)
		{
			// Not yielding any interest
			continue;
		}
		
		// Convert to multiplicable values
		$interest = 1 + ($interest / 100);
	
		// Update database
		$vbulletin->db->query_write("
			UPDATE " . TABLE_PREFIX . "dbtech_vbshop_bank
			SET 
				points = ROUND(points * $interest, 2),
				lastinterest = " . intval(TIMENOW) . "
			WHERE points > 0
				AND currencyid = $currencyid
				AND userid = " . intval($vbulletin->userinfo['userid']) . "
		");
	}
	
	// Success phrase
	$vbulletin->url = 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=bank';
	eval(print_standard_redirect('redirect_dbtech_vbshop_updatethanks'));
}

// #############################################################################
if ($_POST['action'] == 'manage')
{
	$vbulletin->input->clean_array_gpc('p', array(
		'deposit' 	=> TYPE_ARRAY_UNUM,
		'withdraw' 	=> TYPE_ARRAY_UNUM,
	));
	
	foreach (VBSHOP::$cache['currency'] as $currencyid => $currency)
	{
		if (!$currency['active'])
		{
			// Can't bank this
			continue;
		}
		
		if (!$currency['canbank'])
		{
			// Can't bank this
			continue;
		}
		
		if (!$vbulletin->GPC['deposit'][$currencyid] AND !$vbulletin->GPC['withdraw'][$currencyid])
		{
			// Not doing anything with this currency
			continue;
		}
		
		if ($vbulletin->GPC['deposit'][$currencyid])
		{
			// Check how many points we have
			$userpoints = $db->query_first_slave("
				SELECT " . $currency['pointscolumn'] . " AS points
				FROM " . TABLE_PREFIX . $currency['pointstable'] . "
				WHERE userid = " . $db->sql_prepare($vbulletin->userinfo['userid']) . "
			");
			
			// Ensure we're not trying to deposit more than we have
			$vbulletin->GPC['deposit'][$currencyid] = ($vbulletin->GPC['deposit'][$currencyid] > $userpoints['points'] ? $userpoints['points'] : $vbulletin->GPC['deposit'][$currencyid]);
			
			// Update the bank
			$db->query_write("
				UPDATE " . TABLE_PREFIX . "dbtech_vbshop_bank
				SET points = points + '" . doubleval($vbulletin->GPC['deposit'][$currencyid]) . "'
				WHERE userid = " . $db->sql_prepare($vbulletin->userinfo['userid']) . "
					AND currencyid = " . intval($currencyid)
			);
			
			// Update the points table
			$db->query_write("
				UPDATE " . TABLE_PREFIX . $currency['pointstable'] . "
				SET " . $currency['pointscolumn'] . " = " . $currency['pointscolumn'] . " - '" . doubleval($vbulletin->GPC['deposit'][$currencyid]) . "'
				WHERE userid = " . $db->sql_prepare($vbulletin->userinfo['userid'])
			);
			
			$info = array(
				'currencyid' 	=> $currencyid,
				'amount' 		=> doubleval($vbulletin->GPC['deposit'][$currencyid]),
			);
						
			// 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', 		'deposit');
				$dm->set('info', 		$info);
			$dm->save();
			unset($dm);			
		}
		
		if ($vbulletin->GPC['withdraw'][$currencyid])
		{
			// Check how many points we have
			$userpoints = $db->query_first_slave("
				SELECT points
				FROM " . TABLE_PREFIX . "dbtech_vbshop_bank
				WHERE userid = " . $db->sql_prepare($vbulletin->userinfo['userid']) . "
					AND currencyid = " . intval($currencyid)
			);
			
			// Ensure we're not trying to deposit more than we have
			$vbulletin->GPC['withdraw'][$currencyid] = ($vbulletin->GPC['withdraw'][$currencyid] > $userpoints['points'] ? $userpoints['points'] : $vbulletin->GPC['withdraw'][$currencyid]);
			
			// Update the bank
			$db->query_write("
				UPDATE " . TABLE_PREFIX . "dbtech_vbshop_bank
				SET points = points - '" . doubleval($vbulletin->GPC['withdraw'][$currencyid]) . "'
				WHERE userid = " . $db->sql_prepare($vbulletin->userinfo['userid']) . "
					AND currencyid = " . intval($currencyid)
			);
			
			// Update the points table
			$db->query_write("
				UPDATE " . TABLE_PREFIX . $currency['pointstable'] . "
				SET " . $currency['pointscolumn'] . " = " . $currency['pointscolumn'] . " + '" . doubleval($vbulletin->GPC['withdraw'][$currencyid]) . "'
				WHERE userid = " . $db->sql_prepare($vbulletin->userinfo['userid'])
			);
			
			$info = array(
				'currencyid' 	=> $currencyid,
				'amount' 		=> doubleval($vbulletin->GPC['withdraw'][$currencyid]),
			);

			// 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', 		'withdraw');
				$dm->set('info', 		$info);
			$dm->save();
			unset($dm);			
		}
	}
	
	// Success phrase
	$vbulletin->url = 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=bank';
	eval(print_standard_redirect('redirect_dbtech_vbshop_updatethanks'));
}

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