<?php
/*======================================================================*\
|| #################################################################### ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2013 Fillip Hannisdal AKA Revan/NeoRevan/Belazor 	  # ||
|| # All Rights Reserved. 											  # ||
|| # This file may not be redistributed in whole or significant item. # ||
|| # ---------------------------------------------------------------- # ||
|| # You are not allowed to use this on your server unless the files  # ||
|| # you downloaded were done so with permission.					  # ||
|| # ---------------------------------------------------------------- # ||
|| #################################################################### ||
\*======================================================================*/

// #############################################################################
if ($_REQUEST['action'] == 'inventory' OR empty($_REQUEST['action']))
{
	$items_by_category = array();
	foreach ((array)VBSHOP::$cache['item'] as $itemid => $item)
	{
		// Create array of items
		$items_by_category[VBSHOP::$cache['category'][$item['categoryid']]['title']][$itemid] = $item['title'];
	}
	
	print_cp_header($vbphrase['dbtech_vbshop_purchase_list']);
	
	print_form_header('vbshop', 'inventory');
	construct_hidden_code('action', 'update');
	print_table_header($vbphrase['dbtech_vbshop_add_new_item']);
	print_input_row($vbphrase['user_name'], 							'inventory[username]');
	print_select_row($vbphrase['dbtech_vbshop_item'], 					'inventory[featureid]', $items_by_category);
	print_submit_row($vbphrase['dbtech_vbshop_add_new_item'], false);	
	
	print_form_header('vbshop', 'inventory');
	construct_hidden_code('action', 'massadd');
	print_table_header($vbphrase['dbtech_vbshop_mass_add_new_item']);	
	print_chooser_row($vbphrase['usergroup'], 'usergroupid', 'usergroup', -1, $vbphrase['all_usergroups']);
	print_select_row($vbphrase['dbtech_vbshop_item'], 					'itemid', $items_by_category);
	print_input_row($vbphrase['number_of_users_to_process_per_cycle'], 'perpage', 1000);	
	print_submit_row($vbphrase['dbtech_vbshop_mass_add_new_item'], false);	


	$items_by_category = array(
		'N/A' => array(
			0 => $vbphrase['all']
		)
	);
	foreach ((array)VBSHOP::$cache['item'] as $itemid => $item)
	{
		// Create array of items
		$items_by_category[VBSHOP::$cache['category'][$item['categoryid']]['title']][$itemid] = $item['title'];
	}

	// ###################### Start modify #######################
	print_form_header('vbshop', 'inventory');
	construct_hidden_code('action', 'view');
	print_table_header($vbphrase['dbtech_vbshop_purchase_list']);
	print_input_row($vbphrase['log_entries_to_show_per_page'], 'perpage', 100);
	print_input_row($vbphrase['user_name'], 'username');
	print_select_row($vbphrase['order_by'], 'orderby', array(
		'username' 	=> $vbphrase['user_name'],
		'title' 	=> $vbphrase['dbtech_vbshop_item'],
	), 'date');
	print_select_row($vbphrase['dbtech_vbshop_item'], 					'itemid', $items_by_category, 0);
	print_submit_row($vbphrase['view'], 0);
}

// #############################################################################
if ($_REQUEST['action'] == 'update')
{
	// Grab stuff
	$vbulletin->input->clean_array_gpc('p', array(
		'inventory' => TYPE_ARRAY,
	));

	// Check username
	if (!$vbulletin->GPC['inventory']['userid'] = VBSHOP::$db->fetchOne('SELECT userid FROM $user WHERE username = ?', array(htmlspecialchars_uni($vbulletin->GPC['inventory']['username']))))
	{
		// no users found!
		print_stop_message('no_users_matched_your_query');
	}
	
	// Get rid of username
	unset($vbulletin->GPC['inventory']['username']);	
	
	// Set some hardcoded things
	$vbulletin->GPC['inventory']['buyer'] 		= $vbulletin->userinfo['userid'];
	$vbulletin->GPC['inventory']['feature'] 	= 'item';
	$vbulletin->GPC['inventory']['dateline'] 	= TIMENOW;
	$vbulletin->GPC['inventory']['active'] 		= 0;
	$vbulletin->GPC['inventory']['hidden'] 		= 1;

	// Insert item
	VBSHOP::$db->insert('dbtech_vbshop_purchase', $vbulletin->GPC['inventory']);

	// Required by reference
	$user = array('userid' => $vbulletin->GPC['inventory']['userid']);

	// Rebuild the cache
	VBSHOP::build_purchases($user);	
	
	define('CP_REDIRECT', 'vbshop.php?do=inventory');
	print_stop_message('dbtech_vbshop_x_y', $vbphrase['dbtech_vbshop_item'], $vbphrase['dbtech_vbshop_added']);
}

