<?php
/**
 * ###############################################
 *
 * SWIFT Framework
 * _______________________________________________
 *
 * @author		Varun Shoor
 *
 * @package		SWIFT
 * @copyright	Copyright (c) 2001-2012, Kayako
 * @license		http://www.kayako.com/license
 * @link		http://www.kayako.com
 *
 * ###############################################
 */

/**
 * The Custom Field Value Management Class
 *
 * @author Varun Shoor
 */
class SWIFT_CustomFieldValue extends SWIFT_Model
{
	const TABLE_NAME		=	'customfieldvalues';
	const PRIMARY_KEY		=	'customfieldvalueid';

	const TABLE_STRUCTURE	=	"customfieldvalueid I PRIMARY AUTO NOTNULL,
								customfieldid I DEFAULT '0' NOTNULL,
								typeid I DEFAULT '0' NOTNULL,
								fieldvalue X NOTNULL,
								isserialized I2 DEFAULT '0' NOTNULL,
								isencrypted I2 DEFAULT '0' NOTNULL,
								dateline I DEFAULT '0' NOTNULL,
								uniquehash C(100) DEFAULT '' NOTNULL,
								lastupdated I DEFAULT '0' NOTNULL";

	const INDEX_1			=	'customfieldid, typeid';
	const INDEX_2			=	'uniquehash';


	protected $_dataStore = array();

	/**
	 * Constructor
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Data $_SWIFT_DataObject The SWIFT_Data Object
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Record could not be loaded
	 */
	public function __construct(SWIFT_Data $_SWIFT_DataObject)
	{
		parent::__construct();

		if (!$_SWIFT_DataObject instanceof SWIFT_Data || !$_SWIFT_DataObject->GetIsClassLoaded() || !$this->LoadData($_SWIFT_DataObject)) {
			throw new SWIFT_Exception('Failed to load Custom Field Value Object');

			$this->SetIsClassLoaded(false);

			return false;
		}

		return true;
	}

	/**
	 * Destructor
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function __destruct()
	{
		$this->ProcessUpdatePool();

		parent::__destruct();

		return true;
	}

	/**
	 * Processes the Update Pool Data
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	public function ProcessUpdatePool()
	{
		if (!$this->GetIsClassLoaded()) {
			return false;
		} else if (!_is_array($this->GetUpdatePool())) {
			return false;
		}

		$this->Database->AutoExecute(TABLE_PREFIX . 'customfieldvalues', $this->GetUpdatePool(), 'UPDATE', "customfieldvalueid = '" . intval($this->GetCustomFieldValueID()) . "'");

		$this->ClearUpdatePool();

		return true;
	}

	/**
	 * Retrieves the Custom Field Value ID
	 *
	 * @author Varun Shoor
	 * @return mixed "customfieldvalueid" on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	public function GetCustomFieldValueID()
	{
		if (!$this->GetIsClassLoaded())
		{
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		return $this->_dataStore['customfieldvalueid'];
	}

	/**
	 * Load the Data
	 *
	 * @author Varun Shoor
	 * @param SWIFT_Data $_SWIFT_DataObject The SWIFT_Data Object
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Ticket_Exception If Invalid Data is Provided
	 */
	protected function LoadData($_SWIFT_DataObject)
	{
		$_SWIFT = SWIFT::GetInstance();

		// Is it a ID?
		if ($_SWIFT_DataObject instanceof SWIFT_DataID && $_SWIFT_DataObject->GetIsClassLoaded())
		{
			$_dataStore = $_SWIFT->Database->QueryFetch("SELECT * FROM " . TABLE_PREFIX . "customfieldvalues WHERE customfieldvalueid = '" . intval($_SWIFT_DataObject->GetDataID()) . "'");
			if (isset($_dataStore['customfieldvalueid']) && !empty($_dataStore['customfieldvalueid']))
			{
				$this->_dataStore = $_dataStore;

				return true;
			}

			// Is it a Store?
		} else if ($_SWIFT_DataObject instanceof SWIFT_DataStore && $_SWIFT_DataObject->GetIsClassLoaded()) {
			$this->_dataStore = $_SWIFT_DataObject->GetDataStore();

			if (!isset($this->_dataStore['customfieldvalueid']) || empty($this->_dataStore['customfieldvalueid']))
			{
				throw new SWIFT_Exception(SWIFT_INVALIDDATA);
			}

			return true;
		}

		throw new SWIFT_Exception(SWIFT_INVALIDDATA);

		return false;
	}

	/**
	 * Returns the Data Store Array
	 *
	 * @author Varun Shoor
	 * @return mixed "_dataStore" Array on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	public function GetDataStore()
	{
		if (!$this->GetIsClassLoaded())
		{
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		return $this->_dataStore;
	}

	/**
	 * Retrieves a Property Value from Data Store
	 *
	 * @author Varun Shoor
	 * @param string $_key The Key Identifier
	 * @return mixed Property Data on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	public function GetProperty($_key)
	{
		if (!$this->GetIsClassLoaded())
		{
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		} else if (!isset($this->_dataStore[$_key])) {
			throw new SWIFT_Exception(SWIFT_INVALIDDATA);

			return false;
		}

		return $this->_dataStore[$_key];
	}

	/**
	 * Create a new Custom Field Value Record
	 *
	 * @author Varun Shoor
	 * @param int $_customFieldID The Custom Field ID
	 * @param int $_typeID The Type ID
	 * @param string $_fieldValue The Field Value
	 * @param bool $_isSerialized Whether the value is serialized
	 * @param bool $_isEncrypted Whether the value is encrypted
	 * @return int The Custom Field Value ID
	 * @throws SWIFT_Exception If Invalid Data is Provided or If the Object could not be created
	 */
	static public function Create($_customFieldID, $_typeID, $_fieldValue, $_isSerialized, $_isEncrypted)
	{
		$_SWIFT = SWIFT::GetInstance();

		if (empty($_customFieldID) || empty($_typeID))
		{
			throw new SWIFT_Exception(SWIFT_INVALIDDATA);

			return false;
		}

		$_SWIFT->Database->AutoExecute(TABLE_PREFIX . 'customfieldvalues', array('customfieldid' => intval($_customFieldID), 'typeid' => intval($_typeID), 'fieldvalue' => $_fieldValue,
			'dateline' => DATENOW, 'lastupdated' => '0', 'isserialized' => intval($_isSerialized), 'isencrypted' => intval($_isEncrypted), 'uniquehash' => BuildHash()), 'INSERT');
		$_customFieldValueID = $_SWIFT->Database->Insert_ID();

		if (!$_customFieldValueID)
		{
			throw new SWIFT_Exception(SWIFT_CREATEFAILED);

			return false;
		}

		return $_customFieldValueID;
	}

