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

// Add to the navbits
$navbits[''] = $pagetitle = $vbphrase['dbtech_vbshop_purchase_history'];

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

$vbulletin->input->clean_array_gpc('r', array(
	'pagenumber'  	=> TYPE_UINT,
	'perpage'     	=> TYPE_UINT,
));

// Ensure there's no errors or out of bounds with the page variables
if ($vbulletin->GPC['pagenumber'] < 1)
{
	$vbulletin->GPC['pagenumber'] = 1;
}
$pagenumber = $vbulletin->GPC['pagenumber']; // $vbulletin->options['dbtech_vbshout_maxshouts']
$perpage = (!$vbulletin->GPC['perpage'] OR $vbulletin->GPC['perpage'] > 25) ? 25 : $vbulletin->GPC['perpage'];

// Count number of users
$entries = $db->query_first_slave("
	SELECT COUNT(*) AS totalentries
	FROM " . TABLE_PREFIX . "dbtech_vbshop_transactionlog AS transactionlog
	WHERE userid = " . $vbulletin->userinfo['userid'] . " 
		OR recipient = " . $vbulletin->userinfo['userid']
);

// Ensure every result is as it should be
sanitize_pageresults($entries['totalentries'], $pagenumber, $perpage);

// Find out where to start
$startat = ($pagenumber - 1) * $perpage;

// Constructs the page navigation
$pagenav = construct_page_nav(
	$pagenumber,
	$perpage,
	$entries['totalentries'],
	'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . "do=transactionlog",
	"&amp;perpage=$perpage"
);

// Fetch users
$entries_q = $db->query_read_slave("
	SELECT
		transactionlog.*,
		
		buyer.userid AS buyeruserid,
		buyer.username AS buyerusername,
		buyer.usergroupid AS buyerusergroupid,
		buyer.infractiongroupid AS buyerinfractiongroupid,
		buyer.displaygroupid AS buyerdisplaygroupid,
		buyer.dbtech_vbshop_purchase,
		
		recipient.userid AS recipientuserid,
		recipient.username AS recipientusername,
		recipient.usergroupid AS recipientusergroupid,
		recipient.infractiongroupid AS recipientinfractiongroupid,
		recipient.displaygroupid AS recipientdisplaygroupid,
		recipient.dbtech_vbshop_purchase AS recipientpurchase	
	FROM " . TABLE_PREFIX . "dbtech_vbshop_transactionlog AS transactionlog
	LEFT JOIN " . TABLE_PREFIX . "user AS buyer ON (buyer.userid = transactionlog.userid)
	LEFT JOIN " . TABLE_PREFIX . "user AS recipient ON (recipient.userid = transactionlog.recipient)
	WHERE transactionlog.userid = " . $vbulletin->userinfo['userid'] . " 
		OR transactionlog.recipient = " . $vbulletin->userinfo['userid'] . "
	ORDER BY dateline DESC			
	LIMIT $startat, " . $perpage
);

// Store better purchases cache
$purchaseentries = array();

