<?php
class ControllerCommonCurrency extends Controller {
	public function index() {

        if($this->cache->cache_get($this->session->data['language']. '-common_currency', 'common/'))
            return $this->cache->cache_get($this->session->data['language']. '-common_currency', 'common/');

		$this->load->language('common/currency');
		$data['text_currency'] = $this->language->get('text_currency');
		$data['action'] = $this->url->link('common/currency/currency', '', $this->request->server['HTTPS']);
		$data['code'] = $this->session->data['currency'];
		$this->load->model('localisation/currency');
		$data['currencies'] = array();
		$results = $this->model_localisation_currency->getCurrencies();
		
		$data['eur'] = isset($results['EUR']['value']) ? $results['EUR']['value'] : 0;
		$data['try'] = $results['TRY']['value'];
		$data['usd'] = $results['USD']['value'];

		if($data['try'] != 0.0 AND $data['eur'] != 0.0 AND $data['usd'] != 0.0){
			$data['eur'] = number_format($data['try'] / $data['eur'],4);
			$data['usd'] = number_format($data['try'] / $data['usd'],4);
		}else{
			$data['eur'] = '';
			$data['usd'] = '';
		}

		foreach ($results as $result) {
			if ($result['status']) {
				$data['currencies'][] = array(
					'title'        => $result['title'],
					'code'         => $result['code'],
					'symbol_left'  => $result['symbol_left'],
					'symbol_right' => $result['symbol_right']
				);
			}
		}

		if (!isset($this->request->get['route'])) {
			$data['redirect'] = $this->url->link('common/home','', true);
		} else {
			$url_data = $this->request->get;
			unset($url_data['_route_']);
			$route = $url_data['route'];
			unset($url_data['route']);
			$url = '';
			if ($url_data) {
				$url = '&' . urldecode(http_build_query($url_data, '', '&'));
			}
			$data['redirect'] = $this->url->link($route, $url, $this->request->server['HTTPS']);
		}


        $cache = $this->load->view( DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') .'/template/common/currency', $data);
        $this->cache->cache_set($this->session->data['language']. '-common_currency', $this->cache->minify_to_html($cache), 'common/');
        return $this->cache->cache_get($this->session->data['language']. '-common_currency', 'common/');
		
	}

	public function currency() {
		if (isset($this->request->post['code'])) {
			$this->session->data['currency'] = $this->request->post['code'];
			unset($this->session->data['shipping_method']);
			unset($this->session->data['shipping_methods']);
		}
		
		if (isset($this->request->post['redirect'])) {
			$this->response->redirect($this->request->post['redirect']);
		} else {
			$this->response->redirect($this->url->link('common/home', '', true));
		}
	}
}