	/**
	 * Update the Custom Field Value Record
	 *
	 * @author Varun Shoor
	 * @param string $_fieldValue The Field Value
	 * @param bool $_isSerialized Whether the value is serialized
	 * @param bool $_isEncrypted Whether the value is encrypted
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded or If Invalid Data is Provided
	 */
	public function Update($_fieldValue, $_isSerialized, $_isEncrypted)
	{
		if (!$this->GetIsClassLoaded()) {
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}
		/**
		 * BUG FIX - Anjali Sharma <anjali.sharma@kayako.com>
		 *
		 * SWIFT-4020 Problem updating custom fields through the API/UpdateTicketCustomFields returns null
		 */
		if (!empty($_fieldValue)) {

			$this->UpdatePool('fieldvalue', $_fieldValue);
			$this->UpdatePool('isserialized', intval($_isSerialized));
			$this->UpdatePool('isencrypted', intval($_isEncrypted));
		}

		$this->ProcessUpdatePool();

		return true;
	}

	/**
	 * Delete the Custom Field Value record
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	public function Delete()
	{
		if (!$this->GetIsClassLoaded())
		{
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		self::DeleteList(array($this->GetCustomFieldValueID()));

		$this->SetIsClassLoaded(false);

		return true;
	}

	/**
	 * Delete a list of Custom Field Values
	 *
	 * @author Varun Shoor
	 * @param array $_customFieldValueIDList
	 * @return bool "true" on Success, "false" otherwise
	 */
	static public function DeleteList($_customFieldValueIDList)
	{
		$_SWIFT = SWIFT::GetInstance();

		if (!_is_array($_customFieldValueIDList))
		{
			return false;
		}

		$_SWIFT->Database->Query("DELETE FROM " . TABLE_PREFIX . "customfieldvalues WHERE customfieldvalueid IN (" . BuildIN($_customFieldValueIDList) . ")");

		return true;
	}

	/**
	 * Delete the List of Custom Field Values based on a list of Custom Field IDs
	 *
	 * @author Varun Shoor
	 * @param array $_customFieldIDList The Custom Field ID List
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If Invalid Data is Provided
	 */
	static public function DeleteOnCustomField($_customFieldIDList)
	{
		$_SWIFT = SWIFT::GetInstance();

		if (!_is_array($_customFieldIDList))
		{
			return false;
		}

		$_customFieldValueIDList = array();
		$_SWIFT->Database->Query("SELECT customfieldvalueid FROM " . TABLE_PREFIX . "customfieldvalues WHERE customfieldid IN (" . BuildIN($_customFieldIDList) . ")");
		while ($_SWIFT->Database->NextRecord())
		{
			$_customFieldValueIDList[] = $_SWIFT->Database->Record['customfieldvalueid'];
		}

		if (!_is_array($_customFieldValueIDList))
		{
			return false;
		}

		self::DeleteList($_customFieldValueIDList);

		return true;
	}

	/**
	 * Sync the custom field values on type
	 *
	 * @author Varun Shoor
	 * @param array $_groupTypeList
	 * @param int $_newTypeID
	 * @param array $_oldTypeIDList
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If Invalid Data is Provided
	 */
	static public function SyncOnType($_groupTypeList, $_newTypeID, $_oldTypeIDList) {
		$_SWIFT = SWIFT::GetInstance();

		if (!_is_array($_groupTypeList) || empty($_newTypeID) || !_is_array($_oldTypeIDList)) {
			return false;
		}

		// First retrieve the custom field groups
		$_customFieldGroupIDList = array();
		$_SWIFT->Database->Query("SELECT * FROM " . TABLE_PREFIX . "customfieldlinks WHERE grouptype IN (" . BuildIN($_groupTypeList) . ") AND linktypeid = '" . intval($_newTypeID) . "'");
		while ($_SWIFT->Database->NextRecord()) {
			$_customFieldGroupIDList[] = $_SWIFT->Database->Record['customfieldgroupid'];
		}

		// Now retrieve custom fields for the groups
		$_customFieldIDList = array();
		$_SWIFT->Database->Query("SELECT customfieldid FROM " . TABLE_PREFIX . "customfields WHERE customfieldgroupid IN (" . BuildIN($_customFieldGroupIDList) . ")");
		while ($_SWIFT->Database->NextRecord()) {
			$_customFieldIDList[] = $_SWIFT->Database->Record['customfieldid'];
		}

		// Now update the values
		$_SWIFT->Database->AutoExecute(TABLE_PREFIX . 'customfieldvalues', array('typeid' => intval($_newTypeID)), 'UPDATE', "customfieldid IN (" . BuildIN($_customFieldIDList) . ") AND typeid IN (" . BuildIN($_oldTypeIDList) . ")");

		return true;
	}
}
?>