while ($entries_r = $db->fetch_array($entries_q))
{
	// Ensure we have the proper day selected for the grouping
	$day = vbdate($vbulletin->options['dateformat'], $entries_r['dateline']);
	
	$buyer = array(
		'userid' 					=> $entries_r['buyeruserid'],
		'username' 					=> $entries_r['buyerusername'],
		'usergroupid' 				=> $entries_r['buyerusergroupid'],
		'infractiongroupid' 		=> $entries_r['buyerinfractiongroupid'],
		'displaygroupid' 			=> $entries_r['buyerdisplaygroupid'],
	);
	
	$recipient = array(
		'userid' 					=> $entries_r['recipientuserid'],
		'username' 					=> $entries_r['recipientusername'],
		'usergroupid' 				=> $entries_r['recipientusergroupid'],
		'infractiongroupid' 		=> $entries_r['recipientinfractiongroupid'],
		'displaygroupid' 			=> $entries_r['recipientdisplaygroupid'],
		'dbtech_vbshop_purchase' 	=> $entries_r['recipientpurchase'],
	);
	
	$link = 'member.php?' . $vbulletin->session->vars['sessionurl'] . 'u=' . $buyer['userid'] . '&amp;tab=vbshop';
	$link2 = 'member.php?' . $vbulletin->session->vars['sessionurl'] . 'u=' . $recipient['userid'] . '&amp;tab=vbshop';
	
	// Grab musernames
	fetch_musername($buyer);
	fetch_musername($recipient);
	
	$entries_r['info'] = @unserialize($entries_r['info']);
	$entries_r['phrase'] = '';	
	switch ($entries_r['action'])
	{
		case 'purchase':
			$item = (VBSHOP::$cache["{$entries_r[info][feature]}"]["{$entries_r[info][featureid]}"]['title'] ? VBSHOP::$cache["{$entries_r[info][feature]}"]["{$entries_r[info][featureid]}"]['title'] : 'N/A');
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_purchase'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				$item,
				$entries_r['info']['price'],
				VBSHOP::$cache['currency']["{$entries_r[info][currencyid]}"]['title'],
				VBSHOP::$cache['shop']["{$entries_r[info][shopid]}"]['title']
			);
			break;
			
		case 'donate':
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_donate'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				$entries_r['info']['amount'],
				VBSHOP::$cache['currency']["{$entries_r[info][currencyid]}"]['title'],
				'<a href="' . $link2 . '">' . $recipient['musername'] . '</a>'
			);
			break;
			
		case 'stealsuccess':
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_stealsuccess'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				vb_number_format($entries_r['info']['gain']['total'], VBSHOP::$cache['currency']["{$entries_r[info][currencyid]}"]['rounding']),
				VBSHOP::$cache['currency']["{$entries_r[info][currencyid]}"]['title'],
				'<a href="' . $link2 . '">' . $recipient['musername'] . '</a>'
			);
			break;
			
		case 'stealfail':
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_stealfail'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				vb_number_format($entries_r['info']['loss']['total'], VBSHOP::$cache['currency']["{$entries_r[info][currencyid]}"]['rounding']),
				VBSHOP::$cache['currency']["{$entries_r[info][currencyid]}"]['title'],
				'<a href="' . $link2 . '">' . $recipient['musername'] . '</a>'
			);			
			break;
			
		case 'deposit':
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_deposit'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				$entries_r['info']['amount'],
				VBSHOP::$cache['currency']["{$entries_r[info][currencyid]}"]['title']
			);			
			break;
			
		case 'withdraw':
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_withdraw'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				$entries_r['info']['amount'],
				VBSHOP::$cache['currency']["{$entries_r[info][currencyid]}"]['title']
			);			
			break;
			
		case 'interest':
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_interest'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				$entries_r['info']['amount'],
				VBSHOP::$cache['currency']["{$entries_r[info][currencyid]}"]['title']
			);			
			break;
			
		case 'discard':
			$item = (VBSHOP::$cache["{$entries_r[info][feature]}"]["{$entries_r[info][featureid]}"]['title'] ? VBSHOP::$cache["{$entries_r[info][feature]}"]["{$entries_r[info][featureid]}"]['title'] : 'N/A');
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_discard'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				$item,
				VBSHOP::$cache['shop']["{$entries_r[info][shopid]}"]['title']
			);
			break;
			
		case 'gift':
			$item = (VBSHOP::$cache["{$entries_r[info][feature]}"]["{$entries_r[info][featureid]}"]['title'] ? VBSHOP::$cache["{$entries_r[info][feature]}"]["{$entries_r[info][featureid]}"]['title'] : 'N/A');
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_gift'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				$item,
				'<a href="' . $link2 . '">' . $recipient['musername'] . '</a>',
				$entries_r['info']['message']
			);
			break;
			
		case 'sale':
			$item = (VBSHOP::$cache["{$entries_r[info][feature]}"]["{$entries_r[info][featureid]}"]['title'] ? VBSHOP::$cache["{$entries_r[info][feature]}"]["{$entries_r[info][featureid]}"]['title'] : 'N/A');
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_sale'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				$item,
				$entries_r['info']['price'],
				VBSHOP::$cache['currency']["{$entries_r[info][currencyid]}"]['title'],
				VBSHOP::$cache['shop']["{$entries_r[info][shopid]}"]['title'],
				'<a href="' . $link2 . '">' . $recipient['musername'] . '</a>'
			);
			break;
			
		case 'sellback':
			$item = (VBSHOP::$cache["{$entries_r[info][feature]}"]["{$entries_r[info][featureid]}"]['title'] ? VBSHOP::$cache["{$entries_r[info][feature]}"]["{$entries_r[info][featureid]}"]['title'] : 'N/A');
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_sellback'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				$item,
				$entries_r['info']['price'],
				VBSHOP::$cache['currency']["{$entries_r[info][currencyid]}"]['title'],
				VBSHOP::$cache['shop']["{$entries_r[info][shopid]}"]['title']
			);
			break;
			
		case 'perreply':
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_perreply'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				$entries_r['info']['amount'],
				VBSHOP::$cache['currency']["{$entries_r[info][currencyid]}"]['title'],
				'<a href="showpost.php?' . $vbulletin->session->vars['sessionurl'] . 'p=' . $entries_r['info']['postid'] . '">' . $entries_r['info']['postid'] . '</a>'
			);			
			break;
			
		case 'perthread':
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_perthread'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				$entries_r['info']['amount'],
				VBSHOP::$cache['currency']["{$entries_r[info][currencyid]}"]['title'],
				'<a href="showthread.php?' . $vbulletin->session->vars['sessionurl'] . 't=' . $entries_r['info']['threadid'] . '">' . $entries_r['info']['threadid'] . '</a>'
			);			
			break;
			
		case 'lotteryticket':
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_lotteryticket'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				$entries_r['info']['price'],
				VBSHOP::$cache['currency'][$entries_r['info']['currencyid']]['title'],
				'<a href="vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=lottery&amp;action=view&amp;lotteryid=' . $entries_r['info']['lotteryid'] . '">' . VBSHOP::$cache['lottery'][$entries_r['info']['lotteryid']]['title'] . '</a>'
			);			
			break;
			
		case 'lotteryprize':
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_lotteryprize'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>',
				$entries_r['info']['winnings'],
				VBSHOP::$cache['currency'][$entries_r['info']['currencyid']]['title'],
				'<a href="vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=lottery&amp;action=view&amp;lotteryid=' . $entries_r['info']['lotteryid'] . '">' . VBSHOP::$cache['lottery'][$entries_r['info']['lotteryid']]['title'] . '</a>',
				'<b>' . VBSHOP::$cache['lotteryprize'][$entries_r['info']['prizeid']]['title'] . '</b>'
			);			
			break;
			
		case 'pointsadjust':
			$entries_r['phrase'] = construct_phrase($vbphrase['dbtech_vbshop_transactionlog_pointsadjust'],
				'<a href="' . $link2 . '">' . $recipient['musername'] . '</a>',			
				$entries_r['info']['amount'],
				VBSHOP::$cache['currency']["{$entries_r[info][currencyid]}"]['title'],
				'<a href="' . $link . '">' . $buyer['musername'] . '</a>'				
			);			
			break;
	}
	
	/*
	if ($entries_r['buyer'] == $vbulletin->userinfo['userid'])
	{
		if ($entries_r['userid'] == $vbulletin->userinfo['userid'])
		{
			$entries_r['phrase'] = construct_phrase(
				$vbphrase['dbtech_vbshop_item_x_purchased_y'],
				VBSHOP::$cache["$entries_r[feature]"]["$entries_r[featureid]"]['title'],
				vbdate($vbulletin->options['timeformat'], $entries_r['dateline'])
			);
		}
		else
		{
			$entries_r['phrase'] = construct_phrase(
				$vbphrase['dbtech_vbshop_item_x_purchased_for_y'],
				VBSHOP::$cache["$entries_r[feature]"]["$entries_r[featureid]"]['title'],
				$recipient['username'],			
				vbdate($vbulletin->options['timeformat'], $entries_r['dateline'])
			);
		}
	}
	else
	{
		$entries_r['phrase'] = construct_phrase(
			$vbphrase['dbtech_vbshop_item_x_received_y_from_x'],
			VBSHOP::$cache["$entries_r[feature]"]["$entries_r[featureid]"]['title'],
			$buyer['username'],			
			vbdate($vbulletin->options['timeformat'], $entries_r['dateline'])
		);					
	}
	*/
	
	// Add the entry to the list, grouped by day
	$purchaseentries["$day"]["$entries_r[transactionlogid]"] = $entries_r;
}

$entrybits = '';
foreach ($purchaseentries as $day => $entries)
{
	$entrybitbits = '';
	foreach ($entries as $entry)
	{
		$entry['dateline'] = vbdate($vbulletin->options['timeformat'], $entry['dateline']);
		
		$templaterr = vB_Template::create('dbtech_vbshop_entrybit');
			$templaterr->register('entry', $entry);
		$entrybitbits .= $templaterr->render();
	}
	
	$templater = vB_Template::create('dbtech_vbshop_daybit');
		$templater->register('day', $day);
		$templater->register('entrybits', $entrybitbits);				
	$entrybits .= $templater->render();
}

// Create the archive template
$templater = vB_Template::create('dbtech_vbshop_transactionlog');
	$templater->register('pagetitle', 	$pagetitle);
	$templater->register('pagenav', 	$pagenav);
	$templater->register('pagenumber', 	$pagenumber);
	$templater->register('perpage', 	$perpage);
	$templater->register('history', 	$entrybits);
$HTML = $templater->render();