// #############################################################################
if ($_REQUEST['action'] == 'massadd')
{
	print_cp_header($vbphrase['dbtech_vbshop_purchase_list']);

	@set_time_limit(0);
	ignore_user_abort(1);

	// Grab stuff
	$vbulletin->input->clean_array_gpc('r', array(
		'itemid' 		=> TYPE_UINT,
		'usergroupid' 	=> TYPE_INT,
		'perpage' 		=> TYPE_UINT,
		'startat' 		=> TYPE_UINT,		
	));

	$users = VBSHOP::$db->fetchAllSingleKeyed('
		SELECT userid
		FROM $user
		WHERE userid >= ?
			' . ($vbulletin->GPC['usergroupid'] > 0 ? 'AND (usergroupid = ' . $vbulletin->GPC['usergroupid'] . ' OR FIND_IN_SET(' . $vbulletin->GPC['usergroupid'] . ', membergroupids))' : '') . '
		LIMIT :perPage
	', 'userid', 'userid', array(
		':perPage' => $vbulletin->GPC['perpage'],
		$vbulletin->GPC['startat']
	));
	
	$finishat = $vbulletin->GPC['startat'];
	
	foreach ($users as $userid)
	{
		echo construct_phrase($vbphrase['processing_x'], $userid) . "<br />\n";
		vbflush();
	
		// Insert item
		VBSHOP::$db->insert('dbtech_vbshop_purchase', array(
			'userid' 		=> $userid,
			'buyer' 		=> $vbulletin->userinfo['userid'],
			'feature' 		=> 'item',
			'featureid' 	=> $vbulletin->GPC['itemid'],			
			'dateline'	 	=> TIMENOW,
			'active' 		=> 0,
			'hidden' 		=> 1,
		));

		// Required by reference
		$user = array('userid' => $userid);

		// Rebuild the cache
		VBSHOP::build_purchases($user);

		$finishat = ($userid > $finishat ? $userid : $finishat);		
	}
	$finishat++;

	if ($checkmore = VBSHOP::$db->fetchOne('
		SELECT userid
		FROM $user
		WHERE userid >= ?
			' . ($vbulletin->GPC['usergroupid'] > 0 ? 'AND (usergroupid = ' . $vbulletin->GPC['usergroupid'] . ' OR FIND_IN_SET(' . $vbulletin->GPC['usergroupid'] . ', membergroupids))' : '') . '
		LIMIT 1
	', array(
		$finishat
	)))
	{
		print_cp_redirect("vbshop.php?" . $vbulletin->session->vars['sessionurl'] . "do=inventory&action=massadd&startat=$finishat&pp=" . $vbulletin->GPC['perpage'] . "&itemid=" . $vbulletin->GPC['itemid'] . "&usergroupid=" . $vbulletin->GPC['usergroupid']);
		echo "<p><a href=\"vbshop.php?" . $vbulletin->session->vars['sessionurl'] . "do=inventory&amp;action=massadd&amp;startat=$finishat&amp;pp=" . $vbulletin->GPC['perpage'] . "&amp;itemid=" . $vbulletin->GPC['itemid'] . "&amp;usergroupid=" . $vbulletin->GPC['usergroupid'] . "\">" . $vbphrase['click_here_to_continue_processing'] . "</a></p>";
	}
	else
	{
		define('CP_REDIRECT', 'vbshop.php?do=inventory');
		print_stop_message('dbtech_vbshop_x_y', $vbphrase['dbtech_vbshop_item'], $vbphrase['dbtech_vbshop_added']);
	}	
}

