<?php
/*
	Stempora Web Framework
	Copyright (c) 2002-2014 Stempora. 
	All rights reserved.
		web:  www.stempora.com
		mail: support@stempora.com		
*/

// dependencies

/**
* description
*
* @library	
* @author	
* @since	
*/
class CCurrency extends CPlugin{
	
	var $tplvars; 

	function CCurrency() {
		//$this->CPlugin($db, $tables , $templates);
	}

	function DoEvents(){
		global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS;

		parent::DoEvents();

		if ($_GET["mod"] == "currency") {
			$this->__init();

			switch ($_GET["sub"]) {
				case "change":
					return $this->ChangeCurrency();
				break;
			}
		}


		if ($_GET["submod"] == "currency") {
			return $this->CronTab();
		}

		
	}

	function __init() {
		global $_CONF;

		if ($this->__inited) {
			return "";
		}

		$this->__inited = true;
		
		$path = $this->tpl_path;

		$templates = array(
			"menu"				=> "menu.htm",
		);

		foreach ($templates as $key => $val) {
			$this->private->templates[$key] = new CTemplateDynamic(
				$path . $val
			);
		}

		$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("currency");

	} 

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __loadCurrencies() {
		$this->__init();

		if (!$this->loaded) {

			$rates = $this->db->QFetchRowArray(
				"SELECT * FROM 
					{$this->tables['plugin:currency_rates']}
				WHERE
					cur_code LIKE '%s' OR 
					cur_code LIKE '%s'
					
				",
				array(
					$_COOKIE["currency"] ? $_COOKIE["currency"] : $this->tpl_module["settings"]["set_default_site"],
					$this->tpl_module["settings"]["set_default"],
				)
			);

			if (is_array($rates)) {
				foreach ($rates as $key => $val) {
					$this->rates[$val["cur_code"]] = $val;
				}
				
			}
			
		}
		


		$this->loaded = true;
	}
	
	
		
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function FormatPrice($price , $type = "") {

		$this->__loadCurrencies();



		$current = $_COOKIE["currency"] ? $_COOKIE["currency"] : $this->tpl_module["settings"]["set_default_site"];
		$default = $this->tpl_module["settings"]["set_default"];


		//process the price

		$price = $price / $this->rates[$current]["cur_rate"];
		$price = number_format((float)$price , 2 , "." , "");

	
		switch ($type) {
			case "split":

				$tmp = explode("." , $price);
				
				return array(
					"pref"	=> $this->rates[$current]["cur_pref"],
					"suf"	=> $this->rates[$current]["cur_suf"],
					"cur"	=> $this->rates[$current]["cur_code"],
					"num"	=> $tmp[0] , 
					"dec"	=> $tmp[1]
				);
			break;


			case "numeric":
				return $price;
			break;


			case "int":

				$tmp = explode("." , $price);

				return "$ ". $tmp[0];
			break;

			default: 
				return "$ " . $price;
			break;
		}		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function GetCurrencyCode() {
		return "USD";
	}
	


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function CurrencyMenu($template = null) {
		global $base , $_CONF;

		if (!$this->tpl_module["settings"]["set_menu"]) {
			return "";
		}
		

		$rates = $this->db->QFetchRowArray(
			"SELECT * FROM {$this->tables['plugin:currency_rates']} WHERE cur_status = 1 ORDER BY cur_code"
		);

		if ($template === null) {
			$template = &$this->private->templates["menu"];
		}
		

		if (is_array($rates) && (count($rates) > 1)) {

			if ($_COOKIE["currency"]) {
				$default = $_COOKIE["currency"];
			} elseif ($this->tpl_module["settings"]["set_default_site"]) {
				$default = $this->tpl_module["settings"]["set_default_site"];
			} else {
				$default = $this->tpl_module["settings"]["set_default"];
			}
			
			foreach ($rates as $key => $val) {

				$rates[$key]["link"] = $val["link"] = "__locale__/currency/"  .  $val["cur_code"] . "/";

				if ($val["cur_code"] == $default) {
					$rates[$key]["selected"] = $template->blockReplace("Selected" , $val);
					$rate = $val;
				}
				
			}
			
			
			return $base->html->Table(
				$template , 
				"" , 
				$rates,
				array(
					"current"	=> $template->blockReplace("Current" , $rate),
					"link"		=> $_CONF["url"] . "__locale__/currency",
				)
			);

		} else {
			return "";
		}
		
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ChangeCurrency() {
		global $_CONF;

		$cur = $this->db->QFetchArray(
			"SELECT * FROM {$this->tables['plugin:currency_rates']} WHERE cur_code LIKE '%s'",
			array(
				$_GET["cur_code"]
			)
		);

		if (is_array($cur)) {
			setcookie ( 
				"currency" , 
				$_GET["cur_code"],
				time() + 3600 * 24 * 30, 
				"/"
			);
		}
		
		if ($_SERVER["HTTP_REFERER"]) {	
			header("Location: " . $_SERVER["HTTP_REFERER"] , true , "301");
			die();
		} else {
			header("Location: " . $_CONF["url"] , true , "301");
			die();
		}

	}
	
		

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function onGlobalHooksExecute($module) {
		global $_LANG_ID , $_TSM , $base;

		$this->__init();

		$_TSM["PUB:CURRENCY_MENU"] = $this->CurrencyMenu();

	}



	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function CronTab($module) {

		$this->__init();
	
		switch ($this->tpl_module["settings"]["set_update"]) {
			//manual
			default:
			break;

			//open exchange
			case "2":
				$this->OpenExchange();
				debug($this->tpl_module,1);
			break;

			//central europan bank
			case "3":
			break;
		}
		
		//throw new Exception('Error runing feeds.');
	}
	

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function OpenExchange() {

		$this->__init();
		
//		$path = "https://openexchangerates.org/api/latest.json?app_id=" . $this->tpl_module["settings"]["set_openexchange_api"];

		$path = "http://supremeinstall2.templates.office.stempora.com/api.json";


		$rates = CHTTP::NewInstance()
			->Get($path)
			->Json();


		$default = $this->db->QFetchArray(
			"SELECT * FROM {$this->tables['plugin:currency_rates']} WHERE cur_id=%d" , 
			array(
				$this->tpl_module["settings"]["set_default"]
			)
		);

		if (is_array($default)) {
			$rate = $rates["rates"][$default["cur_code"]];

			$this->db->QueryUpdate(
				$this->tables["plugin:currency_rates"],
				array(					
					"cur_last_update"		=> time(),
					"cur_rate"				=> "1",
				),
				"cur_id = {$default[cur_id]}"
			);

			//update the usd rate
			$this->db->QueryUpdate(
				$this->tables["plugin:currency_rates"],
				array(					
					"cur_last_update"		=> time(),
					"cur_rate"				=> 1/$rate,
				),
				"cur_code LIKE 'USD'"
			);

		} else{
			//throw new Exception("No default currency set!");
		}
		

		if (is_array($rates["rates"])) {


			foreach ($rates["rates"] as $key => $val) {

				if (($key != $default["cur_code"] ) && ($key != "USD") && is_array($old = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:currency_rates']} WHERE cur_code LIKE '{$key}'"))) {

					$this->db->QueryUpdate(
						$this->tables["plugin:currency_rates"],
						array(					
							"cur_last_update"		=> time(),
							"cur_rate"				=> 1 * $val/ $rate,
						),
						"cur_id = {$old[cur_id]}"
					);

				}
				
			}
			
		}
		

	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ConvertRate($to , $from = null) {
		

	}

}

?>