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

class vBShop_Item_smilie 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_smilie';
	}
	
	/**
	* 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);
							$this->registry->input->clean_gpc('f', 'upload', 		TYPE_FILE);
		
		if ($noConfigure)
		{
			// We're done, we wanted to let the recipient configure it themselves
			return true;
		}

		if (!$code['smilietext'])
		{
			// No smilie text
			return false;
		}

		$code['smiliepath_insert'] = false;
		if ($code['smilieurl'] == '' OR $code['smilieurl'] == 'http://www.')
		{
			if (!is_uploaded_file($this->registry->GPC['upload']['tmp_name']) AND $code['smilieid'])
			{
				$code['smiliepath_insert'] = $this->config['configuration']['smiliepath_insert'];
			}
		}

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

		if (!$code['smiliepath_insert'])
		{
			require_once(DIR . '/includes/class_upload.php');
			require_once(DIR . '/includes/class_image.php');

			// Begin the upload
			$upload = new vB_Upload_Image($this->registry);
			$upload->image =& vB_Image::fetch_library($this->registry);
			$upload->path = DIR . '/dbtech/vbshop/images/smilies';
			$upload->maxwidth = $this->registry->options['dbtech_vbshop_smilies_maxwidth'];
			$upload->maxheight = $this->registry->options['dbtech_vbshop_smilies_maxheight'];
			if (!$code['smiliepath'] = $upload->process_upload($code['smilieurl']))
			{
				eval(standard_error(fetch_error('there_were_errors_encountered_with_your_upload_x', $upload->fetch_error())));
			}
			$code['smiliepath_insert'] = $this->registry->options['bburl'] . str_replace(DIR, '', $code['smiliepath']);

			if ($this->config['configuration']['smiliepath'] AND $code['smiliepath'] != $this->config['configuration']['smiliepath'])
			{
				// Get rid of old image
				@unlink($this->config['configuration']['smiliepath']);
			}
		}

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

		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'],
						implode("\n", array(
							$vbphrase['title'] . ': ' . $code['title'],
							$vbphrase['text_to_replace'] . ': ' . $code['smilietext'],
							$vbphrase['smilie_file_path'] . ': ' . $code['smiliepath']
						))
					)
				);
			}
		}
		
		// 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);				
	}	

	/**
	* Form to purchase an item
	*/	
	public function render()
	{
		$categories = VBSHOP::$db->fetchAll('
			SELECT imagecategoryid, title
			FROM $imagecategory
			WHERE imagetype = ?
			ORDER BY displayorder
		', array(
			3
		));

		if (!count($categories))
		{
			// Couldn't render
			return '';
		}

		foreach ($categories as $category)
		{
			// Create the number option template
			$templater = vB_Template::create('option');
				$templater->register('optionvalue', 	$category['imagecategoryid']);
				$templater->register('optiontitle', 	$category['title']);
				$templater->register('optionselected', 	($this->config['configuration']['imagecategoryid'] == $category['imagecategoryid'] ? 'selected="selected"' : ''));
			$this->config['imagecategoryoptions'] .= $templater->render();
		}

		return parent::render();
	}

	/**
	* Build the perms
	*/	
	protected function build_image_permissions($table)
	{
		$output = array();

		if ($table != 'avatar' AND $table != 1)
		{
			return $output;
		}

		$categories = $this->registry->db->query_read_slave("
			SELECT imagecategory.imagecategoryid, COUNT(avatarid) AS avatars
			FROM " . TABLE_PREFIX . "imagecategory AS imagecategory
			LEFT JOIN " . TABLE_PREFIX . "avatar AS avatar ON (avatar.imagecategoryid=imagecategory.imagecategoryid)
			WHERE imagetype = 1
			GROUP BY imagecategory.imagecategoryid
			HAVING avatars > 0
		");

		$cats = array();
		while ($cat = $this->registry->db->fetch_array($categories))
		{
				$cats[] = $cat['imagecategoryid'];
		}

		if (!empty($cats))
		{
			$noperms = $this->registry->db->query_read_slave("
				SELECT usergroupid, COUNT(*) AS count
				FROM " . TABLE_PREFIX . "imagecategorypermission
				WHERE imagecategoryid IN (" . implode(',', $cats) . ")
				GROUP BY usergroupid
				HAVING count = " . count($cats) . "
			");
			while ($noperm = $this->registry->db->fetch_array($noperms))
			{
				$output[] = $noperm['usergroupid'];
			}
		}
		else	// No Avatars?
		{
			$output['all'] = true;
		}

		build_datastore('noavatarperms', serialize($output), 1);
		return $output;
	}
}
?>