<?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;

class VpemHelperOrderdata extends VpemHelperMustache
{
	public function __construct($data = null, $mustache = null, $constructor = null)
	{
		parent::__construct($data, $mustache, $constructor);
		
		$this->setVendor();
	}
	
	protected function setProperties($order)
	{
		if ($this->_constructor === null)
		{
			$this->_constructor = $order;
		}
		
		$array = is_object($order) ? get_object_vars($order) : $order;
		
		foreach ($array as $property => $value)
		{
			if (isset($order->$property))
			{
				if ($property == 'items' && is_array($value))
				{
					foreach ($value as $key => &$item)
					{
						$value[$key] = new VpemHelperOrderitem($item, $this->_mustache, $this->_constructor);
					}
				}
				
				$this->$property = $value;
			}
		}
	}
	
	public function _country_to_iso($input, \Mustache_LambdaHelper $helper)
	{
		$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 = $helper->render($input);
		}
		
		$iso_code = $this->_constructor->getCountryISO($input, $format);

		if (!$iso_code)
		{
			return '';
		}
		
		return $iso_code;
	}
	
	public function _state_to_iso($input, \Mustache_LambdaHelper $helper)
	{
		$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 = $helper->render($input);
		}
		
		$iso_code = $this->_constructor->getStateISO($input, $format);
		
		if (!$input)
		{
			return '';
		}
		
		return $iso_code;
	}
	
	public function _in_user_currency($input, \Mustache_LambdaHelper $helper)
	{
		$orderDetails         = $this->_constructor;
		$user_currency_id     = $orderDetails->details['BT']->user_currency_id;
		$virtuemart_vendor_id = !empty($orderDetails->details['BT']->virtuemart_vendor_id) ? $orderDetails->details['BT']->virtuemart_vendor_id : 1;
		
		JPluginHelper::importPlugin('vmpayment');
		
		$dispatcher = JDispatcher::getInstance();
		$dispatcher->trigger('plgVmgetEmailCurrency', [$orderDetails->details['BT']->virtuemart_paymentmethod_id, $orderDetails->details['BT']->virtuemart_order_id, &$user_currency_id]);

		$currency = CurrencyDisplay::getInstance($user_currency_id, $virtuemart_vendor_id);
		
		if ($user_currency_id)
		{
			$currency->exchangeRateShopper = $orderDetails->details['BT']->user_currency_rate;
		}
		
		if (!empty($input))
		{
			if (strpos($input, ',') !== false)
			{
				$args = explode(',', $input);
				$args = array_map('trim', $args);
				
				foreach ($args as &$arg)
				{
					$arg = $helper->render($arg);
				}
			}
			else
			{
				$input = $helper->render($input);
				$args  = [$input];
			}
			
			if (!isset($args[1]) && isset($args[0]))
			{
				$args[1] = $user_currency_id;
			}
		}
		
		$result = call_user_func_array([$currency, 'priceDisplay'], $args);
		
		return strip_tags($result);
	}
	
	public function _in_shop_currency($input, \Mustache_LambdaHelper $helper)
	{
		$orderDetails         = $this->_constructor;
		$user_currency_id     = $orderDetails->details['BT']->user_currency_id;
		$virtuemart_vendor_id = !empty($orderDetails->details['BT']->virtuemart_vendor_id) ? $orderDetails->details['BT']->virtuemart_vendor_id : 1;
		$vendorModel          = VmModel::getModel('vendor');
		$vendor               = $vendorModel->getVendor($virtuemart_vendor_id);
		$currency             = CurrencyDisplay::getInstance($vendor->vendor_currency, $virtuemart_vendor_id);
		
		if (!empty($input))
		{
			if (strpos($input, ',') !== false)
			{
				$args = explode(',', $input);
				$args = array_map('trim', $args);
				
				foreach ($args as &$arg)
				{
					$arg = $helper->render($arg);
				}
			}
			else
			{
				$input = $helper->render($input);
				$args  = [$input];
			}
		}
		
		$result = call_user_func_array([$currency, 'priceDisplay'], $args);
		
		return strip_tags($result);
	}
	
	public function _comments($string = null)
	{
		$orderDetails = $this->_constructor;
		$nb           = count($orderDetails->history);

		if ($orderDetails->history[$nb-1]->customer_notified && !empty($orderDetails->history[$nb-1]->comments))
		{
			if ($string)
			{
				return $string;
			}

			return nl2br(html_entity_decode($orderDetails->history[$nb-1]->comments));
		}
		
		return '';
	}
	
	public function _order_items_table()
	{
		$orderDetails         = $this->_constructor;
		$user_currency_id     = $orderDetails->details['BT']->user_currency_id;
		$virtuemart_vendor_id = !empty($orderDetails->details['BT']->virtuemart_vendor_id) ? $orderDetails->details['BT']->virtuemart_vendor_id : 1;
		$vendorModel          = VmModel::getModel('vendor');
		$vendor               = $vendorModel->getVendor($virtuemart_vendor_id);

		/*
		 * Deprecated trigger will be renamed or removed
		 */
		JPluginHelper::importPlugin('vmpayment');
		
		$dispatcher = JDispatcher::getInstance();
		$dispatcher->trigger('plgVmgetEmailCurrency', [$orderDetails->details['BT']->virtuemart_paymentmethod_id, $orderDetails->details['BT']->virtuemart_order_id, &$user_currency_id]);

		$currency = CurrencyDisplay::getInstance($user_currency_id, $virtuemart_vendor_id);
		
		if ($user_currency_id)
		{
			$currency->exchangeRateShopper = $orderDetails->details['BT']->user_currency_rate;
		}

		if ($vendor->vendor_currency != $user_currency_id)
		{
			$currencyV = CurrencyDisplay::getInstance($vendor->vendor_currency, $virtuemart_vendor_id);
		}
		else
		{
			$currencyV = $currency;
		}

		if ($user_currency_id != $orderDetails->details['BT']->payment_currency_id)
		{
			$currencyP = CurrencyDisplay::getInstance($orderDetails->details['BT']->payment_currency_id, $virtuemart_vendor_id);
			$currencyP->exchangeRateShopper = $orderDetails->details['BT']->payment_currency_rate;
		}
		else
		{
			$currencyP = $currency;
		}

		$os_trigger_refunds = VmConfig::get('os_trigger_refunds', array('R'));
		
		$toRefund = [];
		
		$orderDetails->details['BT']->order_total = $currency->roundByPriceConfig(floatval($orderDetails->details['BT']->order_total));
		$orderDetails->details['BT']->toPay = $orderDetails->details['BT']->order_total;
		
		foreach ($orderDetails->items as $i => $_item)
		{
			$orderDetails->items[$i]->linkedit = 'index.php?option=com_virtuemart&view=product&task=edit&virtuemart_product_id=' . $_item->virtuemart_product_id;

			if (in_array($_item->order_status,$os_trigger_refunds))
			{
				$toRefund[] = $_item;
				$orderDetails->details['BT']->toPay -= $currency->roundByPriceConfig($_item->product_subtotal_with_tax);
			}
		}
		
		$orderDetails->details['BT']->toPay = $currency->roundByPriceConfig(($orderDetails->details['BT']->toPay));

		$rulesSorted = shopFunctionsF::summarizeRulesForBill($orderDetails->rawOrderDetails);
		
		$discountsBill = $rulesSorted['discountsBill'];
		$taxBill = $rulesSorted['taxBill'];

		//Fallback for old layouts.
		foreach ($taxBill as $i=> $rule)
		{
			$taxBill[$i]->calc_result = $rule->calc_amount;
		}
		
		$params = JComponentHelper::getParams('com_vpem');
		
		$displayData = [
			'orderDetails'     => $orderDetails,
			'currency'         => $currency,
			'currencyV'        => $currencyV,
			'currencyP'        => $currencyP,
			'toRefund'         => $toRefund,
			'discountsBill'    => $discountsBill,
			'taxBill'          => $taxBill,
			'user_currency_id' => $user_currency_id,
			'params'           => $params
		];
		
		return JLayoutHelper::render('order_items', $displayData, null, ['client' => 'site', 'component' => 'com_vpem']);
	}
}