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

// The array with the shop we own
$shop = array();

// Only do this if we're trying to set an owner
foreach ((array)VBSHOP::$cache['shop'] as $shopid => $shopinfo)
{
	if ($shopinfo['ownerid'] == $vbulletin->userinfo['userid'])
	{
		// We haz shop
		$shop = $shopinfo;
		break;
	}
}

if (!count($shop))
{
	// We don't own the shop
	eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_you_are_not_owner'])));
}

// #############################################################################
if ($_REQUEST['action'] == 'itemmanagement' OR empty($_REQUEST['action']))
{
	$items_by_category 	= array();
	foreach ((array)VBSHOP::$cache['item'] as $itemid => $item)
	{
		if ($item['ownerid'] != $vbulletin->userinfo['userid'])
		{
			// We're not the owner of this item
			continue;
		}
		
		// Index by categoryid
		$items_by_category[$item['categoryid']][$itemid] = $item;
	}
	
	$find = array(
		"\r\n",
		"\n",
		"\t",
		"'"
	);
	
	$replace = array(
		'\r\n',
		'\n',
		'\t',
		"\'",
	);
	
	$categorybits = '';
	if (count($items_by_category))
	{
		foreach ($items_by_category as $categoryid => $items)
		{
			$itembits = '';			
			foreach ($items as $itemid => $item)
			{
				$phrases = array(
					'delete' => str_replace($find, $replace, construct_phrase($vbphrase['dbtech_vbshop_are_you_sure_want_to_delete_item_x'], $item['title'], 'itemid', $itemid, ''))
				);
				
				// Ensure this is set
				$item['icon'] 		= ($item['icon'] 		? $item['icon'] 	: 'unknown.gif');
				$item['shopicon'] 	= ($item['shopicon'] 	? $item['shopicon'] : 'unknown_shop.gif');
				
				// Do currencybits bits
				$templater = vB_Template::create('dbtech_vbshop_itemmanagement_itembit');
					$templater->register('item', $item);
					$templater->register('phrases', $phrases);
				$itembits .= $templater->render();
			}
			
			// Do currencybits bits
			$templater = vB_Template::create('dbtech_vbshop_itemmanagement_categorybit');
				$templater->register('category', VBSHOP::$cache['category'][$categoryid]);
				$templater->register('itembits', $itembits);
			$categorybits .= $templater->render();
		}
	}
	
	// Add to the navbits
	$navbits[''] = $pagetitle = $vbphrase['dbtech_vbshop_item_management'];
	
	// Create the archive template
	$templater = vB_Template::create('dbtech_vbshop_itemmanagement');
		$templater->register('pagetitle', 		$pagetitle);
		$templater->register('categorybits', 	$categorybits);
	$HTML = $templater->render();	
}

	
// #############################################################################
if ($_REQUEST['action'] == 'modify')
{
	$itemid = $vbulletin->input->clean_gpc('r', 'itemid', TYPE_UINT);
	$item = ($itemid ? VBSHOP::$cache['item']["$itemid"] : false);
	
	$currencys 	= array();
	foreach ((array)VBSHOP::$cache['currency'] as $currencyid => $currency)
	{
		if (!$currency['customshops'])
		{
			// Can't use in custom shops
			continue;
		}

		// Index by categoryid
		$currencys["$currencyid"] = $currency['title'];
	}
	
	// Sort the array as a string
	asort($currencys, SORT_STRING);	
	
	if (!count($currencys))
	{
		// Missing categories
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_no_available_currencies'])));
	}
	
	$categorys = array();
	foreach ((array)VBSHOP::$cache['category'] as $categoryid => $category)
	{
		if (!VBSHOP::checkPermissions($vbulletin->userinfo, $category['permissions']))
		{
			// This isn't to be displayed
			continue;
		}
		
		if (!$category['customshops'])
		{
			// Can't use in custom shops
			continue;
		}
		
		// 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
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_no_available_categories'])));
	}
	
	if (!is_array($item))
	{
		// Non-existing item
		$itemid = 0;
	}
	
	$icons = array('unknown.gif' => $vbphrase['none']);
	$shopicons = array('unknown_shop.gif' => $vbphrase['none']);

	$folders = array('customitems');
	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);
	
	$defaults = array(
		'itemtypeid' 	=> 'custom',
		'title' 		=> 'An Item',
		'description' 	=> 'A random new item that does fancy things.',
		'displayorder'	=> 10,
		'uniqueitem'	=> 0,
		'duration'		=> 0,
		'reconfigure'	=> 1,
		'regift'		=> 1,
	);	
	
	if ($itemid)
	{
		// Edit
		
		// Fetch info about all shops this item belongs to
		$inventory = $db->query_first_slave("
			SELECT inventory.*
			FROM " . TABLE_PREFIX . "dbtech_vbshop_shopinventory AS inventory
			LEFT JOIN " . TABLE_PREFIX . "dbtech_vbshop_shop AS shop USING(shopid)
			WHERE inventory.itemid = $itemid
				AND inventory.shopid = " . intval($shop['shopid'])
		);
	}
	else
	{
		// Add
		
		// Set defaults
		$item = $defaults;
		$inventory = array(
			'price' 		=> 0,
			'buybackprice' 	=> 0,
			'buybacktime' 	=> 0,
			'stock' 		=> 0,
			'maxstock' 		=> 0,
			'refilltime' 	=> 0,
			'lastrefill' 	=> 0
		);
	}
	
	$currencies 		= '';
	$categories 		= '';
	$iconoptions 		= '';
	$shopiconoptions 	= '';
	
	foreach ($currencys as $optionvalue => $optiontitle)
	{
		$templater = vB_Template::create('option');
			$templater->register('optionvalue', 	$optionvalue);
			$templater->register('optiontitle', 	$optiontitle);
			$templater->register('optionselected', 	($item['currencyid'] == $optionvalue ? 'selected="selected"' : ''));
		$currencies .= $templater->render();	
	}
	
	foreach ($categorys as $optionvalue => $optiontitle)
	{
		$templater = vB_Template::create('option');
			$templater->register('optionvalue', 	$optionvalue);
			$templater->register('optiontitle', 	$optiontitle);
			$templater->register('optionselected', 	($item['categoryid'] == $optionvalue ? 'selected="selected"' : ''));
		$categories .= $templater->render();	
	}
	
	foreach ($icons as $optionvalue => $optiontitle)
	{
		$templater = vB_Template::create('option');
			$templater->register('optionvalue', 	$optionvalue);
			$templater->register('optiontitle', 	$optiontitle);
			$templater->register('optionselected', 	($item['icon'] == $optionvalue ? 'selected="selected"' : ''));
		$iconoptions .= $templater->render();	
	}
	
	foreach ($shopicons as $optionvalue => $optiontitle)
	{
		$templater = vB_Template::create('option');
			$templater->register('optionvalue', 	$optionvalue);
			$templater->register('optiontitle', 	$optiontitle);
			$templater->register('optionselected', 	($item['shopicon'] == $optionvalue ? 'selected="selected"' : ''));
		$shopiconoptions .= $templater->render();	
	}
	
	$fieldbits = '';
	for ($i = 1; $i <= 5; $i++)
	{
		$templater = vB_Template::create('dbtech_vbshop_itemmanagement_modify_fieldbit');
			$templater->register('i', 		$i);
			$templater->register('field', 	$item['code'][$i]);
		$fieldbits .= $templater->render();	
	}
	
	// Htmlise
	//$item['title'] 			= htmlspecialchars_uni($item['title']);
	//$item['description'] 	= htmlspecialchars_uni($item['description']);
	
	// Add to the navbits
	$navbits[''] = $pagetitle = ($itemid ? strip_tags(construct_phrase($vbphrase['dbtech_vbshop_editing_x_y'], $vbphrase['dbtech_vbshop_item'], $item['title'])) : $vbphrase['dbtech_vbshop_add_new_item']);
	
	// Create the archive template
	$templater = vB_Template::create('dbtech_vbshop_itemmanagement_modify');
		$templater->register('pagetitle', 		$pagetitle);
		$templater->register('item', 			$item);
		$templater->register('shop', 			$shop);
		$templater->register('inventory', 		$inventory);
		$templater->register('currencies', 		$currencies);
		$templater->register('categories', 		$categories);
		$templater->register('iconoptions', 	$iconoptions);
		$templater->register('shopiconoptions', $shopiconoptions);
		$templater->register('fieldbits', 		$fieldbits);
	$HTML = $templater->render();	
	
	// Add the JS
	$bodyinclude = VBSHOP::js('_admin', true, false);
	$bodyinclude .= VBSHOP::js("vBShop_Admin.image_preview('item_icon', '{$vbulletin->options['bburl']}/dbtech/vbshop/images/');", false, false);	
	$bodyinclude .= VBSHOP::js("vBShop_Admin.image_preview('item_shopicon', '{$vbulletin->options['bburl']}/dbtech/vbshop/images/');", false, false);	
}

