<?php
/**
 * @package    VP Email Manager
 * @copyright  Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @author     Abhishek Das <info@virtueplanet.com>
 * @link       https://www.virtueplanet.com
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;

/**
 * Mailer helper class.
 */
class VpemHelperRenderer extends JObject
{
	protected $db;
	
	protected static $moustache_registered = false;
	
	protected static $instance = null;

	/**
	* Constructor.
	*
	* @param   array  $config  An optional associative array of configuration settings.
	*
	* @since   1.0
	*/
	public function __construct($config = [])
	{
		$this->db = isset($config['db']) ? $config['db'] : JFactory::getDbo();
		
		// Register Mustache Autoloader class
		JLoader::register('Mustache_Autoloader', JPATH_ADMINISTRATOR . '/components/com_vpem/libraries/Mustache/Autoloader.php');
	}

	/**
	* Method to get the mailer helper instance.
	* 
	* @param  array  $config  An optional associative array of configuration settings.
	* 
	* @return object  VPAdvancedUserHelperMailer instance
	*/
	public static function getInstance($config = [])
	{
		if (self::$instance === null)
		{
			self::$instance = new self($config);
		}
		
		return self::$instance;
	}

	/**
	* Method to render email with Mustache.
	* 
	* @param  array    $data            Data array
	* @param  string   $emailSubject    Empty email subject string
	* @param  string   $emailBody       Empty email body string
	* @param  objecy   $mustache        Optional Mustache instance
	* @param  boolean  $html_mode       Optional HTML mode. Default is html.
	* 
	* @return boolean  False in case of failure.
	*/
	public function renderMail($data, &$emailSubject, &$emailBody, $mustache = null, $html_mode = true)
	{
/*		if (empty($template->id) || !is_array($data))
		{
			$this->setError('Email template rendering failed. Invalid template or data.');
			return false;
		}*/
		
		$filter = JFilterInput::getInstance();
		
		if (!$mustache)
		{
			// Get Mustache instance
			if (!$mustache = $this->getMustache($html_mode))
			{
				$this->setError($this->getError());
				return false;
			}
		}
		
		// Render email subject
		$emailSubject = $mustache->render($emailSubject, $data);
		$emailSubject = $filter->clean($emailSubject);
		
		// Render email body
		$emailBody    = $mustache->render($emailBody, $data);
		
		if (!$html_mode)
		{
			// Ensure plain text email body
			$emailBody = $filter->clean($emailBody);
		}

		return true;
	}

	/**
	* Method to get a new Mustache engine instance.
	* 
	* @param boolean $html_mode True if html mode
	* 
	* @return mixed (object/boolean) False in case of failure
	*/
	public function getMustache($html_mode = true)
	{
		// If Mustache Autoloader class is not found throw an error
		if (!class_exists('Mustache_Autoloader'))
		{
			$this->setError('Mustache library not loaded.');
			
			return false;
		}
		
		// Register Mustache autoloader if not registered yet
		if (!self::$moustache_registered)
		{
			Mustache_Autoloader::register();
			
			self::$moustache_registered = true;
		}
		
		// Build a new Mustache engine instance
		$mustache = new Mustache_Engine([
			'escape' => function($value) {
				return $value;
			},
			'charset' => 'UTF-8',
			'strict_callables' => false
		]);
		
		// Register helper classes
		JLoader::register('VpemHelperMustacheJText', __DIR__ . '/mustache/jtext.php');
		JLoader::register('VpemHelperMustacheDo',    __DIR__ . '/mustache/do.php');
		
		// Add Mustache JText helper
		$JTextHelper = new VpemHelperMustacheJText(['html' => $html_mode]);
		$mustache->addHelper('JText', $JTextHelper);
		
		// Add Mustache Do helper
		$DoHelper = new VpemHelperMustacheDo();
		$mustache->addHelper('do', $DoHelper);

		return $mustache;
	}
}
