<?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.					  # ||
|| # ---------------------------------------------------------------- # ||
|| #################################################################### ||
\*======================================================================*/

// #############################################################################
require_once(DIR . '/dbtech/vbshop/includes/functions.php');

// #############################################################################
if ($_REQUEST['action'] == 'item' OR empty($_REQUEST['action']))
{
	$items_by_category 	= array();
	foreach ((array)VBSHOP::$cache['item'] as $itemid => $item)
	{
		// Index by categoryid
		$items_by_category[($item['ownerid'] ? 1 : 0)]["$item[categoryid]"]["$itemid"] = $item;
	}
	
	$itemtypes 	= array();
	foreach ((array)VBSHOP::$cache['itemtype'] as $itemtypeid => $itemtype)
	{
		if (!$itemtype['active'])
		{
			// Inactive item type
			continue;
		}
		
		// Index by categoryid
		$itemtypes["$itemtypeid"] = $itemtype['title'];
	}
	
	print_cp_header($vbphrase['dbtech_vbshop_item_management']);
	
	// Table header
	$headings = array();
	$headings[] = $vbphrase['title'];
	$headings[] = nl2br($vbphrase['description']);
	$headings[] = $vbphrase['active'];
	$headings[] = preg_replace('/<dfn>.*$/isU', '', $vbphrase['dbtech_vbshop_item_type']);
	$headings[] = $vbphrase['display_order'];
	//$headings[] = $vbphrase['dbtech_vbshop_item_price'];
	/*DBTECH_PRO_START*/
	$headings[] = preg_replace('/<dfn>.*$/isU', '', $vbphrase['dbtech_vbshop_item_giftable']);
	$headings[] = preg_replace('/<dfn>.*$/isU', '', $vbphrase['dbtech_vbshop_item_unique']);
	/*DBTECH_PRO_END*/
	//$headings[] = $vbphrase['edit_permissions'];
	$headings[] = $vbphrase['edit'];
	$headings[] = $vbphrase['delete'];
	
	print_form_header('vbshop', 'item');
	construct_hidden_code('action', 'modify');
	print_table_header($vbphrase['dbtech_vbshop_item_management'], count($headings));
	if (empty($itemtypes))
	{
		print_description_row($vbphrase['dbtech_vbshop_no_items'], false, count($headings));
		print_table_footer();
	}
	else
	{
		print_select_row($vbphrase['dbtech_vbshop_item_type'], 'itemtypeid', $itemtypes);
		print_submit_row($vbphrase['dbtech_vbshop_add_new_item'], false, count($headings));
	}
	
	if (count($items_by_category))
	{
		print_form_header('vbshop', 'item');
		construct_hidden_code('action', 'displayorder');
		print_table_header($vbphrase['dbtech_vbshop_item_management'], count($headings));
		print_description_row($vbphrase['dbtech_vbshop_item_management_descr'], false, count($headings));	
		
		foreach ($items_by_category as $ownertype => $items_categories)
		{
			print_table_header($vbphrase['dbtech_vbshop_itemtype_' . $ownertype], count($headings));
			foreach ($items_categories as $categoryid => $items)
			{
				print_description_row(VBSHOP::$cache['category']["$categoryid"]['title'], false, count($headings), 'optiontitle');			
				print_description_row(VBSHOP::$cache['category']["$categoryid"]['description'], false, count($headings));	
				print_cells_row($headings, 0, 'thead');
				
				foreach ($items as $itemid => $item)
				{
					// Ensure this is set
					$item['icon'] 		= ($item['icon'] 		? $item['icon'] 	: 'unknown.gif');
					$item['shopicon'] 	= ($item['shopicon'] 	? $item['shopicon'] : 'unknown_shop.gif');
					
					// Table data
					$cell = array();
					$cell[] = ($item['icon'] ? '<img src="../dbtech/vbshop/images/' . $item['icon'] . '" alt="" /> ' : '') . ($item['shopicon'] ? '<img src="../dbtech/vbshop/images/' . $item['shopicon'] . '" alt="" /> ' : '') . $item['title'];
					$cell[] = nl2br(htmlspecialchars_uni($item['description']));
					$cell[] = ($item['active'] ? $vbphrase['yes'] : '<span class="col-i"><strong>' . $vbphrase['no'] . '</strong></span>');
					$cell[] = $itemtypes["$item[itemtypeid]"];
					$cell[] = "<input type=\"text\" class=\"bginput\" name=\"order[$itemid]\" value=\"$item[displayorder]\" tabindex=\"1\" size=\"3\" title=\"" . $vbphrase['edit_display_order'] . "\"" . iif($vbulletin->debug, " title=\"name=&quot;order[$itemid]&quot; value=&quot;$item[displayorder]&quot;\"") . " />";
					//$cell[] = vb_number_format(round($item['price'], 2)) . ' ' . $vbulletin->options['dbtech_vbshop_pointsname'];
					/*DBTECH_PRO_START*/
					$cell[] = ($item['giftable'] 	? $vbphrase['yes'] : '<span class="col-i"><strong>' . $vbphrase['no'] . '</strong></span>');
					$cell[] = ($item['uniqueitem'] 	? $vbphrase['yes'] : '<span class="col-i"><strong>' . $vbphrase['no'] . '</strong></span>');
					/*DBTECH_PRO_END*/
					//$cell[] = construct_link_code($vbphrase['edit_permissions'], 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=itempermissions&amp;itemid=' . $itemid);
					$cell[] = construct_link_code($vbphrase['edit'], 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=item&amp;action=modify&amp;itemid=' . $itemid);
					$cell[] = construct_link_code($vbphrase['delete'], 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=item&amp;action=delete&amp;itemid=' . $itemid);
					
					// Print the data
					print_cells_row($cell, 0, 0, -5, 'middle', 0, 1);
				}
			}
		}
		
		print_submit_row($vbphrase['save_display_order'], false, count($headings));	
	}
}

// #############################################################################
if ($_REQUEST['action'] == 'modify')
{
	$itemid = $vbulletin->input->clean_gpc('r', 'itemid', TYPE_UINT);
	$item = ($itemid ? VBSHOP::$cache['item']["$itemid"] : false);
	
	if (!$itemid)
	{	
		$vbulletin->input->clean_gpc('r', 'itemtypeid', TYPE_STR);
		if (!$vbulletin->GPC['itemtypeid'])
		{
			print_stop_message('dbtech_vbshop_missing_x',
				$vbphrase['dbtech_vbshop_itemtype'],
				$vbulletin->session->vars['sessionurl'],
				'item',
				'item'
			);
		}
	}
	
	$currencys 	= array();
	foreach ((array)VBSHOP::$cache['currency'] as $currencyid => $currency)
	{
		// Index by categoryid
		$currencys[$currencyid] = $currency['title'];
	}
	
	// Sort the array as a string
	asort($currencys, SORT_STRING);	
	
	$currencys_nocustom 	= array();
	foreach ((array)VBSHOP::$cache['currency'] as $currencyid => $currency)
	{
		if (!$currency['customshops'])
		{
			// Can't use in custom shops
			continue;
		}
		
		// Index by categoryid
		$currencys_nocustom[$currencyid] = $currency['title'];
	}
	
	// Sort the array as a string
	asort($currencys_nocustom, SORT_STRING);	
	
	if (!count($currencys))
	{
		// Missing categories
		print_stop_message('dbtech_vbshop_missing_x',
			$vbphrase['dbtech_vbshop_currency'],
			$vbulletin->session->vars['sessionurl'],
			'currency',
			'modify'
		);
	}
	
	$categorys = array();
	foreach ((array)VBSHOP::$cache['category'] as $categoryid => $category)
	{
		// Add the phrased category name to the array
		$categorys[$categoryid] = $category['title'];
	}
	
	// Sort the array as a string
	asort($categorys, SORT_STRING);	
	
	if (!count($categorys))
	{
		// Missing categories
		print_stop_message('dbtech_vbshop_missing_x',
			$vbphrase['dbtech_vbshop_category'],
			$vbulletin->session->vars['sessionurl'],
			'category',
			'modify'
		);
	}
	
	if (!is_array($item))
	{
		// Non-existing item
		$itemid = 0;
	}
	
	$icons = $shopicons = array('' => $vbphrase['none']);
	$folders = array('items', 'customitems', 'gifts');
	foreach ($folders as $folder)
	{
		// Normal icons
		$d = dir(DIR . '/dbtech/vbshop/images/' . $folder);
		while (false !== ($file = $d->read()))
		{
			if ($file != '.' AND $file != '..' AND $file != 'index.html' AND $file != $folder)
			{
				// Store the icon
				$icons[$folder . '/' . $file] = $file;
			}
		}
		$d->close();

		// Shop icons
		$d = dir(DIR . '/dbtech/vbshop/images/' . $folder . '/shop');
		while (false !== ($file = $d->read()))
		{
			if ($file != '.' AND $file != '..' AND $file != 'index.html')
			{
				// Store the icon
				$shopicons[$folder . '/shop/' . $file] = $file;
			}
		}
		$d->close();
	}

	// Sort the array as a string
	asort($icons, SORT_STRING);
	asort($shopicons, SORT_STRING);
	
	$itemtypes 	= array();
	foreach ((array)VBSHOP::$cache['itemtype'] as $itemtypeid => $itemtype)
	{
		// Index by categoryid
		$itemtypes[$itemtypeid] = $itemtype['title'];
	}	
	
	$headings = array(
		$vbphrase['usergroup'],
		$vbphrase['dbtech_vbshop_can_purchase']
	);	
	
	$defaults = array(
		'itemtypeid' 	=> $vbulletin->GPC['itemtypeid'],
		'title' 		=> 'An Item',
		'description' 	=> 'A random new item that does fancy things.',
		'displayorder'	=> 10,
		'active'		=> 1,
		'uniqueitem'	=> 0,
		'duration'		=> 0,
		'reconfigure'	=> 1,
		'regift'		=> 1,
		'nodisplay'		=> 0,
	);	
	$inventorydefaults = array(
		'active' 		=> 0,
		'price' 		=> 0,
		'buybackprice' 	=> 0,
		'buybacktime' 	=> 0,
		'stock'			=> -1,
		'maxstock'		=> -1,
		'refilltime'	=> 0,
	);	
	
	if ($itemid)
	{
		// Edit
		print_cp_header(strip_tags(construct_phrase($vbphrase['dbtech_vbshop_editing_x_y'], $vbphrase['dbtech_vbshop_item'], $item['title'])));
		print_form_header('vbshop', 'item');
		construct_hidden_code('action', 'update');
		construct_hidden_code('itemid', $itemid);
		print_table_header(construct_phrase($vbphrase['dbtech_vbshop_editing_x_y'], $vbphrase['dbtech_vbshop_item'], $item['title']));
		
		// Fetch info about all shops this item belongs to
		$inventory = VBSHOP::$db->fetchAllKeyed('
			SELECT *
			FROM $dbtech_vbshop_shopinventory
			WHERE itemid = ?
		', 'shopid', array(
			$itemid
		));
	}
	else
	{
		// Add
		print_cp_header($vbphrase['dbtech_vbshop_add_new_item']);
		print_form_header('vbshop', 'item');
		construct_hidden_code('action', 'update');
		print_table_header($vbphrase['dbtech_vbshop_add_new_item']);
		construct_hidden_code('item[shop]', 0);
		
		// Set defaults
		$item = $defaults;
	}
	
	// Load the item info
	$itemobj = VBSHOP::init_item($item);
	
	construct_hidden_code('item[itemtypeid]', 																	$item['itemtypeid']);	
	
	
	print_label_row($vbphrase['dbtech_vbshop_item_type'], 														$itemtypes[$item['itemtypeid']]);
	print_input_row($vbphrase['title'], 								'item[title]', 							$item['title']);
	print_select_row($vbphrase['dbtech_vbshop_category'], 				'item[categoryid]', 		$categorys, $item['categoryid']);
	print_textarea_row($vbphrase['description'], 						'item[description]', 					$item['description']);
	print_yes_no_row($vbphrase['active'], 								'item[active]', 						$item['active']);
	print_input_row($vbphrase['display_order'], 						'item[displayorder]', 					$item['displayorder']);
	print_select_row($vbphrase['icon'], 								'item[icon]',				$icons,		$item['icon']);
	print_select_row($vbphrase['dbtech_vbshop_shop_icon'], 				'item[shopicon]',			$shopicons,	$item['shopicon']);
	/*DBTECH_PRO_START*/
	print_yes_no_row($vbphrase['dbtech_vbshop_item_giftable'], 			'item[giftable]', 						$item['giftable']);
	print_yes_no_row($vbphrase['dbtech_vbshop_item_onlygiftable'], 		'item[onlygiftable]', 					$item['onlygiftable']);
	print_yes_no_row($vbphrase['dbtech_vbshop_pm_on_gift'], 			'item[giftpm]', 						$item['giftpm']);
	print_yes_no_row($vbphrase['dbtech_vbshop_item_unique'], 			'item[uniqueitem]', 					$item['uniqueitem']);
	print_yes_no_row($vbphrase['dbtech_vbshop_item_threadcreation'], 	'item[threadcreation]', 				$item['threadcreation']);
	print_yes_no_row($vbphrase['dbtech_vbshop_item_threadpage'], 		'item[threadpage]', 					$item['threadpage']);
	print_input_row($vbphrase['dbtech_vbshop_item_duration'], 			'item[duration]', 						$item['duration']);
	/*DBTECH_PRO_END*/
	print_yes_no_row($vbphrase['dbtech_vbshop_item_reconfigure'], 		'item[reconfigure]', 					$item['reconfigure']);
	/*DBTECH_PRO_START*/
	print_yes_no_row($vbphrase['dbtech_vbshop_item_regift'], 			'item[regift]', 						$item['regift']);
	/*DBTECH_PRO_END*/
	print_yes_no_row($vbphrase['dbtech_vbshop_item_nodisplay'], 		'item[nodisplay]', 						$item['nodisplay']);

	if (method_exists($itemobj, 'print_admin_form'))
	{
		// Item info
		print_description_row($vbphrase['dbtech_vbshop_item_type_fields'], false, 2, 'optiontitle');
		$itemobj->print_admin_form($item['code']);
	}
	print_table_header($vbphrase['dbtech_vbshop_per_shop_inventory_configuration']);
	foreach (VBSHOP::$cache['shop'] as $shopid => $shop)
	{
		// Shorthand
		$shopinventory = $inventory[$shopid];

		// Determine which currency array to use
		$currarr = (VBSHOP::$cache['shop'][$shopid]['ownerid'] ? $currencys_nocustom : $currencys);
		
		print_description_row(htmlspecialchars_uni($shop['title']), false, 2, 'optiontitle');
		
		
		
		if (is_array($shopinventory))
		{
			// Set item ID
			construct_hidden_code('inventory[' . $shopid . '][itemid]', $item['itemid']);
		}

		// Now set defaults
		$shopinventory = (is_array($shopinventory) ? $shopinventory : $inventorydefaults);		

		print_yes_no_row($vbphrase['active'], 											'inventory[' . $shopid . '][active]', 					$shopinventory['active']);
		print_select_row($vbphrase['dbtech_vbshop_item_currency'], 						'inventory[' . $shopid . '][currencyid]', 	$currarr, 	$shopinventory['currencyid']);
		print_input_row($vbphrase['dbtech_vbshop_item_price'], 							'inventory[' . $shopid . '][price]', 					$shopinventory['price']);
		print_input_row($vbphrase['dbtech_vbshop_item_buyback_price'], 					'inventory[' . $shopid . '][buybackprice]', 			$shopinventory['buybackprice']);
		print_input_row($vbphrase['dbtech_vbshop_item_buyback_time'], 					'inventory[' . $shopid . '][buybacktime]', 				$shopinventory['buybacktime']);
		print_yes_no_row($vbphrase['dbtech_vbshop_item_buyback_replenish'], 			'inventory[' . $shopid . '][buybackreplenish]', 		$shopinventory['buybackreplenish']);
		print_textarea_row($vbphrase['dbtech_vbshop_item_notifications'], 				'inventory[' . $shopid . '][notifications]', 			$shopinventory['notifications']);
		/*DBTECH_PRO_START*/
		print_textarea_row($vbphrase['dbtech_vbshop_item_notifications_config'],		'inventory[' . $shopid . '][notifications_config]', 	$shopinventory['notifications_config']);
		/*DBTECH_PRO_END*/
		print_input_row($vbphrase['dbtech_vbshop_item_stock'], 							'inventory[' . $shopid . '][stock]', 					$shopinventory['stock']);
		/*DBTECH_PRO_START*/
		print_input_row($vbphrase['dbtech_vbshop_item_maxstock'], 						'inventory[' . $shopid . '][maxstock]', 				$shopinventory['maxstock']);
		print_input_row($vbphrase['dbtech_vbshop_item_refilltime'], 					'inventory[' . $shopid . '][refilltime]', 				$shopinventory['refilltime']);
		/*DBTECH_PRO_END*/
	}
	print_table_header($vbphrase['permissions']);
	print_cells_row($headings, 0, 'thead');
	print_label_row('&nbsp;', '
		<input type="button" value="' . $vbphrase['all_yes'] . '" onclick="vBShop_Admin.toggleRadio(this.form, 1, \'item[permissions]\');" class="button" />
		<input type="button" value=" ' . $vbphrase['all_no'] . '" onclick="vBShop_Admin.toggleRadio(this.form, 0, \'item[permissions]\');" class="button" />
		<input type="button" value=" ' . $vbphrase['all_default'] . '" onclick="vBShop_Admin.toggleRadio(this.form, -1, \'item[permissions]\');" class="button" />
	');	
	foreach ($vbulletin->usergroupcache as $usergroupid => $usergroup)
	{
		print_yes_no_other_row($usergroup['title'], 'item[permissions][' . $usergroupid . ']', $vbphrase['default'], (isset($item['permissions'][$usergroupid]) ? $item['permissions'][$usergroupid] : -1));
	}
	print_submit_row(($itemid ? $vbphrase['save'] : $vbphrase['dbtech_vbshop_add_new_item']));
	VBSHOP::js('_admin');
	VBSHOP::js("vBShop_Admin.image_preview('item\\\[icon\\\]', '{$vbulletin->options['bburl']}/dbtech/vbshop/images/');", false);	
	VBSHOP::js("vBShop_Admin.image_preview('item\\\[shopicon\\\]', '{$vbulletin->options['bburl']}/dbtech/vbshop/images/');", false);	
	VBSHOP::js("vBShop_Admin.image_preview('item\\\[code\\\]\\\[customicon\\\]', '{$vbulletin->options['bburl']}/dbtech/vbshop/images/');", false);	
}

// #############################################################################
if ($_REQUEST['action'] == 'update')
{
	// Grab stuff
	$vbulletin->input->clean_array_gpc('p', array(
		'itemid' 	=> TYPE_UINT,
		'item' 		=> TYPE_ARRAY,
		'inventory' => TYPE_ARRAY,
	));
	
	// init data manager
	$dm =& VBSHOP::initDataManager('Item', $vbulletin, ERRTYPE_CP);
	
	// set existing info if this is an update
	if ($vbulletin->GPC['itemid'])
	{
		if (!$existing = VBSHOP::$cache['item'][$vbulletin->GPC['itemid']])
		{
			// Couldn't find the item
			print_stop_message('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_item'], $vbulletin->GPC['itemid']);
		}
		
		// Set existing
		$dm->set_existing($existing);

		// Added
		$phrase = $vbphrase['dbtech_vbshop_edited'];
	}
	else
	{
		// Added
		$phrase = $vbphrase['dbtech_vbshop_added'];
	}
	
	// item fields
	foreach ($vbulletin->GPC['item'] AS $key => $val)
	{
		if (!$vbulletin->GPC['itemid'] OR $existing[$key] != $val OR is_array($val))
		{
			// Only set changed values
			$dm->set($key, $val);
		}
	}
	
	// Save! Hopefully.
	$itemid = $dm->save();
	unset($dm);

	// Ensure this is set
	$vbulletin->GPC['itemid'] = (!$vbulletin->GPC['itemid'] ? $itemid : $vbulletin->GPC['itemid']);

	// Fetch info about all shops this item belongs to
	$inventory = VBSHOP::$db->fetchAllKeyed('
		SELECT *
		FROM $dbtech_vbshop_shopinventory
		WHERE itemid = ?
	', 'shopid', array(
		$vbulletin->GPC['itemid']
	));

	foreach (VBSHOP::$cache['shop'] as $shopid => $shop)
	{
		// init data manager
		$dm =& VBSHOP::initDataManager('Shopinventory', $vbulletin, ERRTYPE_CP);

		if ($inventory[$shopid])
		{
			// Set existing data
			$dm->set_existing($inventory[$shopid]);
		}
		else
		{
			// Set new data
			$dm->set('itemid', $vbulletin->GPC['itemid']);
			$dm->set('shopid', $shopid);
		}

		foreach ($vbulletin->GPC['inventory'][$shopid] AS $key => $val)
		{
			if (!$inventory[$shopid] OR $inventory[$shopid][$key] != $val)
			{
				// Only set changed values
				$dm->set($key, $val);
			}
		}
		$dm->save();
		unset($dm);
	}
		
	define('CP_REDIRECT', 'vbshop.php?do=item');
	print_stop_message('dbtech_vbshop_x_y', $vbphrase['dbtech_vbshop_item'], $phrase);
}

