<?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 ############################
// #######################################################################

// Grab shopping cart
$shoppingcart = ($vbulletin->userinfo['userid'] ? VBSHOP::$db->fetchRow('
	SELECT *
	FROM $dbtech_vbshop_shoppingcart
	WHERE userid = ?
', array($vbulletin->userinfo['userid'])) : array());

// Ensure this is array
$shoppingcart = (is_array($shoppingcart) ? $shoppingcart : array());

// Fetch list of items
$shoppingcart['items'] = (strlen($shoppingcart['items']) ? @unserialize($shoppingcart['items']) : array());

// #############################################################################
if ($_REQUEST['action'] == 'shop' OR empty($_REQUEST['action']))
{
	// Add to the navbits
	$navbits[''] = $pagetitle = $vbphrase['dbtech_vbshop_shop'];
	
	$vbulletin->input->clean_array_gpc('r', array(
		'shopid'  	  	=> TYPE_UINT,
		'pagenumber'  	=> TYPE_UINT,
		'tab'         	=> TYPE_NOHTML,
		'perpage'     	=> TYPE_UINT,
		'sorttype'    	=> TYPE_STR,
		'sortorder'   	=> TYPE_STR,
		'isajax'   		=> TYPE_BOOL,
	));

	// 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'];
	$perpage 	= (!$vbulletin->GPC['perpage']) ? 25 : $vbulletin->GPC['perpage'];
	$perpage 	= $vbulletin->GPC['perpage'] 	= ($perpage > 250) ? 250 : $perpage;
	$sortorder 	= $vbulletin->GPC['sortorder'] 	= (!in_array(strtolower($vbulletin->GPC['sortorder']), array('asc', 'desc')) ? 'asc' : strtolower($vbulletin->GPC['sortorder']));
	
	// Shorthands to faciliate easy copypaste
	$reverseorder = ($sortorder == 'asc' ? 'desc' : 'asc');
	
	switch ($vbulletin->GPC['sorttype'])
	{
		case 'popularity':
			$sorttype = $vbulletin->GPC['sorttype'] = 'popularity';
			$sqlsort = 'item.purchases';
			break;
			
		case 'price':
			$sorttype = $vbulletin->GPC['sorttype'] = 'price';
			$sqlsort = 'shopinventory.price';
			break;
		
		case 'title':
			$sorttype = $vbulletin->GPC['sorttype'] = 'title';
			$sqlsort = 'item.title';
			break;
		
		default:
			$sorttype = $vbulletin->GPC['sorttype'] = 'default';
			$sqlsort = 'item.displayorder';
			break;
	}
	
	// Store item ids
	$itemids = array();
	foreach ((array)$shoppingcart['items'] as $shopid => $items)
	{
		foreach ($items as $itemid => $quantity)
		{
			if (!$item = VBSHOP::$cache['item'][$itemid])
			{
				// This no longer exists
				continue;
			}

			if (!$item['active'])
			{
				// Skip this
				continue;
			}

			// Store the itemid
			$itemids[] = $itemid;
		}
	}
	
	// Set this
	$userinfo = $vbulletin->userinfo;
	
	if (count($itemids))
	{
		// Store item info
		$iteminfo = array();
		$iteminfo_q = VBSHOP::$db->fetchAll('
			SELECT *		
			FROM $dbtech_vbshop_shopinventory
			WHERE itemid :itemIds
				AND active = 1
		', array(
			':itemIds' => VBSHOP::$db->queryList($itemids)
		));
		foreach ($iteminfo_q as $iteminfo_r)
		{
			// Index by shopid and itemid
			$iteminfo[$iteminfo_r['shopid']][$iteminfo_r['itemid']] = $iteminfo_r;
		}
		
		$cartitems = '';
		$totalprices = array();
		foreach ((array)$shoppingcart['items'] as $shopid => $items)
		{
			foreach ($items as $itemid => $quantity)
			{
				if (!$currency = VBSHOP::$cache['currency'][$iteminfo[$shopid][$itemid]['currencyid']])
				{
					// This currency doesn't exist anymore
					continue;
				}
				
				if (!$item = VBSHOP::$cache['item'][$itemid])
				{
					// This no longer exists
					continue;
				}

				if (!$item['active'])
				{
					// Skip this
					continue;
				}
				
				if (!is_array($iteminfo[$shopid][$itemid]))
				{
					// This no longer exists
					continue;
				}

				// Store total prices
				$totalprices[$currency['currencyid']] += ($iteminfo[$shopid][$itemid]['price'] * $quantity);
				
				 // Ensure this is set
				$iteminfo[$shopid][$itemid]['currency'] = $currency['title'];
				$iteminfo[$shopid][$itemid]['quantity'] = $quantity;
								
				// Decrement our available points
				$userinfo[$currency['pointscolumn']] -= ($iteminfo[$shopid][$itemid]['price'] * $quantity);
				
				$templater = vB_Template::create('dbtech_vbshop_cartitems_item');
					$templater->register('item', array_merge(VBSHOP::$cache['item'][$itemid], $iteminfo[$shopid][$itemid]));
					$templater->register('price', ($iteminfo[$shopid][$itemid]['price'] * $quantity));
				$cartitems .= $templater->render();
			}
		}	
	}
	
	// Create the cartitems list
	$templater = vB_Template::create('dbtech_vbshop_cartitems');
		$templater->register('items', $cartitems);
	$cartitems = $templater->render();
	
	if (is_array($totalprices))
	{
		foreach ($totalprices as $currencyid => $totalcost)
		{
			// Update the total cost
			$totalprices[$currencyid] = $totalcost . ' ' . VBSHOP::$cache['currency'][$currencyid]['title'];
		}
		
		// Finally set the string
		$totalprice = implode('<br />', $totalprices);
	}
	else
	{
		// Cart was empty
		$totalprice = 'N/A';
	}
	$discount = 0;
	
	// Store list of userids to lookup
	$userids = array(0 => 0);
	foreach ((array)VBSHOP::$cache['shop'] as $shopid => $shop)
	{
		if (!$shop['active'])
		{
			// Inactive shop
			continue;
		}
		
		if (isset($userids[$shop['ownerid']]))
		{
			// Ignore this
			continue;
		}
		$userids[$shop['ownerid']] = $shop['ownerid'];
		
		if (isset($userids[$shop['latestcustomer']]))
		{
			// Ignore this
			continue;
		}
		$userids[$shop['latestcustomer']] = $shop['latestcustomer'];		
	}
	foreach ((array)VBSHOP::$cache['item'] as $itemid => $item)
	{
		if (!$item['active'])
		{
			// This item isn't to be displayed
			continue;
		}

		if (!$category = VBSHOP::$cache['category'][$item['categoryid']])
		{
			// This category isn't to be displayed
			continue;
		}
		
		if (!$category['active'])
		{
			// This category isn't to be displayed
			continue;
		}
		
		if (!VBSHOP::checkPermissions($vbulletin->userinfo, $item['permissions']))
		{
			// This item isn't to be displayed
			continue;
		}
		
		if (!VBSHOP::checkPermissions($vbulletin->userinfo, $category['permissions']))
		{
			// This category isn't to be displayed
			continue;
		}
		
		if (isset($userids[$item['ownerid']]))
		{
			// Ignore this
			continue;
		}
		
		if (!$item['ownerid'])
		{
			// Skip this
			continue;
		}
		
		$userids[$item['ownerid']] = $item['ownerid'];
	}
	unset($userids[0]);
	
	if (count($userids) > 0)
	{
		$usernames = VBSHOP::$db->fetchAllKeyed('
			SELECT *
			FROM $user
			WHERE userid :queryList
		', 'userid', array(
			':queryList' => VBSHOP::$db->queryList($userids)
		));
		foreach ($usernames as $username)
		{
			// Grab the markup username
			fetch_musername($username);
			
			// Store this in the lookup
			$userids[$username['userid']] = $username['musername'];
		}
	}
	
	$shops = array();
	$vbulletin->GPC['shopid'] = (!VBSHOP::checkPermissions($vbulletin->userinfo, VBSHOP::$cache['shop'][$vbulletin->GPC['shopid']]['permissions']) ? 0 : $vbulletin->GPC['shopid']);
	foreach ((array)VBSHOP::$cache['shop'] as $shopid => $shop)
	{
		if (!$shop['active'])
		{
			// Inactive shop
			continue;
		}
		
		if (!VBSHOP::checkPermissions($vbulletin->userinfo, $shop['permissions']))
		{
			// This isn't to be displayed
			continue;
		}
		
		$shop['title'] 				= htmlspecialchars_uni($shop['title']);
		$shop['description'] 		= htmlspecialchars_uni($shop['description']);
		$shop['sales'] 				= ($shop['sales'] 			? vb_number_format($shop['sales']) 							: 'N/A');
		$shop['latestsale'] 		= ($shop['latestsale'] 		? VBSHOP::$cache['item'][$shop['latestsale']]['title'] 		: 'N/A');
		$shop['latestcustomer'] 	= ($shop['latestcustomer'] 	? $userids[$shop['latestcustomer']] 						: 'N/A');
		$shop['owner'] 				= ($shop['ownerid'] 		? $userids[$shop['ownerid']] 								: 'N/A');
		$shop['description'] 		= (nl2br($shop['description']));
		$shop['canhavefeedback'] 	= ($vbulletin->options['dbtech_vbshop_enable_feedback'] ? $shop['canhavefeedback'] 		: false);
		
		// Ensure this is set
		$shop['logo'] = ($shop['logo'] ? $shop['logo'] : $vbulletin->options['bburl'] . '/dbtech/vbshop/images/unknown_shop.gif');
		
		// Do the currency bits
		$shop['currencybits'] = '';
		foreach ((array)$shop['salesamounts'] as $currencyid => $amount)
		{
			if (!VBSHOP::$cache['currency'][$currencyid])
			{
				// Ignore this
				continue;
			}
						
			// Do currencybits bits
			$templater = vB_Template::create('dbtech_vbshop_shop_currencybit');
				$templater->register('currency', VBSHOP::$cache['currency'][$currencyid]['title']);
				$templater->register('amount', vb_number_format($amount));
			$shop['currencybits'] .= $templater->render();
		}

		// Set this
		$shop['averagerating_rounded'] = floor($shop['averagerating']);

		// Do shop bits
		$templater = vB_Template::create('dbtech_vbshop_shop_shopbit');
			$templater->register('shop', $shop);
		$shops[] = $templater->render();
		
		// Select first shop
		$vbulletin->GPC['shopid'] = ($vbulletin->GPC['shopid'] != 0 ? $vbulletin->GPC['shopid'] : $shopid);
	}

	// Fetch users
	$items = VBSHOP::$db->fetchAllSingleKeyed('
		SELECT itemid		
		FROM $dbtech_vbshop_shopinventory
		WHERE shopid = ?
			AND active = 1
	', 'itemid', 'itemid', array(
		$vbulletin->GPC['shopid']
	));	
	
	$itemIds = array();
	foreach (VBSHOP::$cache['item'] as $itemid => $item)
	{
		if (!$item['active'])
		{
			// This item isn't to be displayed
			continue;
		}

		if (!$category = VBSHOP::$cache['category'][$item['categoryid']])
		{
			// This category isn't to be displayed
			continue;
		}
		
		if (!$category['active'])
		{
			// This category isn't to be displayed
			continue;
		}
		
		if (!VBSHOP::checkPermissions($vbulletin->userinfo, $item['permissions']))
		{
			// This item isn't to be displayed
			continue;
		}
		
		if (!VBSHOP::checkPermissions($vbulletin->userinfo, $category['permissions']))
		{
			// This category isn't to be displayed
			continue;
		}
		
		if (!isset($items[$itemid]))
		{
			// Not displaying in this shop
			continue;
		}
		
		// Get all possible itemids
		$itemIds[] = $itemid;
	}

	if (count($itemIds))
	{		
		$itemsByCategory = array();
		foreach ($itemIds as $itemid)
		{
			// Shorthand
			$item 		= VBSHOP::$cache['item'][$itemid];
			$category 	= VBSHOP::$cache['category'][$item['categoryid']];

			if (!isset($itemsByCategory[$category['categoryid']]))
			{
				// Ensure this is init'd
				$itemsByCategory[$category['categoryid']] = array();
			}

			//$currentCount = count($itemsByCategory[$category['categoryid']]);
			//if ($currentCount == $startat OR $currentCount < ($startat + $perpage))
			//{
				// Include this item ID in this page
				$itemsByCategory[$category['categoryid']][] = $itemid; 
			//}
		}

		// Count number of users
		$counter['total'] = 0;

		foreach ($itemsByCategory as $categoryid => $items)
		{
			$itemCount = count($items);
			if ($itemCount > $counter['total'])
			{
				// Set the new total count
				$counter['total'] = $itemCount;
			}
		}
		
		// Ensure every result is as it should be
		sanitize_pageresults($counter['total'], $pagenumber, $perpage, 250, 25);
		
		// Find out where to start
		$startat = ($pagenumber - 1) * $perpage;
		
		// Constructs the page navigation
		$pagenav = construct_page_nav(
			$pagenumber,
			$perpage,
			$counter['total'],
			'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . "do=shop",
			"&amp;shopid=" . $vbulletin->GPC['shopid'] . "&amp;perpage=$perpage&amp;sortorder=$sortorder&amp;sorttype=$sorttype"
		);

		// Begin the sorting array
		$items_by_category = array();
		
		$SQL = array();
		foreach (VBSHOP::$cache['category'] as $categoryid => $category)
		{
			if (!$category = VBSHOP::$cache['category'][$item['categoryid']])
			{
				// This category isn't to be displayed
				continue;
			}
			
			if (!$category['active'])
			{
				// This category isn't to be displayed
				continue;
			}

			if (empty($itemsByCategory[$categoryid]))
			{
				// Error prevention
				continue;
			}

			if (count($itemsByCategory[$categoryid]) < $startat)
			{
				// We've not got enough items to show this category now
				continue;
			}

			// Ensure this uses the correct display order
			$items_by_category[$categoryid] = array();

			$SQL[] = '
				SELECT item.itemid, item.categoryid, shopinventory.*
				FROM $dbtech_vbshop_shopinventory AS shopinventory
				LEFT JOIN $dbtech_vbshop_item AS item ON(item.itemid = shopinventory.itemid)
				WHERE shopinventory.itemid IN(' . implode(',', $itemsByCategory[$categoryid]) . ')
					AND shopinventory.active = \'1\'
					AND item.categoryid = ' . $categoryid . '
				ORDER BY :sqlsort :sqlorder
				LIMIT :limitStart, :limitEnd
			';
		}
		
		if (count($SQL))
		{
			// Fetch users
			$items_q = VBSHOP::$db->fetchAll('(' . implode(') UNION ALL (', $SQL) . ')', array(
				':itemIds' 		=> VBSHOP::$db->queryList($itemIds),
				':sqlsort' 		=> $sqlsort,
				':sqlorder' 	=> $sortorder,
				':limitStart' 	=> $startat,
				':limitEnd' 	=> $perpage
			));
			foreach ($items_q as $items_r)
			{
				// Store the category array
				$items_by_category[$items_r['categoryid']][$items_r['itemid']][$items_r['shopid']] = $items_r;
			}
		}

		$firstValidCat = 0;
		foreach ($items_by_category as $categoryid => $itemlist)
		{
			if (!count($itemlist))
			{
				// Don't need this showing up
				continue;
			}
			
			// Set this for later
			$firstValidCat = ($firstValidCat ? $firstValidCat : $categoryid);
		}		
		
		if (!empty($vbulletin->GPC['tab']) AND isset($items_by_category[$vbulletin->GPC['tab']]))
		{
			$selected_tab = $vbulletin->GPC['tab'];
		}
		else
		{
			$selected_tab = $vbulletin->GPC['tab'] = $firstValidCat;
		}

		$purchases = VBSHOP::$db->fetchAllSingleKeyed('
			SELECT featureid
			FROM $dbtech_vbshop_purchase
			WHERE feature = ?
				AND userid = ?
		', 'featureid', 'featureid', array(
			'item',
			$vbulletin->userinfo['userid'],
		));
		
		// Store item ids
		foreach ((array)$shoppingcart['items'] as $shopid => $items)
		{
			foreach ($items as $itemid => $quantity)
			{
				// Store the itemid
				$purchases[$itemid] = true;
			}
		}
		
		$firsttab = true;
		$tabbits = '';
		$tabcontent = '';
		foreach ($items_by_category as $categoryid => $itemlist)
		{
			if (!count($itemlist))
			{
				// Don't need this showing up
				continue;
			}
			
			// Shorthand
			$category = VBSHOP::$cache['category'][$categoryid];
			
			$items = '';
			foreach ($itemlist as $itemid => $shopids)
			{
				foreach ($shopids as $shopid => $iteminfo)
				{
					// Grab the item
					if (!$item = VBSHOP::$cache['item'][$itemid])
					{
						// Dunno why this would happen but meh
						continue;
					}
					
					// Merge these
					$item = array_merge($item, $iteminfo);
					
					// Init this
					$disabled = '';
					
					if (!VBSHOP::check_price($item, $userinfo))
					{
						// Couldn't afford
						$disabled = $vbphrase['dbtech_vbshop_insufficient_funds'];
					}
					
					if ($item['stock'] == 0)
					{
						// Out of stock
						$disabled = $vbphrase['dbtech_vbshop_out_of_stock'];
					}
					
					if ($item['uniqueitem'] AND $purchases[$itemid])
					{
						// Already bought it
						$disabled = $vbphrase['dbtech_vbshop_already_owned_bought'];
					}
					
					// Ensure this is set
					$item['icon'] 		= ($item['icon'] 		? $item['icon'] 	: 'unknown.gif');
					$item['shopicon'] 	= ($item['shopicon'] 	? $item['shopicon'] : 'unknown_shop.gif');
					
					if ($shopid == $vbulletin->GPC['shopid'])
					{
						 // Ensure this is set
						$item['currency'] 		= VBSHOP::$cache['currency'][$item['currencyid']]['title'];
						$item['owner'] 			= ($item['ownerid'] 	? $userids[$item['ownerid']] 	: 'N/A');				
						$item['giftable'] 		= ($item['giftable'] 	? $vbphrase['yes'] 				: $vbphrase['no']);				
						$item['unique'] 		= ($item['uniqueitem'] 	? $vbphrase['yes'] 				: $vbphrase['no']);				
						$item['duration'] 		= ($item['duration'] 	? $item['duration'] 			: $vbphrase['unlimited']);				
						$item['buybacktime'] 	= ($item['buybacktime'] ? $item['buybacktime'] 			: $vbphrase['unlimited']);				
						$item['maxstock'] 		= ($item['stock'] > -1 	? $item['maxstock'] 			: $vbphrase['unlimited']);				
						$item['stock'] 			= ($item['stock'] > -1 	? $item['stock'] 				: $vbphrase['unlimited']);	
						$item['maxstock'] 		= ($item['stock'] 		? $item['maxstock'] 			: 0);						
						$item['description'] 	= nl2br(htmlspecialchars_uni($item['description']));

						// Do item bits only if it's in the currently viewing shop
						$templater = vB_Template::create('dbtech_vbshop_itembit_shop');
							$templater->register('item', 		$item);
							$templater->register('currency', 	VBSHOP::$cache['currency'][$item['currencyid']]);
							$templater->register('disabled', 	$disabled);
						$items .= $templater->render();

						// Do item bits only if it's in the currently viewing shop
						$templater = vB_Template::create('dbtech_vbshop_itempopup');
							$templater->register('item', 		$item);
						$items .= $templater->render();
					}				
				}
			}
			
			if (!$items)
			{
				// We don't need this
				continue;
			}
			
			$templater = vB_Template::create('dbtech_vbshop_tabbit');
				$templater->register('firsttab', 		$firsttab);
				$templater->register('selected_tab', 	$selected_tab);			
				$templater->register('category', 		$category);
			$tabbits .= $templater->render();
			
			$templater = vB_Template::create('dbtech_vbshop_tabcontent');
				$templater->register('firsttab', 		$firsttab);
				$templater->register('selected_tab', 	$selected_tab);			
				$templater->register('category', 		$category);
				$templater->register('items', 			$items);
			$tabcontent .= $templater->render();
			$firsttab = false;
		}
		
		// Do shop bits
		$templater = vB_Template::create('dbtech_vbshop_tabs');
			$templater->register('tabbits', 	$tabbits);
			$templater->register('tabcontent', 	$tabcontent);
			$templater->register('pagenav', 	$pagenav);
		$HTML = $templater->render();
		
		if (!count($itemIds))
		{
			// No items in the shop
			$HTML = $vbphrase['dbtech_vbshop_no_items_frontend'];
		}
	}
	else
	{
		$HTML = $vbphrase['dbtech_vbshop_no_items_frontend'];
	}
	
	if ($vbulletin->GPC['isajax'])
	{
		VBSHOP::outputXML(array(
			'shopname' 		=> VBSHOP::$cache['shop'][$vbulletin->GPC['shopid']]['title'],
			'shopcontent' 	=> $HTML,
			'cartitems' 	=> $cartitems,
			'totalprice' 	=> $totalprice,
		));
	}
	
	$jsphrases = array(
		'dbtech_vbshop_switching_shop' 			=> $vbphrase['dbtech_vbshop_switching_shop'],
		'dbtech_vbshop_switching_shop_descr' 	=> $vbphrase['dbtech_vbshop_switching_shop_descr'],
		'dbtech_vbshop_sorting_items' 			=> $vbphrase['dbtech_vbshop_sorting_items'],
		'dbtech_vbshop_sorting_items_descr' 	=> $vbphrase['dbtech_vbshop_sorting_items_descr'],
		'dbtech_vbshop_buying_item' 			=> $vbphrase['dbtech_vbshop_buying_item'],
		'dbtech_vbshop_buying_item_descr' 		=> $vbphrase['dbtech_vbshop_buying_item_descr'],
	);

	// Escape them
	VBSHOP::jsEscapeString($jsphrases);
	
	$escapedJsPhrases = '';
	foreach ($jsphrases as $varname => $value)
	{
		// Replace phrases with safe values
		$escapedJsPhrases .= "vbphrase['$varname'] = \"$value\"\n\t\t\t\t\t";
	}
	
	$footer = VBSHOP::js($escapedJsPhrases . '
		var vBShop = {
			shopid : ' . $vbulletin->GPC['shopid'] . ',
			pagenumber : ' . $vbulletin->GPC['pagenumber'] . ',
			tab : ' . $vbulletin->GPC['tab'] . ',
			perpage : ' . $vbulletin->GPC['perpage'] . ',
			sorttype : \'' . $vbulletin->GPC['sorttype'] . '\',
			sortorder : \'' . $vbulletin->GPC['sortorder'] . '\'		
		};
	', false, false) . $footer;
	
	$page_templater = vB_Template::create('dbtech_vbshop_shop');
		$page_templater->register('cartitems', 		$cartitems);
		$page_templater->register('discount', 		$discount);
		$page_templater->register('totalprice', 	$totalprice);
		$page_templater->register('shop', 			VBSHOP::$cache['shop'][$vbulletin->GPC['shopid']]);
		if (count($shops) > 1)
		{
			// Only show this if more than one shop exists
			$page_templater->register('shops', 		implode('', $shops));
		}
		$page_templater->register('perpage', 		$vbulletin->GPC['perpage']);
		$page_templater->register('HTML', 			$HTML);
	$HTML = $page_templater->render();
}

