<?php
class ModelLocalisationCurrency extends Model {
	public function addCurrency($data) {
		$this->db->query("INSERT INTO " . DB_PREFIX . "currency SET title = '" . $this->db->escape($data['title']) . "', code = '" . $this->db->escape($data['code']) . "', symbol_left = '" . $this->db->escape($data['symbol_left']) . "', symbol_right = '" . $this->db->escape($data['symbol_right']) . "', decimal_place = '" . $this->db->escape($data['decimal_place']) . "', value = '" . $this->db->escape($data['value']) . "', status = '" . (int)$data['status'] . "', date_modified = NOW()");

		$currency_id = $this->db->getLastId();

		if ($this->config->get('config_currency_auto')) {
			$this->refresh(true);
		}

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

	public function editCurrency($currency_id, $data) {
		$this->db->query("UPDATE " . DB_PREFIX . "currency SET title = '" . $this->db->escape($data['title']) . "', code = '" . $this->db->escape($data['code']) . "', symbol_left = '" . $this->db->escape($data['symbol_left']) . "', symbol_right = '" . $this->db->escape($data['symbol_right']) . "', decimal_place = '" . $this->db->escape($data['decimal_place']) . "', value = '" . $this->db->escape($data['value']) . "', status = '" . (int)$data['status'] . "', date_modified = NOW() WHERE currency_id = '" . (int)$currency_id . "'");

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

	public function deleteCurrency($currency_id) {
		$this->db->query("DELETE FROM " . DB_PREFIX . "currency WHERE currency_id = '" . (int)$currency_id . "'");

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

	public function getCurrency($currency_id) {
		$query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "currency WHERE currency_id = '" . (int)$currency_id . "'");

		return $query->row;
	}

	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 getCurrencies($data = array()) {
		if ($data) {
			$sql = "SELECT * FROM " . DB_PREFIX . "currency";

			$sort_data = array(
				'title',
				'code',
				'value',
				'date_modified'
			);

			if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
				$sql .= " ORDER BY " . $data['sort'];
			} else {
				$sql .= " ORDER BY title";
			}

			if (isset($data['order']) && ($data['order'] == 'DESC')) {
				$sql .= " DESC";
			} else {
				$sql .= " ASC";
			}

			if (isset($data['start']) || isset($data['limit'])) {
				if ($data['start'] < 0) {
					$data['start'] = 0;
				}

				if ($data['limit'] < 1) {
					$data['limit'] = 20;
				}

				$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
			}

			$query = $this->db->query($sql);

			return $query->rows;
		} else {
			$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;
		}
	}

	public function oldRefresh() {
		$currency_data = array();

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

		foreach ($query->rows as $result) {
			$currency_data[] = $this->config->get('config_currency') . $result['code'] . '=X';
			$currency_data[] = $result['code'] . $this->config->get('config_currency') . '=X';
		}

		$curl = curl_init();

		curl_setopt($curl, CURLOPT_URL, 'http://download.finance.yahoo.com/d/quotes.csv?s=' . implode(',', $currency_data) . '&f=sl1&e=.json');
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
		curl_setopt($curl, CURLOPT_TIMEOUT, 30);

		$content = curl_exec($curl);
		
		curl_close($curl);

		$line = explode("\n", trim($content));

		for ($i = 0; $i < count($line); $i = $i + 2) {
			$currency = utf8_substr($line[$i], 4, 3);
			$value = utf8_substr($line[$i], 11, 6);
			
			if ((float)$value < 1 && isset($line[$i + 1])) {
				$value = (1 / utf8_substr($line[$i + 1], 11, 6));
			}	
						
			if ((float)$value) {
				$this->db->query("UPDATE " . DB_PREFIX . "currency SET value = '" . (float)$value . "', date_modified = '" .  $this->db->escape(date('Y-m-d H:i:s')) . "' WHERE code = '" . $this->db->escape($currency) . "'");
			}
		}

		$this->db->query("UPDATE " . DB_PREFIX . "currency SET value = '1.00000', date_modified = '" .  $this->db->escape(date('Y-m-d H:i:s')) . "' WHERE code = '" . $this->db->escape($this->config->get('config_currency')) . "'");

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

public function refresh($force = false)
          {
          $currencies = array();
          $default = $this->config->get('config_currency');
          if ($force)
          {
          $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "currency WHERE code != '" . $this->db->escape($this->config->get('config_currency')) . "'");
          }
          else
          {
          $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "currency WHERE code != '" . $this->db->escape($this->config->get('config_currency')) . "' AND date_modified < '" .  $this->db->escape(date('Y-m-d H:i:s', strtotime('-1 day'))) . "'");
          }          
          foreach ($query->rows as $result)
          {
          if (($result['code'] != $default))
          {
          $currencies[] = $result;
          }
          }          
          if($currencies)
          {
          $tcmb_dosya  = 'http://www.tcmb.gov.tr/kurlar/today.xml';
          $yokla       = @fopen($tcmb_dosya, "r");          
          if($yokla)
          {
          $this->session->data['tcmb'] = "1";
          $connect_tcmb     = simplexml_load_file($tcmb_dosya);          
          $usdefektifsatis 	= $connect_tcmb->Currency[0]->BanknoteSelling;
          $usdefektifalis   = $connect_tcmb->Currency[0]->BanknoteBuying;
          $usdforexsatis    = $connect_tcmb->Currency[0]->ForexSelling;
          $usdforexalis 	  = $connect_tcmb->Currency[0]->ForexBuying;
          $euroefektifsatis = $connect_tcmb->Currency[3]->BanknoteSelling;
          $euroefektifalis  = $connect_tcmb->Currency[3]->BanknoteBuying;
          $euroforexsatis   = $connect_tcmb->Currency[3]->ForexSelling;
          $euroforexalis 	  = $connect_tcmb->Currency[3]->ForexBuying;
          $rubleforexsatis  = $connect_tcmb->Currency[14]->ForexSelling;
          $rubleforexalis 	= $connect_tcmb->Currency[14]->ForexBuying;
          $sterlinefektifsatis  = $connect_tcmb->Currency[4]->BanknoteSelling;
          $sterlinefektifalis 	= $connect_tcmb->Currency[4]->BanknoteBuying;
          $sterlinforexsatis    = $connect_tcmb->Currency[4]->ForexSelling;
          $sterlinforexalis 	  = $connect_tcmb->Currency[4]->ForexBuying;          
          
          //Tercih belirtilmeli
          $dolartercih	  = $usdefektifsatis;
          $eurotercih		  = $euroefektifsatis;
          $rubletercih		= $rubleforexsatis;
          $sterlintercih	= $sterlinefektifsatis;
          
          if($default == "TRY")
          {
          foreach ($currencies as $currency)
          {
          if (isset($currency['code']) and $currency['code'] == "USD")
          {
          $usd = 1/(float)$dolartercih;
          $this->editValueByCode($currency['code'], $usd);
          }
          else if (isset($currency['code']) and $currency['code'] == "EUR")
          {
          $euro = 1/(float)$eurotercih;
          $this->editValueByCode($currency['code'], $euro);
          }
          else if (isset($currency['code']) and $currency['code'] == "RUB")
          {
          $ruble = 1/(float)$rubletercih;
          $this->editValueByCode($currency['code'], $ruble);
          }
          else if (isset($currency['code']) and $currency['code'] == "GBP")
          {
          $sterlin = 1/(float)$sterlintercih;
          $this->editValueByCode($currency['code'], $sterlin);
          }
          }
          }          
          if($default == "USD")
          {
          foreach ($currencies as $currency)
          {
          if (isset($currency['code']) and $currency['code'] == "TRY")
          {
          $usd = (float)$dolartercih;
          $this->editValueByCode($currency['code'], $usd);
          }
          else if (isset($currency['code']) and $currency['code'] == "EUR")
          {
          $euro = (float)$dolartercih/(float)$eurotercih;
          $this->editValueByCode($currency['code'], $euro);
          }
          else if (isset($currency['code']) and $currency['code'] == "RUB")
          {
          $ruble = (float)$dolartercih/(float)$rubletercih;
          $this->editValueByCode($currency['code'], $ruble);
          }
          else if (isset($currency['code']) and $currency['code'] == "GBP")
          {
          $sterlin = (float)$dolartercih/(float)$sterlintercih;
          $this->editValueByCode($currency['code'], $sterlin);
          }
          }
          }          
          if($default == "EUR")
          {
          foreach ($currencies as $currency)
          {
          if (isset($currency['code']) and $currency['code'] == "USD")
          {
          $usd = (float)$eurotercih/(float)$dolartercih;
          $this->editValueByCode($currency['code'], $usd);
          }
          else if (isset($currency['code']) and $currency['code'] == "TRY")
          {
          $euro = (float)$eurotercih;
          $this->editValueByCode($currency['code'], $euro);
          }
          else if (isset($currency['code']) and $currency['code'] == "RUB")
          {
          $ruble = (float)$eurotercih/(float)$rubletercih;
          $this->editValueByCode($currency['code'], $ruble);
          }
          else if (isset($currency['code']) and $currency['code'] == "GBP")
          {
          $sterlin = (float)$eurotercih/(float)$sterlintercih;
          $this->editValueByCode($currency['code'], $sterlin);
          }
          }
          }          
          if($default == "RUB")
          {
          foreach ($currencies as $currency)
          {
          if (isset($currency['code']) and $currency['code'] == "USD")
          {
          $usd = (float)$rubletercih/(float)$dolartercih;
          $this->editValueByCode($currency['code'], $usd);
          }
          else if (isset($currency['code']) and $currency['code'] == "TRY")
          {
          $ruble = (float)$rubletercih;
          $this->editValueByCode($currency['code'], $ruble);
          }
          else if (isset($currency['code']) and $currency['code'] == "EUR")
          {
          $euro = (float)$rubletercih/(float)$eurotercih;
          $this->editValueByCode($currency['code'], $euro);
          }
          else if (isset($currency['code']) and $currency['code'] == "GBP")
          {
          $sterlin = (float)$rubletercih/(float)$sterlintercih;
          $this->editValueByCode($currency['code'], $sterlin);
          }
          }
          }          
          if($default == "GBP")
          {
          foreach ($currencies as $currency)
          {
          if (isset($currency['code']) and $currency['code'] == "USD")
          {
          $usd = (float)$sterlintercih/(float)$dolartercih;
          $this->editValueByCode($currency['code'], $usd);
          }
          else if (isset($currency['code']) and $currency['code'] == "TRY")
          {
          $sterlin = (float)$sterlintercih;
          $this->editValueByCode($currency['code'], $sterlin);
          }
          else if (isset($currency['code']) and $currency['code'] == "RUB")
          {
          $ruble = (float)$sterlintercih/(float)$rubletercih;
          $this->editValueByCode($currency['code'], $ruble);
          }
          else if (isset($currency['code']) and $currency['code'] == "EUR")
          {
          $euro = (float)$sterlintercih/(float)$eurotercih;
          $this->editValueByCode($currency['code'], $euro);
          }
          }
          }          
          $this->cache->delete('currency');
          }
          else
          {
          $this->session->data['tcmb'] = "2";
          }
          }
          $this->editValueByCode($default, '1.00000');
          }
public 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 getTotalCurrencies() {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "currency");

		return $query->row['total'];
	}
}