<?php
/**
* @version	$Id: currency_rates.php 16516 2017-01-20 14:12:22Z alex $
* @package	In-Commerce
* @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license	Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/

defined('FULL_PATH') or die('restricted access!');

class CurrencyRates extends kBase {

	var $RateSource;
	var $ExchangeRates = Array();

	/**
	 * Creates currency rate update class
	 *
	 * @access public
	 */
	public function __construct()
	{
		parent::__construct();

		$this->GetRatesData();
	}

	function GetRatesData()
	{
		$cache_key = 'currency_rates[%CurrSerial%]';
		$rates = $this->Application->getCache($cache_key);
		$primary = $this->Application->GetPrimaryCurrency();

		if ($rates === false) {
			$this->Conn->nextQueryCachable = true;
			$sql = 'SELECT ISO, RateToPrimary
					FROM ' . $this->Application->getUnitOption('curr', 'TableName') . '
					WHERE Status = ' . STATUS_ACTIVE;
			$rates = $this->Conn->Query($sql);

			$this->Application->setCache($cache_key, $rates);
		}

		foreach ($rates as $rate) {
			$this->SetRate($primary, $rate['ISO'], $rate['RateToPrimary']);
		}
	}

	function GetRate($source_cur, $target_cur, $units = 1)
	{
		$source_cur = ($source_cur == 'PRIMARY') ? $this->Application->GetPrimaryCurrency() : $source_cur;
		$target_cur = ($target_cur == 'PRIMARY') ? $this->Application->GetPrimaryCurrency() : $target_cur;
		if($source_cur == $target_cur)
		{
			return 1;
		}

		if($this->ExchangeRates[$target_cur]['TARGET'] == $source_cur)
		{
			$rate = ($this->ExchangeRates[$target_cur]['RATE'] ==  0) ? false : 1 / $this->ExchangeRates[$target_cur]['RATE'];
		}
		elseif($this->ExchangeRates[$source_cur]['TARGET'] == $target_cur)
		{
			$rate = $this->ExchangeRates[$source_cur]['RATE'];
		}
		else
		{
			$rate = ($this->ExchangeRates[$target_cur]['RATE'] == 0) ? false : $this->ExchangeRates[$source_cur]['RATE'] / $this->ExchangeRates[$target_cur]['RATE'];
		}
		$rate *= $units;
		return $rate;
	}

	function Convert($amount, $source_cur, $target_cur)
	{
		return $amount * $this->GetRate($source_cur, $target_cur);
	}

	function AddCurrencySymbol($value, $iso, $decimal_tag = '')
	{
		static $decimal_separator = false;

		$cache_key = 'iso_masks[%CurrSerial%]';
		$iso_masks = $this->Application->getCache($cache_key);

		if ( $iso_masks === false ) {
			$this->Conn->nextQueryCachable = true;
			$symbol_sql = 'IF(COALESCE(Symbol, "") = "", CONCAT(ISO, "&nbsp;"), Symbol)';

			$sql = 'SELECT IF(SymbolPosition = 0, CONCAT(' . $symbol_sql . ', "%s"), CONCAT("%s", ' . $symbol_sql . ')), LOWER(ISO) AS ISO
					FROM ' . $this->Application->getUnitOption('curr', 'TableName') . '
					WHERE Status = ' . STATUS_ACTIVE;
			$iso_masks = $this->Conn->GetCol($sql, 'ISO');
			$this->Application->setCache($cache_key, $iso_masks);
		}

		if ( $decimal_tag ) {
			if ( $decimal_separator === false ) {
				/** @var LanguagesItem $language */
				$language = $this->Application->recallObject('lang.current');

				$decimal_separator = $language->GetDBField('DecimalPoint');
			}

			list ($integer_part, $decimal_part) = explode($decimal_separator, $value);
			$value = $integer_part . $decimal_separator . '<' . $decimal_tag . '>' . $decimal_part . '</' . $decimal_tag . '>';
		}

		$iso = strtolower($iso);

		return array_key_exists($iso, $iso_masks) ? sprintf($iso_masks[$iso], $value) : $value;
	}

	function SetRate($source_cur, $target_cur, $rate, $units = 1)
	{
		$this->ExchangeRates[$target_cur]['TARGET']	= $source_cur;
		$this->ExchangeRates[$target_cur]['ID']		= $target_cur;
		$this->ExchangeRates[$target_cur]['RATE']	= $rate;
		$this->ExchangeRates[$target_cur]['UNITS']	= $units;
	}

	function StoreRates($currencies=null)
	{
		/** @var kDBItem $curr_object */
		$curr_object = $this->Application->recallObject('curr', null, Array ('skip_autoload' => true));

		if ($currencies) {
			if (!is_array($currencies)) {
				$currencies = explode(',', $currencies);
			}
		}
		else {
			$currencies = array_keys($this->ExchangeRates);
		}

		foreach ($currencies as $id) {
			$rate = $this->GetRate($id, 'PRIMARY');
			if ($rate) {
				$curr_object->Clear();
				$curr_object->Load($id, 'ISO');
				$curr_object->SetDBField('RateToPrimary', $rate);
				$curr_object->SetDBField('Modified_date', adodb_mktime());
				$curr_object->SetDBField('Modified_time', adodb_mktime());
				$curr_object->Update();
			}
		}
	}
}