// #############################################################################
if ($_REQUEST['action'] == 'view')
{
	print_cp_header($vbphrase['dbtech_vbshop_purchase_list']);
	
	$vbulletin->input->clean_array_gpc('r', array(
		'perpage' 		=> TYPE_UINT,
		'pagenumber' 	=> TYPE_UINT,
		'orderby' 		=> TYPE_NOHTML,
		'username' 		=> TYPE_STR,
		'itemid' 		=> TYPE_UINT,
	));
	
	$sqlconds = array();
	
	if ($vbulletin->GPC['perpage'] < 1)
	{
		$vbulletin->GPC['perpage'] = 15;
	}
	
	if ($vbulletin->GPC['itemid'])
	{
		$sqlconds[] = 'inventory.featureid = ' . intval($vbulletin->GPC['itemid']);
	}

	if ($vbulletin->GPC['username'])
	{
		$sqlconds[] = "user.username LIKE '%" . $db->escape_string_like(htmlspecialchars_uni($vbulletin->GPC['username'])) . "%'";
	}
	$sqlconds[] = 'inventory.feature = \'item\'';

	$counter = VBSHOP::$db->fetchOne('
		SELECT COUNT(*) AS total
		FROM $dbtech_vbshop_purchase AS inventory
		LEFT JOIN $user AS user ON(user.userid = inventory.userid)
		:where
	', array(
		':where' 			=> (!empty($sqlconds) ? 'WHERE ' . implode("\r\n\tAND ", $sqlconds) : ''),
	));
	$totalpages = ceil($counter / $vbulletin->GPC['perpage']);
	
	if ($vbulletin->GPC['pagenumber'] < 1)
	{
		$vbulletin->GPC['pagenumber'] = 1;
	}
	$startat = ($vbulletin->GPC['pagenumber'] - 1) * $vbulletin->GPC['perpage'];
	
	switch($vbulletin->GPC['orderby'])
	{
		case 'title':
			$order = 'item.title ASC, user.username ASC';
			break;
		default:		
		case 'username':
			$order = 'user.username ASC';
	}
	
	// Query the messages
	$logs = VBSHOP::$db->fetchAllKeyed('
		SELECT inventory.*, item.title, user.username
		FROM $dbtech_vbshop_purchase AS inventory
		LEFT JOIN $user AS user ON(user.userid = inventory.userid)
		LEFT JOIN $dbtech_vbshop_item AS item ON(item.itemid = inventory.featureid)
		:where
		ORDER BY :order
		LIMIT :limitStart, :limitEnd
	', 'inventoryid', array(
		':where' 			=> (!empty($sqlconds) ? 'WHERE ' . implode("\r\n\tAND ", $sqlconds) : ''),
		':order' 			=> $order,
		':limitStart' 		=> $startat,
		':limitEnd' 		=> $vbulletin->GPC['perpage']
	));
	
	if (count($logs))
	{
		if ($vbulletin->GPC['pagenumber'] != 1)
		{
			$prv = $vbulletin->GPC['pagenumber'] - 1;
			$firstpage = "<input type=\"button\" class=\"button\" value=\"&laquo; " . $vbphrase['first_page'] . "\" tabindex=\"1\" onclick=\"window.location='vbshop.php?" . $vbulletin->session->vars['sessionurl'] . "do=inventory&action=view&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&page=1&username=" . urlencode($vbulletin->GPC['username']) . "&itemid=" . $vbulletin->GPC['itemid'] ."'\">";
			$prevpage = "<input type=\"button\" class=\"button\" value=\"&lt; " . $vbphrase['prev_page'] . "\" tabindex=\"1\" onclick=\"window.location='vbshop.php?" . $vbulletin->session->vars['sessionurl'] . "do=inventory&action=view&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&page=$prv&username=" . urlencode($vbulletin->GPC['username']) . "'\">";
		}
	
		if ($vbulletin->GPC['pagenumber'] != $totalpages)
		{
			$nxt = $vbulletin->GPC['pagenumber'] + 1;
			$nextpage = "<input type=\"button\" class=\"button\" value=\"" . $vbphrase['next_page'] . " &gt;\" tabindex=\"1\" onclick=\"window.location='vbshop.php?" . $vbulletin->session->vars['sessionurl'] . "do=inventory&action=view&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&page=$nxt&username=" . urlencode($vbulletin->GPC['username']) ."&itemid=" . $vbulletin->GPC['itemid'] ."'\">";
			$lastpage = "<input type=\"button\" class=\"button\" value=\"" . $vbphrase['last_page'] . " &raquo;\" tabindex=\"1\" onclick=\"window.location='vbshop.php?" . $vbulletin->session->vars['sessionurl'] . "do=inventory&action=view&pp=" . $vbulletin->GPC['perpage'] . "&orderby=" . $vbulletin->GPC['orderby'] . "&page=$totalpages&username=" . urlencode($vbulletin->GPC['username']) . "&itemid=" . $vbulletin->GPC['itemid'] ."'\">";
		}
		
		$headings = array();
		$headings[] = $vbphrase['id'];
		$headings[] = $vbphrase['title'];
		$headings[] = $vbphrase['user_name'];
		$headings[] = $vbphrase['delete'];
	
		print_form_header('vbshop', 'view');
		print_description_row(construct_link_code($vbphrase['restart'], "vbshop.php?" . $vbulletin->session->vars['sessionurl'] . "do=inventory"), false, count($headings), 'thead', 'right');
		print_table_header(construct_phrase($vbphrase['dbtech_vbshop_purchase_list_page_x_y_there_are_z_total_log_entries'], vb_number_format($vbulletin->GPC['pagenumber']), vb_number_format($totalpages), vb_number_format($counter)), count($headings));
		print_cells_row($headings, 1);
		
		foreach ($logs as $log)
		{			
			$cell = array();
			$cell[] = $log['purchaseid'];
			$cell[] = $log['title'];
			$cell[] = '<span class="smallfont">' . $log['username'] . '</span>';
			$cell[] = construct_link_code($vbphrase['delete'], 'vbshop.php?' . $vbulletin->session->vars['sessionurl'] . 'do=inventory&amp;action=delete&amp;purchaseid=' . $log['purchaseid'] . '&amp;userid=' . $log['userid']);

			print_cells_row($cell, false, false, 0, 'top', false, true);
		}
	
		print_table_footer(count($headings), "$firstpage $prevpage &nbsp; $nextpage $lastpage");
	}
	else
	{
		print_stop_message('no_results_matched_your_query');
	}
}

