<?php
/**
 * Goweb Sitemanager 5 Framework
 *
 * @version    5.0.17
 * @category   Goweb
 * @package    Goweb_Currency
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2009 (c) Goweb (http://www.goweb.pt)
 */

goweb::loadClass('Zend_Currency');

/**
 * Classe de manipulação de conversão de câmbios
 * Baseado em http://porteightyeight.com/2009/06/25/adding-currency-conversion-to-zend_currency/
 *
 * @version    5.0.17
 * @category   Goweb
 * @package    Goweb_Currency
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2009 (c) Goweb (http://www.goweb.pt)
 */
class Goweb_Currency extends Zend_Currency {

	/**
	 * URL to conversions provided by the European Central Bank
	 *
	 * This data is updated every 24 hours @3pm C.E.T.
	 *
	 * @var string
	 */
	protected $_conversionUrl = 'http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml';

	/**
	 * Convert a quantity from this currency to another
	 *
	 * @param string $toCurrency The three-characeter destination currency short name code
	 * @param float  $quantity What value $fromCurrency should be converted to $toCurrency
	 * @param string $fromCurrency The three-characeter origin currency short name code
	 * @return float
	 */
	public function convert($toCurrency, $quantity, $fromCurrency = null) {
		$cache = self::getCache();
		if(!$cache) {
			$conversions = $this->getConversions();
		} else {
			//Cache the result for 24 hours if we can
			$cache = Zend_Cache::factory('Class', $cache->getBackend(), array('cached_entity' => $this, 'lifetime' => 60*60*24));
			$conversions = $cache->getConversions();
		}

		if (is_null($fromCurrency)) $fromCurrency = $this->getShortName();

		if(!isset($conversions[$fromCurrency]) && !isset($conversions[$toCurrency])) {
			return false;
		}

		$inEuros = $quantity / $conversions[$fromCurrency];
		$inDestinationCurrency = $conversions[$toCurrency] * $inEuros;

		return $inDestinationCurrency;
	}

	/**
	 * Get the conversions table
	 *
	 * @return array An array indexed by currency code. Values are the conversion rate against the Euro.
	 */
	public function getConversions() {
	    goweb::loadClass('Zend_Http_Client');
		$client = new Zend_Http_Client($this->_conversionUrl);
		$response = $client->request(Zend_Http_Client::GET);

		if($response->getStatus() != 200) {
			return array();
		}

		$xml = $response->getBody();

		$regex = '#[\'"]([A-Z]{3})[\'"].+[\'"]([0-9\.]+)[\'"]#';
		$matches = array();
		if(!preg_match_all($regex, $xml, $matches)) {
			return array();
		}

		$conversions = array_combine($matches[1], $matches[2]);
		$conversions['EUR'] = 1;

		foreach ($conversions as $k => $v) {
			$conversions[$k] = (float)$v;
		}

		return $conversions;
	}
}