// #############################################################################
if ($_REQUEST['action'] == 'checkout')
{
	// Add to the navbits
	$navbits[''] = $pagetitle = $vbphrase['dbtech_vbshop_checkout'];
	
	// Include cart code
	require(DIR . '/dbtech/vbshop/includes/cart.php');

	$jsphrases = array(
		'dbtech_vbshop_updating_cart' 			=> $vbphrase['dbtech_vbshop_updating_cart'],
		'dbtech_vbshop_updating_cart_descr' 	=> $vbphrase['dbtech_vbshop_updating_cart_descr']
	);

	// Escape them
	VBSHOP::jsEscapeString($jsphrases);
	
	$escapedJsPhrases = '';
	foreach ($jsphrases as $varname => $value)
	{
		// Replace phrases with safe values
		$escapedJsPhrases .= "vbphrase['$varname'] = \"$value\"\n\t\t\t\t\t";
	}
	
	$footer = VBSHOP::js($escapedJsPhrases, false, false) . $footer;

	$page_templater = vB_Template::create('dbtech_vbshop_checkout');
		$page_templater->register('allowsubmit', 	$allowsubmit);
		$page_templater->register('cartcontents', 	$cartcontents);
	$HTML = $page_templater->render();	
}

// #############################################################################
if ($_POST['action'] == 'confirmcheckout')
{
	// Store item ids
	$itemids = array();
	foreach ((array)$shoppingcart['items'] as $shopid => $items)
	{
		foreach ($items as $itemid => $quantity)
		{
			if (!$item = VBSHOP::$cache['item'][$itemid])
			{
				// This no longer exists
				continue;
			}

			if (!$item['active'])
			{
				// Skip this
				continue;
			}

			// Store the itemid
			$itemids[] = $itemid;
		}
	}
	
	$allowsubmit = false;
	if (count($itemids))
	{
		// Store item info
		$iteminfo = array();
		$iteminfo_q = VBSHOP::$db->fetchAll('
			SELECT *		
			FROM $dbtech_vbshop_shopinventory
			WHERE itemid :itemIds
				AND active = 1
		', array(
			':itemIds' => VBSHOP::$db->queryList($itemids)
		));
		foreach ($iteminfo_q as $iteminfo_r)
		{
			// Index by shopid and itemid
			$iteminfo[$iteminfo_r['shopid']][$iteminfo_r['itemid']] = $iteminfo_r;
		}
		$db->free_result($iteminfo_q);
		unset($iteminfo_r);
		
		$userinfo = $vbulletin->userinfo;
		$cartitems = '';
		$totals = '';
		$totalprices = array();
		$allowsubmit = true;
		
		foreach ((array)$shoppingcart['items'] as $shopid => $items)
		{
			foreach ($items as $itemid => $quantity)
			{
				if (!is_array(VBSHOP::$cache['item'][$itemid]))
				{
					// This no longer exists
					continue;
				}
				
				if (!is_array($iteminfo[$shopid][$itemid]))
				{
					// This no longer exists
					continue;
				}
				
				// Grab the full item info
				$item = array_merge(VBSHOP::$cache['item'][$itemid], $iteminfo[$shopid][$itemid]);
				
				 // Ensure this is set
				$item['quantity'] = ($item['uniqueitem'] ? 1 : $quantity);
				
				// Init the item
				$itemobj = VBSHOP::init_item($item);
				
				if (!$itemobj->purchase($vbulletin->userinfo))
				{
					// Purchase failed
					continue;
				}
			}
		}
	}
	
	// Update shopping cart
	VBSHOP::$db->query('
		REPLACE INTO $dbtech_vbshop_shoppingcart
			(userid, items)
		VALUES 
			(?, ?)
	', array(
		$vbulletin->userinfo['userid'],
		trim(serialize(array()))
	));
	
	// Success phrase
	$vbulletin->url = 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=inventory';
	eval(print_standard_redirect('redirect_dbtech_vbshop_purchasethanks'));	
}

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