<?php
/*======================================================================*\
|| #################################################################### ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2013 Fillip Hannisdal AKA Revan/NeoRevan/Belazor 	  # ||
|| # All Rights Reserved. 											  # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ---------------------------------------------------------------- # ||
|| # You are not allowed to use this on your server unless the files  # ||
|| # you downloaded were done so with permission.					  # ||
|| # ---------------------------------------------------------------- # ||
|| #################################################################### ||
\*======================================================================*/

if (!class_exists('vB_DataManager', false))
{
	exit;
}

/**
* Class to do data save/delete operations for currencys
*
* @package	vbshop
*/
class vBShop_DataManager_Currency extends vB_DataManager
{
	/**
	* Array of recognised and required fields for currencys, and their types
	*
	* @var	array
	*/
	var $validfields = array(
		'currencyid' 	=> array(TYPE_UINT, 	REQ_INCR, 	VF_METHOD, 	'verify_nonzero'),
		'title' 		=> array(TYPE_STR, 		REQ_YES, 	VF_METHOD),
		'description' 	=> array(TYPE_STR, 		REQ_NO),
		'active' 		=> array(TYPE_STR, 		REQ_NO, 	VF_METHOD, 	'verify_onoff'),
		'displayorder' 	=> array(TYPE_UINT, 	REQ_NO),
		'pointstable' 	=> array(TYPE_STR, 		REQ_YES, 	VF_METHOD),
		'pointscolumn' 	=> array(TYPE_STR, 		REQ_YES, 	VF_METHOD, 	'verify_nonempty'),
		'canbank' 		=> array(TYPE_STR, 		REQ_NO, 	VF_METHOD, 	'verify_onoff'),		
		'cansteal' 		=> array(TYPE_STR, 		REQ_NO, 	VF_METHOD, 	'verify_onoff'),		
		'stealprotect' 	=> array(TYPE_NUM, 		REQ_NO),		
		'interest' 		=> array(TYPE_NUM, 		REQ_NO),		
		'rounding' 		=> array(TYPE_UINT, 	REQ_NO),
		'privacy' 		=> array(TYPE_UINT, 	REQ_NO),
		'customshops' 	=> array(TYPE_STR, 		REQ_NO, 	VF_METHOD, 	'verify_onoff'),
		'perreply' 		=> array(TYPE_UINT, 	REQ_NO),
		'perthread' 	=> array(TYPE_UINT, 	REQ_NO),
		'postbit' 		=> array(TYPE_NOCLEAN, 	REQ_NO),
		'bitfield' 		=> array(TYPE_UINT, 	REQ_AUTO),	
	);

	/**
	* Array of field names that are bitfields, together with the name of the variable in the registry with the definitions.
	*
	* @var	array
	*/
	//var $bitfields = array('adminpermissions' => 'bf_ugp_adminpermissions');

	/**
	* The main table this class deals with
	*
	* @var	string
	*/
	var $table = 'dbtech_vbshop_currency';

	/**
	* Condition for update query
	*
	* @var	array
	*/
	var $condition_construct = array('currencyid = %1$d', 'currencyid');

	/**
	* Constructor - checks that the registry object has been passed correctly.
	*
	* @param	vB_Registry	Instance of the vBulletin data registry object - expected to have the database object as one of its $this->db member.
	* @param	integer		One of the ERRTYPE_x constants
	*/
	function vBShop_DataManager_Currency(&$registry, $errtype = ERRTYPE_STANDARD)
	{
		parent::vB_DataManager($registry, $errtype);

		($hook = vBulletinHook::fetch_hook('dbtech_vbshop_currencydata_start')) ? eval($hook) : false;
	}