// #############################################################################
if ($_POST['action'] == 'displayorder')
{
	$vbulletin->input->clean_array_gpc('p', array('order' => TYPE_ARRAY));
	
	if (is_array($vbulletin->GPC['order']))
	{
		foreach ($vbulletin->GPC['order'] as $itemid => $displayorder)
		{
			if (!$existing = VBSHOP::$cache['item']["$itemid"])
			{
				// Couldn't find the item
				continue;
			}
			
			if ($existing['displayorder'] == $displayorder)
			{
				// No change
				continue;
			}
			
			// init data manager
			$dm =& VBSHOP::initDataManager('Item', $vbulletin, ERRTYPE_CP);
				$dm->set_existing($existing);
				$dm->set('displayorder', $displayorder);
			$dm->save();
			unset($dm);	
		}
	}
	
	define('CP_REDIRECT', 'vbshop.php?do=item');
	print_stop_message('saved_display_order_successfully');	
}

// #############################################################################
if ($_REQUEST['action'] == 'delete')
{
	$vbulletin->input->clean_gpc('r', 'itemid', TYPE_UINT);
	
	print_cp_header(construct_phrase($vbphrase['dbtech_vbshop_delete_x'], $vbphrase['dbtech_vbshop_item']));
	print_delete_confirmation('dbtech_vbshop_item', $vbulletin->GPC['itemid'], 'vbshop', 'item', 'dbtech_vbshop_item', array('action' => 'kill'), '', 'title');
	print_cp_footer();
}

