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

class vBShop_Item_forumpermission extends vBShop_Item_Core
{	
	/**
	* The constructor
	*
	* @param	vBulletin	vBulletin registry
	* @param	array		Item info
	*/	
	public function __construct(&$registry, &$item)
	{
		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_forum_chooser($vbphrase['dbtech_vbshop_permission_value'], 'item[code][value]', $code['value']);
	}
	
	/**
	* 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;
		}
		
		$this->registry->db->query_write("
			REPLACE INTO " . TABLE_PREFIX . "access
				(userid, forumid, accessmask)
			VALUES (" . $recipient['userid'] . ", " . intval($this->config['code']['value']) . ", 1)
		");
		$this->registry->db->query_write("
			UPDATE " . TABLE_PREFIX . "user
			SET options = (options + " . $this->registry->bf_misc_useroptions['hasaccessmask'] . ")
			WHERE userid = " . $recipient['userid'] . " 
				AND NOT (options & " . $this->registry->bf_misc_useroptions['hasaccessmask'] . ")
		");	
	}
	
	/**
	* Deactivate an item
	*
	* @param	integer		Purchase ID
	* @param	mixed		Recipient
	*/	
	public function deactivate($purchaseid, $recipient = null, $dorebuild = true)
	{
		global $vbphrase;
		
		// Ensure this is set
		$recipient = (!$recipient ? $this->registry->userinfo : $recipient);		
		
		// Ensure this gets ran
		if (!parent::deactivate($purchaseid, $recipient, $dorebuild))
		{
			// Couldn't deactivate
			return false;
		}
		
		$this->registry->db->query_write("
			DELETE FROM " . TABLE_PREFIX . "access
			WHERE userid = " . $recipient['userid'] . "
				AND forumid = " . intval($this->config['code']['value']) . "
		");
	}
}
?>