<?php
function SetupCurrency()
{
	if(isset($GLOBALS['CurrentCurrency'])) {
		return $GLOBALS['CurrentCurrency'];
	}
	// Is there an incoming currency in the request? If so, we also save it in the session
	if(isset($_REQUEST['setCurrencyId']) && SaveCurrencyInSession($_REQUEST['setCurrencyId'])) {
		$GLOBALS['CurrentCurrency'] = (int)$_REQUEST['setCurrencyId'];
	}

	// Is there a currency ID stored in the users session?
	else if(isset($_SESSION['CURRENCY'])) {
		$GLOBALS['CurrentCurrency'] = (int)$_SESSION['CURRENCY'];
	}

	// Can we detect the currency from the visitors IP address?
	else {
		$ipCurrency = GetCurrencyByIp();
		if($ipCurrency) {
			SaveCurrencyInSession($ipCurrency);
		}
	}

	// If the currency in the session doesn't exist, remove it
	if(isset($GLOBALS['CurrentCurrency']) && $GLOBALS['CurrentCurrency'] > 0 && !GetCurrencyById($GLOBALS['CurrentCurrency'])) {
		SaveCurrencyInSession(0);
		unset($GLOBALS['CurrentCurrency']);
	}

	// Otherwise we fetch the default currency
	if(!isset($GLOBALS['CurrentCurrency'])) {
		$currency = GetDefaultCurrency();
		$GLOBALS['CurrentCurrency'] = $currency['currencyid'];
	}

	return $GLOBALS['CurrentCurrency'];
}

function GetDefaultCurrency()
{
	$currencyCache = $GLOBALS['ISC_CLASS_DATA_STORE']->Read('Currencies');

	// Double check that the cache is not empty. The currency cache will never be empty on a good install
	if(empty($currencyCache)) {
		$GLOBALS['ISC_CLASS_DATA_STORE']->UpdateCurrencies();
		$currencyCache = $GLOBALS['ISC_CLASS_DATA_STORE']->Read('Currencies');
	}

	if(!isset($currencyCache['default'])) {
		return false;
	}
	$defaultCurrency = $currencyCache[$currencyCache['default']];
	return $defaultCurrency;
}

function GetCurrencyByIP()
{
	require_once ISC_BASE_PATH."/lib/geoip/geoip.php";
	$geoIp = @geoip_open(ISC_BASE_PATH."/lib/geoip/GeoIP.dat", GEOIP_STANDARD);
	if(!$geoIp) {
		return false;
	}
	$code = geoip_country_code_by_addr($geoIp, GetIP());
	if(!$code) {
		return false;
	}

	$query = "
		SELECT currencyid
		FROM [|PREFIX|]currencies cu
		LEFT JOIN [|PREFIX|]countries co ON cu.currencycountryid = co.countryid
		LEFT JOIN (
			SELECT r.couregid, c.countryiso2
			FROM [|PREFIX|]countries c
			JOIN [|PREFIX|]country_regions r ON c.countrycouregid = r.couregid
		) cr ON cu.currencycouregid = cr.couregid
		WHERE
			(
				co.countryiso2 = '" . $GLOBALS['ISC_CLASS_DB']->Quote($code) . "' OR
				cr.countryiso2 = '" . $GLOBALS['ISC_CLASS_DB']->Quote($code) . "'
			) AND
			cu.currencystatus = 1
		LIMIT 1
	";
	return $GLOBALS['ISC_CLASS_DB']->FetchOne($query, 'currencyid');
}

function ConvertPriceToCurrency($price, $toCurrency=null, $forcedExchangeRate=null, $fromCurrency=null)
{
	if($fromCurrency != null) {
		if(!is_array($fromCurrency)) {
			$fromCurrency = GetCurrencyById($fromCurrency);
		}
	}

	if($toCurrency == null) {
		if(!isset($GLOBALS['CurrentCurrency'])) {
			$toCurrency = GetDefaultCurrency();
		}
		else {
			$toCurrency = GetCurrencyById($GLOBALS['CurrentCurrency']);
		}
	}
	else if(!is_array($toCurrency)) {
		$toCurrency = GetCurrencyById($toCurrency);
	}


	if(!isset($toCurrency['currencyid'])) {
		return $price;
	}

	if(!is_null($forcedExchangeRate)) {
		$toCorrency['currencyexchangerate'] = $forcedExchangeRate;
	}

	$price *= $toCurrency['currencyexchangerate'];
	return $price;
}

function ConvertPriceToDefaultCurrency($price, $fromCurrency=null)
{
	if($fromCurrency == null) {
		$fromCurrency = GetCurrencyById($GLOBALS['CurrentCurrency']);
	}

	if(!is_array($fromCurrency)) {
		$fromCurrency = GetCurrencyById($fromCurrency);
	}

	$toCurrency = GetDefaultCurrency();

	if(!$fromCurrency['currencyid'] || $fromCurrency['currencyid'] == $toCurrency['currencyid']) {
		return $price;
	}

	$price = $price / $fromCurrency['currencyexchangerate'];
	$price = number_format($price, $toCurrency['currencydecimalplace'], '.', '');
	return $price;
}

