<?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();
}

// #############################################################################
if ($_REQUEST['action'] == 'shopmanagement' OR empty($_REQUEST['action']))
{
	// 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))
	{
		// Store list of userids to lookup
		$userids = array(0 => 0);
		
		if (!isset($userids[$shop['latestcustomer']]))
		{
			// Ignore this
			$userids[$shop['latestcustomer']] = $shop['latestcustomer'];	
		}
		unset($userids[0]);		
		
		if (count($userids))
		{
			$usernames = $db->query_read_slave("
				SELECT
					userid,
					username,
					usergroupid,
					infractiongroupid,
					displaygroupid,
					dbtech_vbshop_purchase
				FROM " . TABLE_PREFIX . "user
				WHERE userid IN(" . implode(',', $userids) . ")
			");
			while ($username = $db->fetch_array($usernames))
			{
				// Grab the markup username
				fetch_musername($username);
				
				// Store this in the lookup
				$userids[$username['userid']] = $username['musername'];
			}
		}
		
		$shop['logo'] 			= ($shop['logo'] 			? $shop['logo'] 											: $vbulletin->options['bburl'] . '/dbtech/vbshop/images/unknown_shop.gif');
		$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['description'] 	= nl2br($shop['description']);
		
		// 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();
		}			
	}
	
	// Add to the navbits
	$navbits[''] = $pagetitle = $vbphrase['dbtech_vbshop_shop_management'];
	
	// Create the archive template
	$templater = vB_Template::create('dbtech_vbshop_shopmanagement');
		$templater->register('pagetitle', 		$pagetitle);
		$templater->register('shop', 			$shop);
	$HTML = $templater->render();
}

// #############################################################################
if ($_REQUEST['action'] == 'update')
{
	// Grab stuff
	$vbulletin->input->clean_array_gpc('p', array(
		'shopid' 	=> TYPE_UINT,
		'shop' 		=> TYPE_ARRAY,
	));
	
	//$vbulletin->GPC['shop']['title'] 		= htmlspecialchars_uni($vbulletin->GPC['shop']['title']);
	//$vbulletin->GPC['shop']['description'] 	= htmlspecialchars_uni($vbulletin->GPC['shop']['description']);
		
	// init data manager
	$dm =& VBSHOP::initDataManager('Shop', $vbulletin, ERRTYPE_STANDARD);
	
	// set existing info if this is an update
	if ($vbulletin->GPC['shopid'])
	{
		if (!$existing = VBSHOP::$cache['shop']["{$vbulletin->GPC[shopid]}"])
		{
			// Couldn't find the shop
			eval(standard_error(fetch_error('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_shop'], $vbulletin->GPC['shopid'])));
		}
		
		if ($existing['ownerid'] != $vbulletin->userinfo['userid'])
		{
			// We don't own the shop
			eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_you_are_not_owner'])));
		}
		
		// Set existing
		$dm->set_existing($existing);
				
		// Added
		$phrase = $vbphrase['dbtech_vbshop_edited'];
	}
	else
	{
		// Added
		$phrase = $vbphrase['dbtech_vbshop_added'];
		
		foreach ((array)VBSHOP::$cache['shop'] as $shopid => $shop)
		{
			if ($shop['ownerid'] == $vbulletin->userinfo['userid'])
			{
				// We own another shop - somehow got here
				eval(standard_error(fetch_error('dbtech_vbshop_error_x', $vbphrase['dbtech_vbshop_you_already_own_a_shop'])));
			}
		}
		
		// Locally set this
		$vbulletin->GPC['shop']['ownerid'] = $vbulletin->userinfo['userid'];
	}
	
	// shop fields
	foreach ($vbulletin->GPC['shop'] AS $key => $val)
	{
		if (!$vbulletin->GPC['shopid'] OR $existing["$key"] != $val)
		{
			// Only set changed values
			$dm->set($key, $val);
		}
	}
	
	// Save! Hopefully.
	$dm->save();
	
	// Success phrase
	$vbulletin->url = 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=shopmanagement';
	eval(print_standard_redirect('redirect_dbtech_vbshop_shop_updated'));	
}

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