<?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'] == 'shop' OR empty($_REQUEST['action']))
{
	$shops_by_owner 	= array();
	foreach ((array)VBSHOP::$cache['shop'] as $shopid => $shop)
	{
		// Index by categoryid
		$shops_by_owner[($shop['ownerid'] ? 1 : 0)]["$shopid"] = $shop;
	}
	
	print_cp_header($vbphrase['dbtech_vbshop_shop_management']);
	
	// Table header
	$headings = array();
	$headings[] = $vbphrase['dbtech_vbshop_shop_name'];
	$headings[] = $vbphrase['description'];
	$headings[] = $vbphrase['active'];
	$headings[] = $vbphrase['display_order'];	
	if (VBSHOP::$isPro) $headings[] = $vbphrase['dbtech_vbshop_shop_owner_short'];	
	$headings[] = $vbphrase['edit'];
	$headings[] = $vbphrase['delete'];
	
	
	if (count($shops_by_owner))
	{
		$lookup = array();
		foreach (VBSHOP::$cache['shop'] as $shopid => $shop)
		{
			if (!$shop['ownerid'])
			{
				// System owned
				continue;
			}
			
			// Lookup userid
			$lookup[] = $shop['ownerid'];
		}
		
		if (count($lookup))
		{
			$lookup = VBSHOP::$db->fetchAllSingleKeyed('SELECT username, userid FROM $user WHERE userid :queryList', 'userid', 'username', array(':queryList' => VBSHOP::$db->queryList($lookup)));
		}
		
		print_form_header('vbshop', 'shop');
		construct_hidden_code('action', 'displayorder');
		print_table_header($vbphrase['dbtech_vbshop_shop_management'], count($headings));
		print_description_row($vbphrase['dbtech_vbshop_shop_management_descr'], false, count($headings));	
		
		foreach ($shops_by_owner as $ownertype => $shops)
		{
			print_table_header($vbphrase['dbtech_vbshop_shoptype_' . $ownertype], count($headings));
			print_cells_row($headings, 0, 'thead');			
			foreach ($shops as $shopid => $shop)
			{
				// Table data
				$cell = array();
				$cell[] = htmlspecialchars_uni($shop['title']);
				$cell[] = nl2br(htmlspecialchars_uni($shop['description']));
				$cell[] = ($shop['active'] ? $vbphrase['yes'] : '<span class="col-i"><strong>' . $vbphrase['no'] . '</strong></span>');
				$cell[] = "<input type=\"text\" class=\"bginput\" name=\"order[$shopid]\" value=\"$shop[displayorder]\" tabindex=\"1\" size=\"3\" title=\"" . $vbphrase['edit_display_order'] . "\"" . iif($vbulletin->debug, " title=\"name=&quot;order[$shopid]&quot; value=&quot;$shop[displayorder]&quot;\"") . " />";				
				if (VBSHOP::$isPro) $cell[] = ($lookup[$shop['ownerid']] ? $lookup[$shop['ownerid']] : '<span class="col-i"><strong>' . $vbphrase['dbtech_vbshop_no_owner'] . '</strong></span>');
				$cell[] = construct_link_code($vbphrase['edit'], 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=shop&amp;action=modify&amp;shopid=' . $shopid);
				$cell[] = construct_link_code($vbphrase['delete'], 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=shop&amp;action=delete&amp;shopid=' . $shopid);
				
				// Print the data
				print_cells_row($cell, 0, 0, -5, 'middle', 0, 1);
			}
		}
		print_submit_row($vbphrase['save_display_order'], false, count($headings), false, "<input type=\"button\" id=\"addnew\" class=\"button\" value=\"" . str_pad($vbphrase['dbtech_vbshop_add_new_shop'], 8, ' ', STR_PAD_BOTH) . "\" tabindex=\"1\" onclick=\"window.location = 'vbshop.php?do=shop&amp;action=modify'\" />");	
	}
	else
	{
		print_form_header('vbshop', 'shop');	
		construct_hidden_code('action', 'modify');
		print_table_header($vbphrase['dbtech_vbshop_shop_management'], count($headings));
		print_description_row($vbphrase['dbtech_vbshop_no_shops'], false, count($headings));
		print_submit_row($vbphrase['dbtech_vbshop_add_new_shop'], false, count($headings));	
	}
}

// #############################################################################
if ($_REQUEST['action'] == 'modify')
{
	$shopid = $vbulletin->input->clean_gpc('r', 'shopid', TYPE_UINT);
	$shop = ($shopid ? VBSHOP::$cache['shop']["$shopid"] : false);
	
	if (!is_array($shop))
	{
		// Non-existing shop
		$shopid = 0;
	}
	
	$defaults = array(
		'title' 			=> 'Shop',
		'description' 		=> 'A shop that holds a number of purchasable items.',
		'active' 			=> 1,
		'displayorder'		=> 10,
		'beneficiary'		=> -1,
		'beneficiary_split'	=> 100,
	);
	
	$headings = array(
		$vbphrase['usergroup'],
		$vbphrase['dbtech_vbshop_can_access_shop']
	);
	
	if ($shopid)
	{
		// Edit
		print_cp_header(strip_tags(construct_phrase($vbphrase['dbtech_vbshop_editing_x_y'], $vbphrase['dbtech_vbshop_shop'], htmlspecialchars_uni($shop['title']))));
		print_form_header('vbshop', 'shop');
		construct_hidden_code('action', 'update');
		construct_hidden_code('shopid', $shopid);
		print_table_header(construct_phrase($vbphrase['dbtech_vbshop_editing_x_y'], $vbphrase['dbtech_vbshop_shop'], htmlspecialchars_uni($shop['title'])));

		// Fetch info about all shops this item belongs to
		$inventory = VBSHOP::$db->fetchAllKeyed('
			SELECT *
			FROM $dbtech_vbshop_shopinventory
			WHERE shopid = ?
		', 'itemid', array(
			$shopid
		));
	}
	else
	{
		// Add
		print_cp_header($vbphrase['dbtech_vbshop_add_new_shop']);
		print_form_header('vbshop', 'shop');
		construct_hidden_code('action', 'update');
		print_table_header($vbphrase['dbtech_vbshop_add_new_shop']);
		
		$shop = $defaults;
		$inventory = array();
	}
	
	print_description_row($vbphrase['dbtech_vbshop_main_settings'], false, 2, 'optiontitle');	
	print_input_row($vbphrase['title'], 								'shop[title]', 				$shop['title']);
	print_textarea_row($vbphrase['description'], 						'shop[description]', 		$shop['description']);
	print_yes_no_row($vbphrase['active'],								'shop[active]',				$shop['active']);
	print_input_row($vbphrase['display_order'], 						'shop[displayorder]', 		$shop['displayorder']);
	print_description_row($vbphrase['dbtech_vbshop_shop_settings'], false, 2, 'optiontitle');
	print_textarea_row($vbphrase['dbtech_vbshop_shop_logo'], 			'shop[logo]', 				$shop['logo']);
	/*DBTECH_PRO_START*/
	print_yes_no_row($vbphrase['dbtech_vbshop_canhavefeedback'],		'shop[canhavefeedback]',	$shop['canhavefeedback']);
	print_input_row($vbphrase['dbtech_vbshop_shop_owner'], 				'shop[ownerid]', 			$shop['ownerid']);
	print_input_row($vbphrase['dbtech_vbshop_shop_beneficiary'], 		'shop[beneficiary]', 		$shop['beneficiary']);
	print_input_row($vbphrase['dbtech_vbshop_shop_beneficiary_split'], 	'shop[beneficiary_split]', 	$shop['beneficiary_split']);
	/*DBTECH_PRO_END*/
	print_description_row($vbphrase['permissions'], false, 2, 'optiontitle');	
	print_cells_row($headings, 0, 'thead');	
	foreach ($vbulletin->usergroupcache as $usergroupid => $usergroup)
	{
		print_yes_no_other_row($usergroup['title'], 			'shop[permissions][' . $usergroupid . ']', $vbphrase['default'], (isset($shop['permissions'][$usergroupid]) ? $shop['permissions'][$usergroupid] : -1));
	}
	/*
	print_description_row($vbphrase['dbtech_vbshop_items'], false, 2, 'optiontitle');
	print_item_row($vbphrase['dbtech_vbshop_sold_items'], 	'items', $inventory);
	 */
	print_submit_row(($shopid ? $vbphrase['save'] : $vbphrase['dbtech_vbshop_add_new_shop']));	
}

// #############################################################################
if ($_REQUEST['action'] == 'update')
{
	// Grab stuff
	$vbulletin->input->clean_array_gpc('p', array(
		'shopid' 	=> TYPE_UINT,
		'shop' 		=> TYPE_ARRAY,
		'items' 	=> TYPE_ARRAY,
	));
	
	// init data manager
	$dm =& VBSHOP::initDataManager('Shop', $vbulletin, ERRTYPE_CP);
	
	// 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
			print_stop_message('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_shop'], $vbulletin->GPC['shopid']);
		}
		
		// Set existing
		$dm->set_existing($existing);
				
		// Added
		$phrase = $vbphrase['dbtech_vbshop_edited'];
	}
	else
	{
		// Added
		$phrase = $vbphrase['dbtech_vbshop_added'];
	}
	
	// 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.
	$shopid = $dm->save();
	unset($dm);

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

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

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

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

		foreach ($vbulletin->GPC['items'][$itemid] AS $key => $val)
		{
			if (!$inventory[$itemid] OR $inventory[$itemid][$key] != $val)
			{
				// Only set changed values
				$dm->set($key, $val);
			}
		}
		$dm->save();
		unset($dm);
	}
	 */
		
	define('CP_REDIRECT', 'vbshop.php?do=shop');
	print_stop_message('dbtech_vbshop_x_y', $vbphrase['dbtech_vbshop_shop'], $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 $shopid => $displayorder)
		{
			if (!$existing = VBSHOP::$cache['shop']["$shopid"])
			{
				// Couldn't find the shop
				continue;
			}
			
			if ($existing['displayorder'] == $displayorder)
			{
				// No change
				continue;
			}
			
			// init data manager
			$dm =& VBSHOP::initDataManager('Shop', $vbulletin, ERRTYPE_CP);
				$dm->set_existing($existing);
				$dm->set('displayorder', $displayorder);
			$dm->save();
			unset($dm);	
		}
	}
	
	define('CP_REDIRECT', 'vbshop.php?do=shop');
	print_stop_message('saved_display_order_successfully');	
}

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

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

print_cp_footer();