<?php
if (!class_exists('vBShop_Item_Core'))
{
	die('No direct access allowed.');
}

class vBShop_Item_usergroupchange extends vBShop_Item_Core
{	
	/**
	* The constructor
	*
	* @param	vBulletin	vBulletin registry
	* @param	array		Item info
	*/	
	public function __construct(&$registry, &$item)
	{
		$item['_nodeactivate'] = true;
		parent::__construct($registry, $item);
	}
	
	/**
	* Function to call before every action
	*/	
	public function action()
	{
		if (!parent::action())
		{
			// This type is inactive
			return false;
		}
		
		// We made it!
		return true;
	}
	
	/**
	* Prints out an AdminCP form
	*/	
	public function print_admin_form($code)
	{
		global $vbphrase;
		
		// Finally print the select
		print_chooser_row($vbphrase['dbtech_vbshop_usergroup'], 	'item[code][usergroupid]', 'usergroup', 	$code['usergroupid']);
		print_select_row($vbphrase['dbtech_vbshop_ug_type'], 		'item[code][ugtype]', array(
				'primary' 	=> $vbphrase['primary_usergroup'],
				'secondary' => $vbphrase['dbtech_vbshop_secondary_usergroup'],
			),
			$code['ugtype']
		);
		print_select_row($vbphrase['dbtech_vbshop_ug_addremove'], 	'item[code][addremove]', array(
				'add' 		=> $vbphrase['add'],
				'remove' 	=> $vbphrase['remove'],
			),
			$code['addremove']
		);
	}
	
	/**
	* Activate an item
	*
	* @param	integer		Purchase ID
	* @param	mixed		Recipient
	*/	
	public function activate($purchaseid, $recipient = null, $dorebuild = true)
	{
		global $vbphrase;
		
		// Ensure this is set
		$recipient = (!$recipient ? $this->registry->userinfo : $recipient);
		
		// Ensure this gets ran
		if (!parent::activate($purchaseid, $recipient, $dorebuild))
		{
			// Couldn't activate
			return false;
		}
		
		// Change the username
		$userdata =& datamanager_init('User', $this->registry, ERRTYPE_STANDARD);
		$userdata->set_existing($recipient);
		
		if ($this->config['code']['ugtype'] == 'primary')
		{
			// Primary UG
			$userdata->set('usergroupid', $this->config['code']['usergroupid']);
		}
		else
		{
			// Secondary UG
			$membergroupids = explode(',', $recipient['membergroupids']);
			
			if ($this->config['code']['addremove'] == 'add')
			{
				$key = array_search($this->config['code']['usergroupid'], $membergroupids);
				if ($key === false)
				{
					// Add it
					$membergroupids[] = $this->config['code']['usergroupid'];
					
					// Save the new membergroupds
					$userdata->set('membergroupids', implode(',', $membergroupids));
				}
			}
			else
			{
				$key = array_search($this->config['code']['usergroupid'], $membergroupids);
				if ($key !== false)
				{
					// Git rid of it!
					unset($membergroupids["$key"]);
					
					// Save the membergroups!
					$membergroupids = (empty($membergroupids) ? '' : implode(',', $membergroupids));
					$userdata->set('membergroupids', $membergroupids);
				}
			}
		}
		
		$userdata->save();
	}	
}
?>