<?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 shops
*
* @package	vbshop
*/
class vBShop_DataManager_Shop extends vB_DataManager
{
	/**
	* Array of recognised and required fields for shops, and their types
	*
	* @var	array
	*/
	var $validfields = array(
		'shopid' 			=> 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),
		'logo' 				=> array(TYPE_STR, 		REQ_NO),
		'ownerid' 			=> array(TYPE_UINT, 	REQ_NO, 	VF_METHOD, 	'verify_userid'),
		'permissions' 		=> array(TYPE_NOCLEAN, 	REQ_NO, 	VF_METHOD, 	'verify_serialized'),
		'sales' 			=> array(TYPE_UINT, 	REQ_NO),
		'salesamounts' 		=> array(TYPE_NOCLEAN, 	REQ_NO, 	VF_METHOD, 	'verify_serialized'),
		'latestcustomer' 	=> array(TYPE_UINT, 	REQ_NO, 	VF_METHOD, 	'verify_userid'),
		'latestsale' 		=> array(TYPE_UINT, 	REQ_NO, 	VF_METHOD, 	'verify_itemid'),
		'bitfield' 			=> array(TYPE_UINT, 	REQ_AUTO),
		'beneficiary' 		=> array(TYPE_INT, 		REQ_NO, 	VF_METHOD),
		'beneficiary_split' => array(TYPE_UINT, 	REQ_NO, 				'if ($data < 0) { $data = 0; } if ($data > 100) { $data = 100; } return true;'),	
		'averagerating' 	=> array(TYPE_UNUM, 	REQ_NO),
		'positivepercent' 	=> array(TYPE_UINT, 	REQ_NO),
		'negativepercent' 	=> array(TYPE_UINT, 	REQ_NO),
		'neutralpercent' 	=> array(TYPE_UINT, 	REQ_NO),
		'canhavefeedback' 	=> array(TYPE_STR, 		REQ_NO, 	VF_METHOD, 	'verify_onoff'),
	);

	/**
	* 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_shop';

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

	/**
	* 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_Shop(&$registry, $errtype = ERRTYPE_STANDARD)
	{
		parent::vB_DataManager($registry, $errtype);

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

	/**
	* Verifies that the title is valid
	*
	* @param	string	Title of the shop
	*
	* @return	boolean
	*/
	function verify_title(&$title)
	{
		global $vbphrase;
		
		$title = strval($title);
		if ($title === '')
		{
			// Invalid
			return false;
		}
		
		/*
		// Check for existing shop of this name
		if ($existing = $this->registry->db->query_first_slave("
			SELECT `title`
			FROM `" . TABLE_PREFIX . "dbtech_vbshop_shop`
			WHERE `title` = " . $this->registry->db->sql_prepare($title) . "
				" . ($this->existing['shopid'] ? "AND `shopid` != " . $this->registry->db->sql_prepare($this->existing['shopid']) : '') . "			
			LIMIT 1
		"))
		{
			// Whoopsie, exists
			$this->error('dbtech_vbshop_x_already_exists_y', $vbphrase['dbtech_vbshop_shop'], $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 specified user exists
	*
	* @param	integer	User ID
	*
	* @return 	boolean	Returns true if user exists
	*/
	function verify_userid(&$userid)
	{
		if ($userid == 0)
		{
			// 0 is valid in this case 
			return true;
		}

		return parent::verify_userid($userid);
	}
	
	/**
	* Verifies that the specified beneficiary exists
	*
	* @param	integer	User ID
	*
	* @return 	boolean	Returns true if user exists
	*/
	function verify_beneficiary(&$userid)
	{
		if ($userid == 0 OR $userid == -1)
		{
			// 0 is valid in this case 
			return true;
		}

		return parent::verify_userid($userid);
	}

	/**
	* Verifies that the itemid is valid
	*
	* @param	integer	itemid
	*
	* @return	boolean
	*/
	function verify_itemid(&$itemid)
	{
		// Validate itemid
		return is_array(VBSHOP::$cache['item']["$itemid"]);
	}

	/**
	* 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_shop`
				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 ($this->fetch_field('ownerid'))
		{
			// Only do this if we're trying to set an owner
			foreach ((array)VBSHOP::$cache['shop'] as $shopid => $shop)
			{
				if ($shopid == $this->fetch_field('shopid'))
				{
					// Skip this shop
					continue;
				}
				
				if ($shop['ownerid'] == $this->fetch_field('ownerid'))
				{
					// This owner already owns another shop
					$this->error('dbtech_vbshop_may_only_own_one_shop');
				}
			}
		}
		
		$return_value = true;
		($hook = vBulletinHook::fetch_hook('dbtech_vbshop_shopdata_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_shopdata_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_shopdata_postsave')) ? eval($hook) : false;

		// Rebuild the cache
		VBSHOP_CACHE::build('shop');

		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_shopdata_delete')) ? eval($hook) : false;
		
		$this->dbobject->query_write("
			UPDATE " . TABLE_PREFIX . "dbtech_vbshop_item
			SET shop = shop - " . $this->existing['bitfield'] . "
			WHERE (shop & " . $this->existing['bitfield'] . ")
		");		
		$this->dbobject->query_write("
			DELETE FROM " . TABLE_PREFIX . "dbtech_vbshop_shopinventory
			WHERE shopid = " . $this->existing['shopid'] . "
		");		
		
		// Rebuild the cache
		VBSHOP_CACHE::build('shop');
		VBSHOP_CACHE::build('item');
		
		return true;
	}
}