<?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 VPCTHelperOrder extends JObject
{
	public $virtuemart_order_id;
	public $invoice_number;
	public $virtuemart_user_id;
	public $virtuemart_vendor_id;
	public $order_number;
	public $customer_number;
	public $order_pass;
	public $order_create_invoice_pass;
	public $order_total;
	public $order_total_rounded;
	public $order_salesPrice;
	public $order_salesPrice_after_couponDiscount;
	public $order_billTaxAmount;
	public $order_billTax;
	public $order_billDiscountAmount;
	public $order_discountAmount;
	public $order_subtotal;
	public $order_subtotal_after_couponDiscount;
	public $order_tax;
	public $order_shipment;
	public $order_shipment_tax;
	public $order_payment;
	public $order_payment_tax;
	public $coupon_discount;
	public $coupon_code;
	public $order_discount;
	public $order_currency;
	public $order_currency_code;
	public $order_status;
	public $order_status_name;
	public $user_currency_id;
	public $user_currency_rate;
	public $user_currency_code;
	public $total_in_user_currency;
	public $payment_currency_id;
	public $payment_currency_code;
	public $payment_currency_rate;
	public $total_in_payment_currency;
	public $virtuemart_paymentmethod_id;
	public $payment_method;
	public $virtuemart_shipmentmethod_id;
	public $shipment_method;
	public $oc_note;
	public $delivery_date;
	public $order_language;
	public $customer_note;
	public $ip_address;
	public $created_on;
	public $created_by;
	public $modified_on;
	public $modified_by;
	public $bill_to;
	public $ship_to;
	public $details;
	public $items;
	public $history;
	public $vendor;
	public $currency;
	public $order_link;
	public $order_link_raw;
	public $pdf_link;

	protected $_processed  = false;
	protected $_currencies = array();
	protected $_countries  = array();
	protected $_states     = array();
	
	protected $_constructor;
	
	function __construct($order = null, $constructor = null)
	{
		if ($order)
		{
			if (isset($order['details']) && isset($order['details']['BT']))
			{
				$this->setProperties($order['details']['BT']);
			}
			
			$this->setProperties($order);
			
			if ($constructor)
			{
				$this->_constructor = $constructor;
			}
			
			return true;
		}

		return false;
	}
	
	/**
	 * Modifies a property of the object, creating it if it does not already exist.
	 *
	 * @param   string  $property  The name of the property.
	 * @param   mixed   $value     The value of the property to set.
	 *
	 * @return  mixed  Previous value of the property.
	 *
	 * @since   1.0
	 */
	public function set($property, $value = null)
	{
		if (property_exists($this, $property))
		{
			$previous = isset($this->$property) ? $this->$property : null;
			$this->$property = $value;
			
			return $previous;
		}
	}
	
	public function process($withAddress = false, $reload = false)
	{
		if ($this->_processed && !$reload)
		{
			return true;
		}
		
		if (!empty($this->order_billTax) && is_string($this->order_billTax))
		{
			$this->order_billTax = @json_decode($this->order_billTax);
			$this->order_billTax = is_object($this->order_billTax) ? (array) $this->order_billTax : $this->order_billTax;
		}
		
		// Get invoice number
		$this->invoice_number = VmModel::getModel('orders')->getInvoiceNumber($this->virtuemart_order_id);
		
		if (isset($this->details['BT']) && !isset($this->details['ST']))
		{
			$this->details['ST'] = $this->details['BT'];
		}
		
		if ($withAddress)
		{
			if (!class_exists('VirtueMartModelUserfields'))
			{
				require(VMPATH_ADMIN . '/models/userfields.php');
			}
			
			$userFieldsModel = VmModel::getModel('userfields');
			
			$userFields = $userFieldsModel->getUserFields(
				'account',
				array('captcha' => true, 'delimiters' => true), // Ignore these types
				array('delimiter_userinfo','user_is_vendor' ,'username','password', 'password2', 'agreed', 'address_type') // Skips
			);
			
			$this->bill_to = $userFieldsModel->getUserFieldsFilled($userFields, $this->details['BT']);
			
			$userFields = $userFieldsModel->getUserFields(
				'shipment',
				array(), // Default switches
				array('delimiter_userinfo', 'username', 'email', 'password', 'password2', 'agreed', 'address_type') // Skips
			);

			$this->ship_to = $userFieldsModel->getUserFieldsFilled($userFields, $this->details['ST']);
		}
		
		if (!class_exists('vmPSPlugin'))
		{
			require(JPATH_VM_PLUGINS . '/vmpsplugin.php');
		}
		
		$dispatcher = JDispatcher::getInstance();
		
		JPluginHelper::importPlugin('vmshipment');
		
		$this->shipment_method = '';
		$return = $dispatcher->trigger('plgVmOnShowOrderFEShipment',array($this->virtuemart_order_id, $this->virtuemart_shipmentmethod_id, &$this->shipment_method));
		
		JPluginHelper::importPlugin('vmpayment');
		
		$this->payment_method = '';
		$return = $dispatcher->trigger('plgVmOnShowOrderFEPayment',array($this->virtuemart_order_id, $this->virtuemart_paymentmethod_id, &$this->payment_method));
		
		if (!class_exists('CurrencyDisplay'))
		{
			require(VMPATH_ADMIN . '/helpers/currencydisplay.php');
		}
		
		if (empty($this->user_currency_id))
		{
			$this->user_currency_id = $this->order_currency;
			$this->user_currency_rate = 1;
		}
		
		if (empty($this->payment_currency_id))
		{
			$this->payment_currency_id = $this->user_currency_id;
			$this->payment_currency_rate = $this->user_currency_rate;
		}
		
		$paymentCurrency = CurrencyDisplay::getInstance ($this->payment_currency_id, $this->virtuemart_vendor_id);
		$paymentCurrency->exchangeRateShopper = $this->payment_currency_rate;
		
		if (!class_exists('ShopFunctions'))
		{
			require(VMPATH_ADMIN . '/helpers/shopfunctions.php');
		}
		
		$this->payment_currency_code     = ShopFunctions::getCurrencyByID($this->payment_currency_id, 'currency_code_3');
		$this->total_in_payment_currency = $paymentCurrency->roundForDisplay($this->order_total, $this->payment_currency_id);
		
		if ($this->user_currency_id != $this->payment_currency_id)
		{
			$currency = CurrencyDisplay::getInstance ($this->user_currency_id, $this->virtuemart_vendor_id);
			$currency->exchangeRateShopper = $this->user_currency_rate;
			
			$this->currency = $currency;
			
			$this->user_currency_code     = ShopFunctions::getCurrencyByID($this->user_currency_id, 'currency_code_3');
			$this->total_in_user_currency = $currency->roundForDisplay($this->order_total, $this->user_currency_id);
		}
		else
		{
			$this->currency = $paymentCurrency;
			$this->user_currency_code     = $this->payment_currency_code;
			$this->total_in_user_currency = $this->total_in_payment_currency;
		}
		
		$this->_currencies['user'] = $this->currency;
		$this->_currencies['vendor'] = $this->currency;
		
		$couponDiscount = 0;
		
		if (!empty($this->coupon_discount))
		{
			$couponDiscount = floatval($this->coupon_discount);
			
			if ($couponDiscount < 0)
			{
				$couponDiscount = $couponDiscount * -1;
			}
		}
		
		$order_salesPrice_after_couponDiscount = $this->order_salesPrice - $couponDiscount;
		$order_subtotal_after_couponDiscount = $this->order_subtotal - $couponDiscount;
		
		if ($this->order_currency != $this->payment_currency_id)
		{
			$orderCurrency = CurrencyDisplay::getInstance ($this->order_currency, $this->virtuemart_vendor_id);
			
			$this->_currencies['vendor'] = $orderCurrency;
			
			$this->order_currency_code = ShopFunctions::getCurrencyByID($this->order_currency, 'currency_code_3');
			$this->order_total_rounded = $orderCurrency->roundForDisplay($this->order_total);
			
			$this->order_salesPrice_after_couponDiscount = $orderCurrency->roundForDisplay($order_salesPrice_after_couponDiscount);
			$this->order_subtotal_after_couponDiscount   = $orderCurrency->roundForDisplay($order_subtotal_after_couponDiscount);
		}
		else
		{
			$this->order_currency_code = $this->payment_currency_code;
			$this->order_total_rounded = $this->total_in_payment_currency;
			
			$this->order_salesPrice_after_couponDiscount = $paymentCurrency->roundForDisplay($order_salesPrice_after_couponDiscount, $this->payment_currency_id);
			$this->order_subtotal_after_couponDiscount   = $paymentCurrency->roundForDisplay($order_subtotal_after_couponDiscount, $this->payment_currency_id);
		}
		
		if (!empty($this->order_status))
		{
			$order_status_name = $this->_constructor->getOrderStatusName($this->order_status);
			
			if (!empty($order_status_name))
			{
				$this->order_status_name = $order_status_name;
			}
		}
		
		if (!empty($this->order_status_name))
		{
			$this->order_status_name = JText::_($this->order_status_name);
		}
		
		$user = JFactory::getUser();
		
		if ($user->guest)
		{
			$this->order_link_raw = 'index.php?option=com_virtuemart&view=orders&layout=details&order_pass=' . $this->order_pass . '&order_number=' . $this->order_number;
			$this->order_link     = JRoute::_($this->order_link_raw);
		}
		else
		{
			$this->order_link_raw = 'index.php?option=com_virtuemart&view=orders&layout=details&virtuemart_order_id=' . $this->virtuemart_order_id;
			$this->order_link     = JRoute::_($this->order_link_raw);
		}
		
		if (!empty($this->invoice_number) && ($sPath = shopFunctions::checkSafePath()))
		{
			if (!class_exists('shopFunctionsF'))
			{
				require(VMPATH_SITE . '/helpers/shopfunctionsf.php');
			}
			
			$path = $sPath . shopFunctionsF::getInvoiceFolderName() . DIRECTORY_SEPARATOR . shopFunctionsF::getInvoiceName($this->invoice_number) . '.pdf';
			
			if (file_exists($path))
			{
				$this->pdf_link = JUri::root(true) . '/index.php?option=com_virtuemart&view=invoice&layout=invoice&format=pdf&tmpl=component&order_number=' . $this->order_number . '&order_pass=' . $this->order_pass;
			}
		}

		$vendorModel  = VmModel::getModel('vendor');
		$this->vendor = $vendorModel->getVendor();
		$vendorModel->addImages($this->vendor, 1);
		
		if (!empty($this->items->order_item_sku))
		{
			$this->items->order_item_sku = trim($this->items->order_item_sku);
		}
		
		$this->_processed = true;
		
		return true;
	}
	
	public function getCurrency($type)
	{
		if (strtolower($type) == 'user')
		{
			return isset($this->_currencies['user']) ? $this->_currencies['user'] : false;
		}
		
		return isset($this->_currencies['vendor']) ? $this->_currencies['vendor'] : false;
	}
	
	public function getCountryISO($country_id, $code = 2)
	{
		$country_id = (int) $country_id;
		
		if (empty($country_id))
		{
			return null;
		}
		
		if (!isset($this->_countries[$country_id]))
		{
			$db    = JFactory::getDbo();
			$query = $db->getQuery(true);
			
			if ($code == 2)
			{
				$query->select($db->quoteName('country_2_code'));
			}
			else
			{
				$query->select($db->quoteName('country_3_code'));
			}
			
			$query->from($db->quoteName('#__virtuemart_countries'))
			      ->where($db->quoteName('virtuemart_country_id') . ' = ' . $country_id);
			
			$db->setQuery($query);
			$this->_countries[$country_id] = $db->loadResult();
		}
		
		return $this->_countries[$country_id];
	}
	
	public function getStateISO($state_id, $code = 2)
	{
		$state_id = (int) $state_id;
		
		if (empty($state_id))
		{
			return null;
		}
		
		if (!isset($this->_states[$state_id]))
		{
			$db    = JFactory::getDbo();
			$query = $db->getQuery(true);
			
			if ($code == 2)
			{
				$query->select($db->quoteName('state_2_code'));
			}
			else
			{
				$query->select($db->quoteName('state_3_code'));
			}
			
			$query->from($db->quoteName('#__virtuemart_states'))
			      ->where($db->quoteName('virtuemart_state_id') . ' = ' . $state_id);
			
			$db->setQuery($query);
			$this->_states[$state_id] = $db->loadResult();
		}
		
		return $this->_states[$state_id];
	}
}