<?php
class ModelLocalisationCurrency extends Model {
	public function getCurrencyByCode($currency) {
		$query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "currency WHERE code = '" . $this->db->escape($currency) . "'");

		return $query->row;
	}


				public function refresh($force = false) {
					if (!extension_loaded('curl')) {
						$this->log->write('CURL não encontrado: Não foi possível atualizar o câmbio das moedas!');
						return false;
					}

					$default = $this->config->get('config_currency');
					$default_sql = $this->db->escape($default);

					if ($force) {
						$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "currency WHERE code != '{$default_sql}'");
					} else {
						$date = date('Y-m-d H:i:s', strtotime('-1 day'));
						$date_sql = $this->db->escape($date);

						$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "currency WHERE code != '{$default_sql}' AND date_modified < '{$date_sql}'");
					}

					$currencies = array();

					foreach ($query->rows as $result) {
						if ($result['code'] != $default) {
							$currencies[] = $result['code'];
						}
					}

					if ($currencies) {
						$rates = $this->getCurrencyRate($default, $currencies);

						if ($rates) {
							foreach ($rates as $code => $value) {
								$new_value = $value;

								// desvaloriza 1% da moeda default para maior segurança
								if ($value < 1) { $new_value = $value * 0.99; } // subtrai 1%
								if ($value > 1) { $new_value = $value * 1.01; } // adiciona 1%

								$new_value = round($new_value, 8); // 8 casas decimais
								$def_value = round(1 / $new_value, 8);

								$this->editValueByCode($code, $new_value);

								$this->log->write("Câmbio atualizado: 1 {$code} = {$def_value} {$default} -ou- 1 {$default} = {$new_value} {$code}");
							}

							$this->cache->delete('currency');
						}
					}

					$this->editValueByCode($default, '1.00000');
				}

				private function getCurrencyRate($default, $currencies) {

					// PRIMEIRA TENTATIVA
					// https://freecurrencyrates.com/api/action.php?s=fcr&f=BRL&v=1&do=cvals&ln=pt&iso=USDEURGBP
					// {"updated":"1533561635","USD":0.2695753260291,"EUR":0.23306359312918,"GBP":0.20767942142132}
					// - permite consultar todas as moedas em uma única chamada

					$codes = implode('', $currencies);
					$response = $this->currencyRateCURL("https://freecurrencyrates.com/api/action.php?s=fcr&f={$default}&v=1&do=cvals&ln=pt&iso={$codes}");
					if ($response !== false) {
						$rates = json_decode($response, true);
						if (json_last_error() == JSON_ERROR_NONE) {
							if (is_array($rates)) {
								unset($rates['updated']);
								return $rates;
							}
						}
					}

					// SEGUNDA TENTATIVA
					// http://www.floatrates.com/daily/brl.json
					// {
					// 	"usd":{"code":"USD","alphaCode":"USD","numericCode":"840","name":"U.S. Dollar","rate":0.26889191168398,"date":"Mon, 6 Aug 2018 12:00:01 GMT","inverseRate":3.718966456586},
					// 	"eur":{"code":"EUR","alphaCode":"EUR","numericCode":"978","name":"Euro","rate":0.23252894513417,"date":"Mon, 6 Aug 2018 12:00:01 GMT","inverseRate":4.3005398722425},
					// 	...
					// }
					// - permite consultar todas as moedas em uma única chamada

					$code = strtolower($default);
					$response = $this->currencyRateCURL("http://www.floatrates.com/daily/{$code}.json");
					if ($response !== false) {
						$json = json_decode($response, true);
						if (json_last_error() == JSON_ERROR_NONE) {
							if (is_array($json)) {
								$rates = array();
								foreach ($currencies as $currency) {
									$code = strtolower($currency);
									if (isset($json[$code]) && isset($json[$code]['rate'])) {
										$rates[$currency] = $json[$code]['rate'];
									}
								}
								if ($rates) {
									return $rates;
								}
							}
						}
					}

					// TERCEIRA TENTATIVA
					// https://free.currencyconverterapi.com/api/v6/convert?q=BRL_USD&compact=ultra
					// {"BRL_USD":0.268421}
					// - precisa consultar cada moeda individualmente

					$rates = array();
					foreach ($currencies as $currency) {
						$code = "{$default}_{$currency}";
						$response = $this->currencyRateCURL("https://free.currencyconverterapi.com/api/v6/convert?q={$code}&compact=ultra");
						if ($response !== false) {
							$rate = json_decode($response, true);
							if (json_last_error() == JSON_ERROR_NONE) {
								if (is_array($rate) && isset($rate[$code])) {
									$rates[$currency] = $rate[$code];
								}
							}
						}
					}
					if ($rates) {
						return $rates;
					}

					// QUARTA TENTATIVA
					// https://www.amdoren.com/api/currency.php?api_key=d7Fkw83yAgk85pQyPF7ynxYqcgaR3i&from=BRL&to=USD&amount=1
					// APIKEY desenvolvimento@hoteldaweb.com.br > d7Fkw83yAgk85pQyPF7ynxYqcgaR3i
					// {"error" : 0, "error_message" : "-", "amount" : 0.26872}
					// - precisa consultar cada moeda individualmente

					$rates = array();
					foreach ($currencies as $currency) {
						$response = $this->currencyRateCURL("https://www.amdoren.com/api/currency.php?api_key=d7Fkw83yAgk85pQyPF7ynxYqcgaR3i&from={$default}&to={$currency}&amount=1");
						if ($response !== false) {
							$rate = json_decode($response, true);
							if (json_last_error() == JSON_ERROR_NONE) {
								if (is_array($rate) && isset($rate['amount'])) {
									$rates[$currency] = $rate['amount'];
								}
							}
						}
					}
					if ($rates) {
						return $rates;
					}

					// ERRO EM TODAS AS TENTATIVAS
					return false;
				}

				private function currencyRateCURL($uri) {
					$curl = curl_init();
					curl_setopt($curl, CURLOPT_URL, $uri);
					curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
					curl_setopt($curl, CURLOPT_HEADER, false);
					curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
					curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
					curl_setopt($curl, CURLOPT_TIMEOUT, 10);
					$response = curl_exec($curl);
					curl_close($curl);
					return $response;
				}

				private function editValueByCode($code, $value) {
					$this->db->query("UPDATE " . DB_PREFIX . "currency SET value = '" . (float)$value . "', date_modified = NOW() WHERE code = '" . $this->db->escape((string)$code) . "'");
					$this->cache->delete('currency');
				}
			
	public function getCurrencies() {
		$currency_data = $this->cache->get('currency');

		if (!$currency_data) {
			$currency_data = array();

			$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "currency ORDER BY title ASC");

			foreach ($query->rows as $result) {
				$currency_data[$result['code']] = array(
					'currency_id'   => $result['currency_id'],
					'title'         => $result['title'],
					'code'          => $result['code'],
					'symbol_left'   => $result['symbol_left'],
					'symbol_right'  => $result['symbol_right'],
					'decimal_place' => $result['decimal_place'],
					'value'         => $result['value'],
					'status'        => $result['status'],
					'date_modified' => $result['date_modified']
				);
			}

			$this->cache->set('currency', $currency_data);
		}

		return $currency_data;
	}
}