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

class vBShop_Item_firemoderator 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_firemoderator';

		if (!function_exists('can_administer'))
		{
			require_once(DIR . '/includes/adminfunctions.php');
		}
	}
	
	/**
	* 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_yes_no_row($vbphrase['dbtech_vbshop_allow_unfire'], 'item[code][unfire]', $code['unfire']);		
		print_description_row($vbphrase['moderators'], false, 2, 'optiontitle');

		$mods = VBSHOP::$db->fetchAll('
			SELECT moderator.*, user.username
			FROM $moderator AS moderator
			LEFT JOIN $user AS user USING (userid)
			WHERE moderator.forumid != -1
		');
		foreach ($mods as $moderator)
		{
			print_checkbox_row($moderator['username'] . ' (' . $this->registry->forumcache[$moderator['forumid']]['title'] . ')', 'item[code][mods][' . $moderator['moderatorid'] . ']', $code['mods'][$moderator['moderatorid']]);
		}
	}

	/**
	* 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']['moderatorid'])
		{
			// Nothin configured
			return true;
		}

		// Ensure this is set
		$recipient = ($recipient === NULL ? $this->registry->userinfo : $recipient);		

		$moderator = VBSHOP::$db->fetchRow('
			SELECT moderator.*, user.username
			FROM $moderator AS moderator
			LEFT JOIN $user AS user USING (userid)
			WHERE moderatorid = ?
		', array(
			$this->config['configuration']['moderatorid']
		));
		if (!$moderator OR !in_array($moderator['moderatorid'], array_keys($this->config['code']['mods'])))
		{
			// Excluded forum
			return true;
		}

		// Back this up
		$this->config['configuration']['moderatordata'] = $moderator;
		unset($this->config['configuration']['moderatordata']['moderatorid']);

		$moddata =& datamanager_init('Moderator', $this->registry, ERRTYPE_SILENT);
		$moddata->set_existing($moderator);
		$moddata->delete(true);
		unset($moddata);

		// Update flag
		$this->registry->db->query_write("
			UPDATE " . TABLE_PREFIX . "dbtech_vbshop_purchase
			SET configuration = " . $this->registry->db->sql_prepare(trim(serialize($this->config['configuration']))) . "
			WHERE purchaseid = " . intval($purchaseid) . "
		");
		
		// Build purchase cache
		VBSHOP::build_purchases($recipient);
		
		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']['moderatorid'] OR !$this->config['code']['unfire'])
		{
			// Nothin configured
			return true;
		}

		// Restore the moderator
		$this->saveModerator();
		
		return true;
	}

	/**
	* Form to purchase an item
	*/	
	public function render()
	{
		$mods = VBSHOP::$db->fetchAll('
			SELECT moderator.*, user.username
			FROM $moderator AS moderator
			LEFT JOIN $user AS user USING (userid)
			WHERE moderator.moderatorid :queryList
		', array(
			':queryList' => VBSHOP::$db->queryList(array_keys($this->config['code']['mods']))
		));

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

		foreach ($mods as $moderator)
		{
			// Create the number option template
			$templater = vB_Template::create('option');
				$templater->register('optionvalue', 	$moderator['moderatorid']);
				$templater->register('optiontitle', 	$moderator['username'] . ' (' . $this->registry->forumcache[$moderator['forumid']]['title'] . ')');
			$this->config['moderatoroptions'] .= $templater->render();
		}

		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['moderatorid'])
		{
			if ($this->config['configuration']['moderatorid'] != $code['moderatorid'] AND $this->config['configuration']['moderatorid'] AND $this->config['code']['unfire'])
			{
				// Reinstate the old mod
				$this->saveModerator();				
			}

			$moderator = VBSHOP::$db->fetchRow('
				SELECT moderator.*, user.username
				FROM $moderator AS moderator
				LEFT JOIN $user AS user USING (userid)
				WHERE moderatorid = ?
			', array(
				$code['moderatorid']
			));
			if (!$moderator OR !in_array($moderator['moderatorid'], array_keys($this->config['code']['mods'])))
			{
				// Excluded forum
				eval(standard_error(fetch_error('dbtech_vbshop_invalid_data', $vbphrase['moderator'])));
			}

			// Back this up
			$code['moderatordata'] = $this->config['configuration']['moderatordata'] = $moderator;

			$moddata =& datamanager_init('Moderator', $this->registry, ERRTYPE_SILENT);
			$moddata->set_existing($moderator);
			$moddata->delete(true);
			unset($moddata);
		}
		else
		{
			if ($this->config['configuration']['moderatorid'] AND $this->config['code']['unfire'])
			{
				// Save the moderator back in
				$this->saveModerator();
			}
		}		
		
		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['moderator'] . ': ' . $this->config['configuration']['moderatordata']['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);				
	}	

	/**
	* Re-adds a moderartor
	*
	* @return	integer		Moderator ID
	*/	
	protected function saveModerator()
	{
		$moddata =& datamanager_init('Moderator', $this->registry, ERRTYPE_SILENT);
		foreach ($this->registry->bf_misc_moderatorpermissions as $key => $val)
		{
			if ($this->config['configuration']['moderatordata']['permissions'] & $val)
			{
				$moddata->set_bitfield('permissions', $key, $val);
			}
		}
		foreach ($this->registry->bf_misc_moderatorpermissions2 as $key => $val)
		{
			if ($this->config['configuration']['moderatordata']['permissions2'] & $val)
			{
				$moddata->set_bitfield('permissions2', $key, $val);
			}
		}
		unset($this->config['configuration']['moderatordata']['permissions'], $this->config['configuration']['moderatordata']['permissions2']);
		foreach ($this->config['configuration']['moderatordata'] as $key => $val)
		{
			// Save the moderator
			$moddata->set($key, $val);
		}
		$modid = $moddata->save();

		if ($modid)
		{
			// Update moderator ID
			VBSHOP::$db->update('moderator', array('moderatorid' => $this->config['configuration']['moderatorid']), 'WHERE moderatorid = ' . intval($modid));
		}

		return true;
	}
}
?>