<?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\CMS\Factory;

class VpemHelperMustacheJtext
{
	protected $html;
	
	public function __construct($config = [])
	{
		$this->html = isset($config['html']) ? $config['html'] : true;
	}
	
	public function _()
	{
		return [$this, 'do_'];
	}
	
	public function do_($string, \Mustache_LambdaHelper $helper)
	{
		$string = (string) $string;
		$string = $helper->render($string);
		
		$string = JText::_(strtoupper($string));
		
		if ($this->html)
		{
			//$string = $this->doLink($string);
			$string = nl2br($string);
		}
		
		return $string;
	}
	
	public function sprintf()
	{
		return [$this, 'doSprintf'];
	}
	
	public function doSprintf($string, \Mustache_LambdaHelper $helper)
	{
		$lang = Factory::getLanguage();
		
		if (strpos($string, ',') === false)
		{
			$string = $helper->render($string);
			
			return $lang->_($string);
		}

		$args = explode(',', $string);
		$args = array_map('trim', $args);
		
		$args[0] = $helper->render($args[0]);
		$args[0] = $lang->_($args[0]);

		// Replace custom named placeholders with sprintf style placeholders
		$args[0] = preg_replace('/\[\[%([0-9]+):[^\]]*\]\]/', '%\1$s', $args[0]);

		$string = call_user_func_array('sprintf', $args);
		
		if ($this->html)
		{
			//$string = $this->doLink($string);
			$string = nl2br($string);
		}
		
		return $string;
	}
	
	public function doLink($string, \Mustache_LambdaHelper $helper)
	{
		$string = $helper->render($string);
		
		return preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank">$1</a>', $string);
	}
}
