<?php
/**
 *---------------------------------------------------------------------------------------
 * @package      VP Conversion Tracking - Joomla! System Plugin
 * @subpackage   For VirtueMart 3+
 *---------------------------------------------------------------------------------------
 * @copyright    Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license      GNU General Public License version 2 or later; see LICENSE.txt
 * @authors      Abhishek Das
 * @email        info@virtueplanet.com
 * @link         https://www.virtueplanet.com
 *---------------------------------------------------------------------------------------
*/
defined ('_JEXEC') or die;

class VPCTHelperMustache
{
	protected $isHTML = false;
	protected $_mustache = null;
	protected $_constructor = null;
	protected $_debug = false;
	
	function __construct($data = null, $mustache = null, $constructor = null)
	{
		$config = JFactory::getConfig();

		if (($config->get('error_reporting') == 'development' || $config->get('error_reporting') == 'maximum') || $config->get('debug'))
		{
			$this->_debug = true;
		}
		else
		{
			$this->_debug = false;
		}
		
		if ($data)
		{
			if ($mustache instanceof Mustache_Engine)
			{
				$this->_mustache = $mustache;
			}
			
			if ($constructor)
			{
				$this->_constructor = $constructor;
			}
			
			// Over load order data
			$this->setProperties($data, $constructor);
		}
	}
	
	public function __isset($method)
	{
		return method_exists($this, '_' . $method);
	}
	
	public function __get($method)
	{
		return array($this, '_' . $method);
	}
	
	public function set($property, $value)
	{
		$property = (string) $property;
		
		$this->$property = $value;
	}

	public function _escape($string)
	{
		$string = $this->renderMustacheVar($string);
		
		return htmlspecialchars($string, ENT_COMPAT, 'UTF-8');
	}
	
	public function _strip_tags($string)
	{
		$string = $this->renderMustacheVar($string);
		
		return strip_tags($string);
	}
	
	public function _htmlspecialchars($string)
	{
		if (strpos($string, ',') === false)
		{
			$args = array($string);
		}
		else
		{
			$args = explode(',', $string);
			$args = array_map('trim', $args);
		}
		
		$args[0] = $this->renderMustacheVar($args[0]);
		
		if (isset($args[1]))
		{
			$args[1] = constant($args[1]);
		}
		
		return call_user_func_array('htmlspecialchars', $args);
	}
	
	public function _JText($string)
	{
		$lang = JFactory::getLanguage();
		
		if (strpos($string, ',') === false)
		{
			$string = $this->renderMustacheVar($string);
			
			return $lang->_(strtoupper($string));
		}

		$args = explode(',', $string);
		$args = array_map('trim', $args);

		$args[0] = $lang->_(strtoupper($args[0]));

		// Replace custom named placeholders with sprintf style placeholders
		$args[0] = preg_replace('/\[\[%([0-9]+):[^\]]*\]\]/', '%\1$s', $args[0]);
		
		foreach($args as $key => &$value)
		{
			if ($key > 0)
			{
				$args[$key] = $this->renderMustacheVar($args[$key]);
			}
		}

		$string = call_user_func_array('sprintf', $args);
		
		if ($this->isHTML)
		{
			$string = nl2br($string);
		}
		
		return $string;
	}
	
	public function _round($string)
	{
		if (empty($string))
		{
			return $string;
		}
		
		$input = $string;
		$type  = 'vendor';
		
		if (strpos($string, ',') !== false)
		{
			$args = explode(',', $string);
			$args = array_map('trim', $args);
			
			if (isset($args[0]))
			{
				$input = $args[0];
			}
			
			if (isset($args[1]))
			{
				$type = (string) $args[1];
			}
		}
		
		$value = $this->renderMustacheVar($input);
		
		if (!is_numeric($value) && $value == $input)
		{
			return $input;
		}
		
		$currency = $this->_constructor->getCurrency($type); 
		
		if ($type == 'user')
		{
			$value = $currency->roundForDisplay($value, $this->user_currency_id);
		}
		else
		{
			$value = $currency->roundForDisplay($value);
		}

		return $value;
	}
	