// #############################################################################
if ($_REQUEST['action'] == 'update')
{
	// Grab stuff
	$vbulletin->input->clean_array_gpc('p', array(
		'itemid' 	=> TYPE_UINT,
		'item' 		=> TYPE_ARRAY,
		'inventory' => TYPE_ARRAY,
	));
	
	// Hardcode some variables
	$vbulletin->GPC['item']['itemtypeid'] 	= 'custom';
	$vbulletin->GPC['item']['shop'] 		= $shop['bitfield'];
	$vbulletin->GPC['item']['ownerid'] 		= $vbulletin->userinfo['userid'];
	$vbulletin->GPC['item']['title'] 		= htmlspecialchars_uni($vbulletin->GPC['item']['title']);
	$vbulletin->GPC['item']['description'] 	= htmlspecialchars_uni($vbulletin->GPC['item']['description']);

	// init data manager
	$dm =& VBSHOP::initDataManager('Item', $vbulletin, ERRTYPE_STANDARD);
	
	// 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
			eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_invalid_item'])));
		}
		
		// Set existing
		$dm->set_existing($existing);
				
		// Added
		$phrase = $vbphrase['dbtech_vbshop_edited'];
	}
	else
	{
		// Added
		$phrase = $vbphrase['dbtech_vbshop_added'];
		$dm->set('shop', $shop['bitfield']);
	}
	
	// item fields
	foreach ($vbulletin->GPC['item'] AS $key => $val)
	{
		if (!$vbulletin->GPC['itemid'] OR $existing["$key"] != $val)
		{
			// Only set changed values
			$dm->set($key, $val);
		}
	}
	
	// Save! Hopefully.
	$itemid = $dm->save();
	
	// Hardcode some variables
	$vbulletin->GPC['inventory']['itemid'] 			= ($vbulletin->GPC['itemid'] ? $vbulletin->GPC['itemid'] : $itemid);
	if (!VBSHOP::$isPro)
	{
		$vbulletin->GPC['inventory']['maxstock'] 	= -1;
	}
	
	
	if (count($vbulletin->GPC['inventory']))
	{
		// Fetch info about all shops this item belongs to
		$inventory = $db->query_first_slave("
			SELECT inventory.*
			FROM " . TABLE_PREFIX . "dbtech_vbshop_shopinventory AS inventory
			LEFT JOIN " . TABLE_PREFIX . "dbtech_vbshop_shop AS shop USING(shopid)
			WHERE inventory.itemid = " . intval($vbulletin->GPC['inventory']['itemid']) . "
				AND inventory.shopid = " . intval($shop['shopid'])
		);
		
		// init data manager
		$dm =& VBSHOP::initDataManager('Shopinventory', $vbulletin, ERRTYPE_STANDARD);
			$dm->set('shopid', $shop['shopid']);
		if ($inventory)
		{
			// Set existing inventory if it, well, exists
			$dm->set_existing($inventory);
		}
		
		foreach ($vbulletin->GPC['inventory'] AS $key => $val)
		{
			if ($inventory[$key] != $val)
			{
				// Only set changed values
				$dm->set($key, $val);
			}
		}
		$dm->save();
		unset($dm);
	}	
	
	// Success phrase
	$vbulletin->url = 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=itemmanagement';
	eval(print_standard_redirect('redirect_dbtech_vbshop_item_updated'));	
}

// #############################################################################
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_STANDARD);
				$dm->set_existing($existing);
				$dm->set('displayorder', $displayorder);
			$dm->save();
			unset($dm);	
		}
	}
	
	$vbulletin->url = 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=itemmanagement';
	eval(print_standard_redirect('redirect_dbtech_vbshop_item_updated'));	
}

// #############################################################################
if ($_REQUEST['action'] == 'kill')
{
	$vbulletin->input->clean_gpc('r', 'itemid', TYPE_UINT);
	
	if (!$existing = VBSHOP::$cache['item'][$vbulletin->GPC['itemid']])
	{
		// Couldn't find the item
		eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_invalid_item'])));
	}
	
	// init data manager
	$dm =& VBSHOP::initDataManager('Item', $vbulletin, ERRTYPE_STANDARD);
		$dm->set_existing($existing);
	$dm->delete();
	
	$vbulletin->url = 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=itemmanagement';
	eval(print_standard_redirect('redirect_dbtech_vbshop_item_updated'));	
}

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