<?php
/*+***********************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.1
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 *************************************************************************************/
/**
* @author IT Sapiens
*/
require_once 'modules/AdvancedReports/utils/ITSapiensDateTimeUtils.php';

class ITSapiensReportModuleHooks{
	/**
	* 
	* @var loaded with configuration from external file
	* @static
	* 
	*/
	private static $configuration;
	/**
	* 
	* @param array $response
	* @param object $user
	* @param string $tableName
	* @param string $tableAlias
	* @param string $columnName
	* @static
	* 
*/
	public static function replaceTableColumnName($response, ARUser $user, $tableName, $tableAlias, $columnName){
		//Load configuration if not loaded
		if(!self::$configuration) self::updateConfiguration($tableAlias, $user);

		if(isset(self::$configuration[$tableName][$columnName])){
			//reload configuration to update values in code snippets
			self::updateConfiguration($tableAlias, $user);

			for($i=0;$i<count($response);$i++){
				$search= $tableAlias.".`{$columnName}`";
				$replace = self::$configuration[$tableName][$columnName];
				$response[$i] = str_replace($search,$replace,$response[$i]);
			}
		}
		return $response;
	}

	public static function getUTCOffset($user)
	{
		//Calculated fields
		$UTCoffset = ITSapiensDateTimeUtils::covertTimeZoneStringToDefaultOffset($user->getTimeZone());

		return "'{$UTCoffset}'";
	}

	public static function updateConfiguration($tableAlias, ARUser $user)
	{
		$UTCoffset = self::getUTCOffset($user);

		self::$configuration = require 'modules/AdvancedReports/config/hooks/reportModuleColumnName.php';
	}

	public static function getColumnName($tableName, $tableAlias, $columnName, $user)
	{
		self::updateConfiguration($tableAlias, $user);

		if (!isset(self::$configuration[$tableName][$columnName])) {
			return null;
		}

		return self::$configuration[$tableName][$columnName];
	}
}
