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

class vBShop_Item_threadban extends vBShop_Item_Core
{
	/**
	* The constructor
	*
	* @param	vBulletin	vBulletin registry
	* @param	array		Item info
	*/	
	public function __construct(&$registry, &$item)
	{
		parent::__construct($registry, $item);
		
		// Set purchase template
		$this->config['purchasetemplate'] = 'dbtech_vbshop_configure_threadban';
	}
	
	/**
	* 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;
		
		print_forum_chooser($vbphrase['dbtech_vbshop_excluded_forums'], 		'item[code][excludedforums][]', $code['excludedforums'], NULL, true, true);
		print_membergroup_row($vbphrase['dbtech_vbshop_excluded_usergroups'], 	'item[code][excludedgroups]', 2, array('membergroupids' => implode(',', (array)$code['excludedgroups'])));
	}
	
	/**
	* Activate an item
	*
	* @param	integer		Purchase ID
	* @param	mixed		Recipient
	*/	
	public function activate($purchaseid, $recipient = NULL, $dorebuild = true)
	{
		if (!parent::activate($purchaseid, $recipient, $dorebuild))
		{
			// Couldn't deactivate
			return false;
		}

		if (!$this->config['configuration']['threadid'])
		{
			// Nothin configured
			return true;
		}

		if (!$this->config['configuration']['userid'])
		{
			// Nothin configured
			return true;
		}

		$this->saveThreadBan(
			$this->config['configuration']['threadid'],
			$this->config['configuration']['userid']
		);
		
		return true;
	}

	/**
	* Deactivate an item
	*
	* @param	integer		Purchase ID
	* @param	mixed		Recipient
	*/	
	public function deactivate($purchaseid, $recipient = null, $dorebuild = true)
	{
		if (!parent::deactivate($purchaseid, $recipient, $dorebuild))
		{
			// Couldn't deactivate
			return false;
		}

		if (!$this->config['configuration']['threadid'])
		{
			// Nothin configured
			return true;
		}

		if (!$this->config['configuration']['userid'])
		{
			// Nothin configured
			return true;
		}

		$this->deleteThreadBan(
			$this->config['configuration']['threadid'],
			$this->config['configuration']['userid']
		);	
		
		return true;
	}

	/**
	* Form to purchase an item
	*/	
	public function render()
	{
		// Grab the username again
		$this->config['configuration']['username'] = VBSHOP::$db->fetchOne('
			SELECT username FROM $user WHERE userid = ?
		', array(
			$this->config['configuration']['userid']
		));

		return parent::render();
	}	
	
	/**
	* 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 ($code['threadid'] AND $code['username'])
		{
			$username = $code['username'];

			$threadinfo = fetch_threadinfo($code['threadid']);
			if (!$threadinfo OR in_array($threadinfo['forumid'], $this->config['code']['excludedforums']))
			{
				// Excluded forum
				eval(standard_error(fetch_error('dbtech_vbshop_invalid_data', $vbphrase['dbtech_vbshop_thread_id'])));
			}

			if (!$user = VBSHOP::$db->fetchRow('SELECT userid, usergroupid, membergroupids FROM $user WHERE username = ?', array(htmlspecialchars_uni($code['username']))))
			{
				// Excluded user
				eval(standard_error(fetch_error('dbtech_vbshop_invalid_data', $vbphrase['username'])));
			}

			if (is_member_of($user, $this->config['code']['excludedgroups']))
			{
				// Excluded user
				eval(standard_error(fetch_error('dbtech_vbshop_invalid_data', $vbphrase['username'])));
			}

			// Store this
			$code['userid'] = $user['userid'];

			if (
				($this->config['configuration']['threadid'] != $code['threadid'] AND $this->config['configuration']['threadid']) OR
				($this->config['configuration']['userid'] != $code['userid'] AND $this->config['configuration']['userid'])
			)
			{
				// Remove old ban
				$this->deleteThreadBan(
					$this->config['configuration']['threadid'],
					$this->config['configuration']['userid']
				);
			}

			if ((
				($this->config['configuration']['threadid'] != $code['threadid']) OR
				($this->config['configuration']['userid'] != $code['userid'])
			) AND $this->config['active'])
			{			
				// Set new ban
				$this->saveThreadBan(
					$code['threadid'],
					$code['userid']
				);
			}

			unset($code['username']);
		}
		else
		{
			if ($this->config['configuration']['threadid'] AND $this->config['configuration']['userid'])
			{
				// Remove old ban
				$this->deleteThreadBan(
					$this->config['configuration']['threadid'],
					$this->config['configuration']['userid']
				);
			}
		}

		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['dbtech_vbshop_thread_id'] . ': ' . intval($code['threadid']) . "\n" .
						$vbphrase['username'] . ': ' . $username
					)
				);
			}
		}
		
		// 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);				
	}

	/**
	* Save thread ban
	*/
	protected function saveThreadBan($threadId, $userId)
	{
		VBSHOP::$db->insert('dbtech_vbshop_threadban', array(
			'threadid' => $threadId,
			'userid' => $userId
		));
	}

	/**
	* Delete thread ban
	*/
	protected function deleteThreadBan($threadId, $userId)
	{
		VBSHOP::$db->delete('dbtech_vbshop_threadban', array(
			$threadId,
			$userId
		), 'WHERE threadid = ? AND userid = ?');
	}
}
?>