function FormatPriceInCurrency($price, $toCurrency=null, $fromCurrency=null, $includeCurrencySymbol=true, $includeCurrencyCode=false)
{
	if($fromCurrency != null) {
		if(!is_array($fromCurrency)) {
			$fromCurrency = GetCurrencyById($fromCurrency);
		}
		$price = NormaliseCurrencyFormattedPrice($price, $fromCurrency);
	}

	if($toCurrency == null && isset($GLOBALS['CurrentCurrency'])) {
		$toCurrency = $GLOBALS['CurrentCurrency'];
	}

	if(!is_array($toCurrency)) {
		$toCurrency = GetCurrencyById($toCurrency);
		if(!is_array($toCurrency)) {
			$toCurrency = GetDefaultCurrency();
		}
	}
	$price = number_format($price, $toCurrency['currencydecimalplace'], $toCurrency['currencydecimalstring'], $toCurrency['currencythousandstring']);

	if ($includeCurrencySymbol == true) {
		if (strtolower($toCurrency['currencystringposition']) == "left") {
			$price = $toCurrency['currencystring'] . $price;
		} else {
			$price .= $toCurrency['currencystring'];
		}
	}

	if($includeCurrencyCode == true) {
		$price .= ' '.$toCurrency['currencycode'];
	}

	return $price;
}

function NormaliseCurrencyFormattedPrice($price, $currency)
{
	$price = str_replace($currency['currencystring'], '', (string)$price);
	$price = str_replace($currency['currencythousandstring'], '', $price);
	$price = str_replace($currency['currencydecimalstring'] , '.', $price);
	return $price;
}

function SaveCurrencyInSession($currencyId)
{
	$currency = GetCurrencyById($currencyId);
	if($currency['currencyid']) {
		$_SESSION['CURRENCY'] = $currencyId;
		return true;
	}

	return false;
}


function GetCurrencyById($currencyId)
{
	if($currencyId == 0) {
		return false;
	}

	$currencyCache = $GLOBALS['ISC_CLASS_DATA_STORE']->Read('Currencies');

	// Double check that the cache is not empty. The currency cache will never be empty on a good install
	if(empty($currencyCache)) {
		$GLOBALS['ISC_CLASS_DATA_STORE']->UpdateCurrencies();
		$currencyCache = $GLOBALS['ISC_CLASS_DATA_STORE']->Read('Currencies');
	}

	if(isset($currencyCache[$currencyId])) {
		return $currencyCache[$currencyId];
	}
	return false;
}

function GetCurrencyByCode($currencyCode)
{
	static $currencyTable = array();
	$currencyId = null;

	// If the result has been cached, set the ID
	if(isset($currencyTable[$currencyCode])) {
		$currencyId = $currencyTable[$currencyCode];
	}

	$currencyCache = $GLOBALS['ISC_CLASS_DATA_STORE']->Read('Currencies');

	// Double check that the cache is not empty. The currency cache will never be empty on a good install
	if(empty($currencyCache)) {
		$GLOBALS['ISC_CLASS_DATA_STORE']->UpdateCurrencies();
		$currencyCache = $GLOBALS['ISC_CLASS_DATA_STORE']->Read('Currencies');
	}

	if($currencyId === null) {
		foreach($currencyCache as $nextCurrencyId => $currency) {
			if(strtolower($currency['currencycode']) == strtolower($currencyCode)) {
				$currencyTable[$currency['currencycode']] = $nextCurrencyId;
				$currencyId = $nextCurrencyId;
				break;
			}
		}
	}

	if ($currencyId === null) {
		return false;
	}

	if(isset($currencyCache[$currencyId])) {
		return $currencyCache[$currencyId];
	}
	else {
		return false;
	}
}

function IsCurrencyCodeReal($code)
{
	$converters	= GetAvailableModules('currency');
	$converter	= $converters[0]['object'];

	return $converter->IsRealCode(strtoupper($code));
}


function UpdateCurrenciesFromCron()
{
	$converters = GetAvailableModules('currency');
	$converter	= $converters[0]['object'];
	$result 	= $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]currencies WHERE currencyisdefault='0'");
	$currencies = array();
	while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
		$currencies[] = $row;
	}

	foreach($currencies as $row) {
		if (($rate = $converter->GetExchangeRateUsingBase($row['currencycode'])) !== false) {
			$data = array(
				'currencyexchangerate' => $rate,
				'currencylastupdated' => time()
			);

			if($rate == 0) {
				continue;
			}
			$GLOBALS['ISC_CLASS_DB']->UpdateQuery("currencies", $data, "currencyid='".$GLOBALS['ISC_CLASS_DB']->Quote((int)$row['currencyid'])."'");
		}
	}
	
	$GLOBALS['ISC_CLASS_DATA_STORE']->UpdateCurrencies();
}
function GetCurrencyCodeByID($CurrencyID)
{
	$query = "SELECT currencycode FROM [|PREFIX|]currencies	WHERE currencyid = '".$GLOBALS['ISC_CLASS_DB']->Quote($CurrencyID)."'";
	$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
	$currencyCode = $GLOBALS['ISC_CLASS_DB']->FetchOne($result);
	return $currencyCode;
}