<?php
/**
* @version	$Id: frny_currency_rates.php 16601 2018-04-06 12:07:55Z 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 FRNYCurrencyRates extends CurrencyRates {

	public function __construct()
	{
		$this->RateSource = 'http://www.ny.frb.org/markets/fxrates/FXtoXML.cfm?FEXdate=%s&FEXtime=1200';

		parent::__construct();
	}

	function GetRatesData()
	{
		/** @var kCurlHelper $curl_helper */
		$curl_helper = $this->Application->recallObject('CurlHelper');
		$curl_helper->followLocation = true;

		for($i = 0; $i < 10; $i++)
		{
			$time = adodb_mktime() - $i * 3600 * 24;
			$source_file = sprintf($this->RateSource, adodb_date('Y-m-d', $time));
			$xml = $curl_helper->Send($source_file);

			if ( !$curl_helper->isGoodResponseCode() || strlen($xml) == 0 ) {
				continue;
			}

			$xml_parser = xml_parser_create();
			xml_parse_into_struct($xml_parser, $xml, $struct, $index);
			foreach($struct as $element)
			{
				if($element['tag'] == 'FRBNY:DATASET')
				{
					break;
				}
			}
			if($element['type'] == 'open')
			{
				break;
			}
		}
		if($element['type'] != 'open')
		{
			return false;
		}

		foreach($struct as $element)
		{
			switch($element['tag'])
			{
				case 'FRBNY:SERIES':
					$currency = $element['attributes']['UNIT'];
					if($currency)
					{
						$data_res[$currency]['ID'] = $currency;
						$data_res[$currency]['UNITS'] = 1;
					}
				break;
				case 'FRBNY:CURR':
					$data_res[$currency]['TARGET'] = $element['value'];
				break;
				case 'FRBNY:OBS_VALUE':
					$data_res[$currency]['RATE'] = ($element['value'] == 0) ? 0 : 1 / $element['value'];
				break;
				default:
			}
		}
		if(!$data_res['USD'])
		{
			$data_res['USD']['ID'] = 'USD';
			$data_res['USD']['UNITS'] = 1;
			$data_res['USD']['TARGET'] = 'USD';
			$data_res['USD']['RATE'] = 1;
		}
		$this->ExchangeRates = $data_res;
	}

}