// #############################################################################
if ($_POST['action'] == 'kill')
{
	$vbulletin->input->clean_gpc('r', 'itemid', TYPE_UINT);
	
	if (!$existing = VBSHOP::$cache['item']["{$vbulletin->GPC[itemid]}"])
	{
		// Couldn't find the item
		print_stop_message('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_item'], $vbulletin->GPC['itemid']);
	}
	
	// init data manager
	$dm =& VBSHOP::initDataManager('Item', $vbulletin, ERRTYPE_CP);
		$dm->set_existing($existing);
	$dm->delete();
	
	define('CP_REDIRECT', 'vbshop.php?do=item');
	print_stop_message('dbtech_vbshop_x_y', $vbphrase['dbtech_vbshop_item'], $vbphrase['dbtech_vbshop_deleted']);	
}

// #############################################################################
if ($_REQUEST['action'] == 'moderation')
{
	$requests = array();
	$requests_q = $db->query_read_slave("
		SELECT item.*, user.username
		FROM " . TABLE_PREFIX . "dbtech_vbshop_item AS item
		LEFT JOIN " . TABLE_PREFIX . "user AS user ON(user.userid = item.ownerid)
		WHERE item.moderation = '1'
		ORDER BY itemid ASC		
	");
	while ($requests_r = $db->fetch_array($requests_q))
	{
		$requests["$requests_r[itemid]"] = $requests_r;
	}
	
	// Table header
	$headings = array();
	$headings[] = $vbphrase['dbtech_vbshop_item'];
	$headings[] = $vbphrase['dbtech_vbshop_item_owner'];
	$headings[] = $vbphrase['dbtech_vbshop_moderation_action'];
	
	
	// Beginning of form
	print_cp_header($vbphrase['dbtech_vbshop_custom_item_moderation']);
	print_form_header('vbshop', 'item');
	construct_hidden_code('action', 'updaterequests');
	print_table_header($vbphrase['dbtech_vbshop_custom_item_moderation'], count($headings));
	print_description_row($vbphrase['dbtech_vbshop_custom_item_moderation_descr'], false, count($headings));
	print_cells_row($headings, 0, 'thead');	
	foreach ((array)$requests as $itemid => $request)
	{
		// Table data
		$cell = array();
		$cell[] = VBSHOP::$cache['item']["$itemid"]['title'];
		$cell[] = ($request['username'] ? $request['username'] : 'N/A');
		$cell[] = '
			<label for="dw_undecided_' . $itemid . '"><input type="radio" name="dowhat[' . $itemid . ']" value="0" id="dw_undecided_' . $itemid . '" checked="checked" />' . $vbphrase['dbtech_vbshop_undecided'] . '</label>
			<label for="dw_approve_' . $itemid . '"><input type="radio" name="dowhat[' . $itemid . ']" value="1" id="dw_approve_' . $itemid . '" />' . $vbphrase['dbtech_vbshop_approve'] . '</label>
			<label for="dw_reject_' . $itemid . '"><input type="radio" name="dowhat[' . $itemid . ']" value="2" id="dw_reject_' . $itemid . '" />' . $vbphrase['dbtech_vbshop_reject'] . '</label>
		';
		
		// Print the data
		print_cells_row($cell, 0, 0, -5, 'top', 1, 1);
	}
	// End of area
	print_submit_row($vbphrase['dbtech_vbshop_perform_moderation'], false, count($headings));
}


// #############################################################################
if ($_POST['action'] == 'updaterequests')
{
	// Grab stuff
	$vbulletin->input->clean_array_gpc('p', array(
		'dowhat'		=> TYPE_ARRAY_UINT,
	));
	
	$SQL 					= array();
	$SQL['approve'] 		= array();
	$SQL['reject'] 			= array();
	$SQL['rejectreason'] 	= array();
	$decrement 				= 0;
	
	foreach ($vbulletin->GPC['dowhat'] as $entryid => $action)
	{
		switch ($action)
		{
			case 1:
				$SQL['approve'][] = $entryid;
				$decrement++;
				break;
			
			case 2:
				$SQL['reject'][] = $entryid;
				$decrement++;
				break;
		}
	}
	
	foreach ($SQL['approve'] as $itemid)
	{
		if (!$existing = VBSHOP::$cache['item']["$itemid"])
		{
			// Couldn't find the item
			continue;
		}
		
		// init data manager
		$dm =& VBSHOP::initDataManager('Item', $vbulletin, ERRTYPE_CP);
			$dm->set_existing($existing);
			$dm->set('moderation', 0);
		$dm->save();
	}
	
	foreach ($SQL['approve'] as $itemid)
	{
		if (!$existing = VBSHOP::$cache['item']["$itemid"])
		{
			// Couldn't find the item
			continue;
		}
		
		// init data manager
		$dm =& VBSHOP::initDataManager('Item', $vbulletin, ERRTYPE_CP);
			$dm->set_existing($existing);
			$dm->set('moderation', 0);
		$dm->save();
	}
	
	foreach ($SQL['reject'] as $itemid)
	{
		if (!$existing = VBSHOP::$cache['item']["$itemid"])
		{
			// Couldn't find the item
			continue;
		}
		
		// init data manager
		$dm =& VBSHOP::initDataManager('Item', $vbulletin, ERRTYPE_CP);
			$dm->set_existing($existing);
		$dm->delete();
	}
	
	/*
	if ($decrement)
	{
		$db->query_write("
			UPDATE `" . TABLE_PREFIX . "user`
			SET 
				`dbtech_vbactivity_medalmoderatecount` = dbtech_vbactivity_medalmoderatecount - $decrement
			WHERE dbtech_vbactivity_medalmoderatecount > 0
		");
	}
	*/
	
	define('CP_REDIRECT', 'vbshop.php?do=item&action=moderation');
	print_stop_message('dbtech_vbshop_x_y', $vbphrase['dbtech_vbshop_item_moderation'], $vbphrase['dbtech_vbshop_edited']);
}

print_cp_footer();