	public function _math($string)
	{
		$value = $this->renderMustacheVar($string);
		
		if (empty($value))
		{
			return $value;
		}
		
		if (!class_exists('EvalMath'))
		{
			require VPCT_PATH . '/libraries/evalmath/evalmath.class.php';
		}
		
		$m = new EvalMath;

		if (!$this->_debug)
		{
			$m->suppress_errors = true;
		}
		else
		{
			$m->suppress_errors = false;
		}
		
		$result = $m->evaluate($value);
		
		return $result;
	}
	
	public function _date($string)
	{
		$input  = '';
		$format = 'Y-m-d';
		$offset = 0;

		if (!empty($string))
		{
			$input = trim($string);
		}
		
		// Expected format (date, format, offset)
		// Offset must be in hours
		
		if (strpos($string, ',') !== false)
		{
			$args = explode(',', $string);
			$args = array_map('trim', $args);
			
			if (isset($args[0]))
			{
				$input = $args[0];
			}
			
			if (isset($args[1]))
			{
				$format = (string) $args[1];
			}
			
			if (isset($args[2]))
			{
				$offset = (int) $args[2];
			}
		}
		
		if (!empty($input))
		{
			$input = $this->renderMustacheVar($input);
		}
		
		if ($input == JText::_('COM_VIRTUEMART_DELDATE_INV'))
		{
			$input = $this->renderMustacheVar('{{ created_on }}');
		}

		if (empty($input) || !self::validateDate($input))
		{
			$input = 'now';
		}

		// Get Joomla! Global Config
		$config = JFactory::getConfig();
		
		// Get a date object based on UTC.
		$date = JFactory::getDate($input, 'UTC');
		
		// Set the correct time zone based on the server configuration.
		$date->setTimeZone(new DateTimeZone($config->get('offset')));
		
		if ($offset)
		{
			if ($offset < 0)
			{
				$interval = new DateInterval('PT' . ($offset * -1) . 'H');
				
				$date->sub($interval);
			}
			else
			{
				$interval = new DateInterval('PT' . $offset . 'H');
				
				$date->add($interval);
			}
		}
		
		return $date->format($format, true);
	}
	
	public function _country_to_iso($input)
	{
		$format = 2;
		
		if (!empty($input))
		{
			if (strpos($input, ',') !== false)
			{
				$args = explode(',', $input);
				$args = array_map('trim', $args);
				
				if (isset($args[0]))
				{
					$input = $args[0];
				}
				
				if (isset($args[1]))
				{
					$format = (string) $args[1];
				}
			}
			
			$input = $this->renderMustacheVar($input);
		}
		
		$iso_code = $this->_constructor->getCountryISO($input, $format);

		if (!$iso_code)
		{
			return '';
		}
		
		return $iso_code;
	}
	
	public function _state_to_iso($input)
	{
		$format = 2;
		
		if (!empty($input))
		{
			if (strpos($input, ',') !== false)
			{
				$args = explode(',', $input);
				$args = array_map('trim', $args);
				
				if (isset($args[0]))
				{
					$input = $args[0];
				}
				
				if (isset($args[1]))
				{
					$format = (string) $args[1];
				}
			}
			
			$input = $this->renderMustacheVar($input);
		}
		
		$iso_code = $this->_constructor->getStateISO($input, $format);
		
		if (!$input)
		{
			return '';
		}
		
		return $iso_code;
	}

	protected function renderMustacheVar($string)
	{
		if ($this->_mustache)
		{
			$string = $this->_mustache->render($string, $this);
		}
		
		return $string;
	}
	
	protected static function validateDate($date)
	{
		$db = JFactory::getDbo();
		$d  = DateTime::createFromFormat($db->getDateFormat(), $date);

		return $d && $d->format($db->getDateFormat()) === $date;
	}
	
	protected function setProperties($data)
	{
		$array = is_object($data) ? get_object_vars($data) : $data;
		
		foreach($array as $property => $value)
		{
			if (isset($data->$property))
			{
				$this->$property = $value;
			}
		}
	}
}