<?php
class ControllerToolCurrency extends Controller
{

	public function index()
	{

		if ($this->config->get('config_currency_auto') AND $this->config->get('config_free_currencyconverterapi')) {
			$log = new Log("currency.txt");
			$this->load->model('localisation/currency');
			$currencyies = $this->model_localisation_currency->getCurrencies();

			foreach ($currencyies as $key => $currency) {

				$update_link = 'http://free.currencyconverterapi.com/api/v5/convert?q=TRY_' . $key . '&compact=y&apiKey=' . $this->config->get('config_free_currencyconverterapi');

				$curl = curl_init($update_link);
				curl_setopt($curl, CURLOPT_HEADER, false);
				//curl_setopt($curl, CURLOPT_POST, true);
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($curl, CURLOPT_VERBOSE, true);
				curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

				$json_response = curl_exec($curl);

				$response = json_decode($json_response, true);



				if (isset($response['TRY_' . $key]['val'])) {

					$this->db->query("UPDATE ps_currency SET value='" . (float)$response['TRY_' . $key]['val'] . "' WHERE currency_id='" . $currency['currency_id'] . "' ");
					$log->write($currency['currency_id'] . ' - ' . $key . ' => ' . $response['TRY_' . $key]['val']);
				}
			}


			$log->write("#########################################################################################################");

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