// #############################################################################
if ($_REQUEST['action'] == 'delete')
{
	$vbulletin->input->clean_gpc('r', 'purchaseid', TYPE_UINT);
	$vbulletin->input->clean_gpc('r', 'userid', TYPE_UINT);

	print_cp_header(construct_phrase($vbphrase['dbtech_vbshop_delete_x'], $vbphrase['dbtech_vbshop_purchase']));
	print_delete_confirmation('dbtech_vbshop_purchase', $vbulletin->GPC['purchaseid'], 'vbshop', 'inventory', 'dbtech_vbshop_item', array('action' => 'kill', 'userid' => $vbulletin->GPC['userid']), '', 'purchaseid', 'purchaseid');
	print_cp_footer();
}

// #############################################################################
if ($_POST['action'] == 'kill')
{
	$vbulletin->input->clean_gpc('r', 'purchaseid', TYPE_UINT);
	$vbulletin->input->clean_gpc('r', 'userid', TYPE_UINT);
	
	if (!$existing = VBSHOP::$db->fetchRow('SELECT * FROM $dbtech_vbshop_purchase WHERE userid = ? AND purchaseid = ?', array($vbulletin->GPC['userid'], $vbulletin->GPC['purchaseid'])))
	{
		// Couldn't find the inventory item
		print_stop_message('dbtech_vbshop_invalid_x', $vbphrase['dbtech_vbshop_item'], $vbulletin->GPC['purchaseid']);
	}

	// Construct the array proper
	$existing = array_merge(VBSHOP::$cache[$existing['feature']][$existing['featureid']], $existing);
	
	// Init the item
	$itemobj = VBSHOP::init_item($existing);
	
	// Discard the item
	$itemobj->discard($existing['purchaseid'], array('userid' => $existing['userid']));	
	
	define('CP_REDIRECT', 'vbshop.php?do=inventory');
	print_stop_message('dbtech_vbshop_x_y', $vbphrase['dbtech_vbshop_item'], $vbphrase['dbtech_vbshop_deleted']);	
}

print_cp_footer();