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

class vBShop_Item_smiliecategory 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);
		
		// Set purchase template
		$this->config['purchasetemplate'] = 'dbtech_vbshop_configure_smiliecategory';
	}
	
	/**
	* Function to call before every action
	*/	
	public function action()
	{
		if (!parent::action())
		{
			// This type is inactive
			return false;
		}
		
		// We made it!
		return true;
	}
	
	/**
	* Configure an item
	*
	* @param	integer		Purchase ID
	* @param	mixed		Recipient
	*/	
	public function configure($purchaseid, $recipient = null)
	{
		global $vbphrase;
		
		if (!$this->can_configure($purchaseid))
		{
			// Can't configure this item
			return false;
		}
		
		// Ensure this is set
		$recipient = (!$recipient ? $this->registry->userinfo : $recipient);
		
		// Get the form code
		$code 			= $this->registry->input->clean_gpc('p', 'code', 			TYPE_ARRAY);
		$noConfigure 	= $this->registry->input->clean_gpc('p', '_noConfigure', 	TYPE_BOOL);
		
		if ($noConfigure)
		{
			// We're done, we wanted to let the recipient configure it themselves
			return true;
		}

		if (!function_exists('build_image_cache'))
		{
			require_once(DIR . '/includes/adminfunctions.php');
		}

		if ($code['imagecategoryid'])
		{
			if ($this->config['configuration']['imagecategoryid'] == $code['imagecategoryid'])
			{
				// Update category title
				VBSHOP::$db->update('imagecategory', array(
					'title' => fetch_censored_text($code['title'])
				), 'WHERE imagecategoryid = ' . intval($this->config['configuration']['imagecategoryid']));
				build_image_cache('imagecategory');
			}
		}
		else
		{
			// Add new category
			$code['imagecategoryid'] = VBSHOP::$db->insert('imagecategory', array(
				'title' => fetch_censored_text($code['title']),
				'imagetype' => 3,
				'displayorder' => 1
			));
			build_image_cache('imagecategory');
		}

		if ($this->config['notifications_config'])
		{
			$userids = explode(',', $this->config['notifications_config']);
			foreach ((array)$userids as $userid)
			{
				// Send PM
				VBSHOP::sendPM(
					$userid,
					construct_phrase($vbphrase['dbtech_vbshop_new_configuration_x'],
						$this->config['title']
					),
					construct_phrase($vbphrase['dbtech_vbshop_x_just_configured_y'],
						$recipient['username'],
						$this->config['title'],
						$vbphrase['title'] . ': ' . $code['title']
					)
				);
			}
		}
		
		// Update flag
		$this->registry->db->query_write("
			UPDATE " . TABLE_PREFIX . "dbtech_vbshop_purchase
			SET configuration = " . $this->registry->db->sql_prepare(trim(serialize($code))) . "
			WHERE purchaseid = " . intval($purchaseid) . "
		");
		
		// Build purchase cache
		VBSHOP::build_purchases($recipient);				
	}	
}
?>