	/**
	* Verifies that the title is valid
	*
	* @param	string	Title of the currency
	*
	* @return	boolean
	*/
	function verify_title(&$title)
	{
		global $vbphrase;
		
		$title = strval($title);
		if ($title === '')
		{
			// Invalid
			return false;
		}
		
		// Check for existing currency of this name
		if ($existing = $this->registry->db->query_first_slave("
			SELECT `title`
			FROM `" . TABLE_PREFIX . "dbtech_vbshop_currency`
			WHERE `title` = " . $this->registry->db->sql_prepare($title) . "
				" . ($this->existing['currencyid'] ? "AND `currencyid` != " . $this->registry->db->sql_prepare($this->existing['currencyid']) : '') . "			
			LIMIT 1
		"))
		{
			// Whoopsie, exists
			$this->error('dbtech_vbshop_x_already_exists_y', $vbphrase['dbtech_vbshop_currency'], $title);
			return false;
		}
		
		return true;
	}

	/**
	* Verifies that the onoff flag is valid
	*
	* @param	string	On/Off flag
	*
	* @return	boolean
	*/
	function verify_onoff(&$onoff)
	{
		// Validate onoff
		$onoff = (!in_array($onoff, array('0', '1')) ? '1' : $onoff);
		
		return true;
	}

	/**
	* Verifies that the pointstable flag is valid
	*
	* @param	string	pointstable flag
	*
	* @return	boolean
	*/
	function verify_pointstable(&$pointstable)
	{
		if (!$pointstable)
		{
			// -.-
			return false;
		}
		
		// Get DB Alter class
		require_once(DIR . '/includes/class_dbalter.php');
		$db_alter = new vB_Database_Alter_MySQL($this->registry->db);
		
		return $db_alter->fetch_table_info($pointstable);
	}

	/**
	* Any checks to run immediately before saving. If returning false, the save will not take place.
	*
	* @param	boolean	Do the query?
	*
	* @return	boolean	True on success; false if an error occurred
	*/
	function pre_save($doquery = true)
	{
		if ($this->presave_called !== null)
		{
			return $this->presave_called;
		}
		
		if (!$this->condition)
		{
			// Check for existing button of this name
			if ($existing = $this->registry->db->query_first_slave("
				SELECT `bitfield`
				FROM `" . TABLE_PREFIX . "dbtech_vbshop_currency`
				ORDER BY `bitfield` DESC
				LIMIT 1
			"))
			{
				// Use existing bitfield
				$bitfield = ($existing['bitfield'] * 2);
			}
			else
			{
				// This is the first one
				$bitfield = 1;
			}
			
			// Set the bitfield
			$this->do_set('bitfield', $bitfield);
		}
		
		if (is_array($this->fetch_field('postbit')))
		{
			$bit = 0;
			foreach ($this->fetch_field('postbit') as $val)
			{
				// Set bitfield value
				$bit += $val;
			}
			
			// Set the bitfield
			$this->do_set('postbit', $bit);
		}
		
		// Get DB Alter class
		require_once(DIR . '/includes/class_dbalter.php');
		$db_alter = new vB_Database_Alter_MySQL($this->registry->db);
		
		if ($db_alter->fetch_table_info($this->fetch_field('pointstable')))
		{
			// Add the column if it does not exist
			$db_alter->add_field(array(
				'name'       => $this->fetch_field('pointscolumn'),
				'type'       => 'double',
				'null'       => false,	// True = NULL, false = NOT NULL
				'default'    => 0
			));
		}

		$return_value = true;
		($hook = vBulletinHook::fetch_hook('dbtech_vbshop_currencydata_presave')) ? eval($hook) : false;

		$this->presave_called = $return_value;
		return $return_value;
	}
	
	/**
	* Additional data to update before a delete call (such as denormalized values in other tables).
	*
	* @param	boolean	Do the query?
	*/
	function pre_delete($doquery = true)
	{
		$return_value = true;
		($hook = vBulletinHook::fetch_hook('dbtech_vbshop_currencydata_predelete')) ? eval($hook) : false;

		$this->presave_called = $return_value;
		return $return_value;
	}

	/**
	* Additional data to update after a save call (such as denormalized values in other tables).
	* In batch updates, is executed for each record updated.
	*
	* @param	boolean	Do the query?
	*/
	function post_save_each($doquery = true)
	{
		($hook = vBulletinHook::fetch_hook('dbtech_vbshop_currencydata_postsave')) ? eval($hook) : false;
		
		if (!$this->condition)
		{
			// New currency
			$this->dbobject->query_write("
				INSERT INTO " . TABLE_PREFIX . "dbtech_vbshop_bank
					(userid, currencyid, points)
				SELECT 
					userid,
					" . $this->fetch_field('currencyid') . ",
					0
				FROM " . TABLE_PREFIX . "user AS user
				ORDER BY userid
			");		
		}
		
		// Rebuild the cache
		VBSHOP_CACHE::build('currency');

		return true;
	}

	/**
	* Additional data to update after a delete call (such as denormalized values in other tables).
	*
	* @param	boolean	Do the query?
	*/
	function post_delete($doquery = true)
	{
		($hook = vBulletinHook::fetch_hook('dbtech_vbshop_currencydata_delete')) ? eval($hook) : false;
		
		$this->dbobject->query_write("
			DELETE FROM " . TABLE_PREFIX . "dbtech_vbshop_bank
			WHERE currencyid = " . $this->existing['currencyid'] . "
		");		
		
		// Rebuild the cache
		VBSHOP_CACHE::build('currency');
		
		return true;
	}
}