<?php
/**
 *-------------------------------------------------------------------------------------
 * @package    VP Payment by Shipment Plugin for VirtueMart
 *-------------------------------------------------------------------------------------
 * @copyright  Copyright (C) 2012-2019 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('JPATH_BASE') or die;

jimport('joomla.form.formfield');
jimport('joomla.registry.registry');

class JFormFieldVPAdminHelper extends JFormField
{
	public $extension_name = 'VP Payment by Shipment Plugin';
	
	public $extension_url = 'plugins/system/vppaymentbyshipment';
	
	public $extension_version = '1.0';
	
	public $type = 'VPAdminHelper';
	
	protected function getInput()
	{
		$app = JFactory::getApplication();
		
		JLoader::register('VmConfig', JPATH_ADMINISTRATOR . '/components/com_virtuemart/helpers/config.php');
		
		if(class_exists('VmConfig'))
		{
			VmConfig::loadConfig();
		}
		
		if(!defined('VM_VERSION') || !class_exists('VmConfig'))
		{
			$app->enqueueMessage('It appears VirtueMart Component is not installed. ' . $this->extension_name . ' is an extension of VirtueMart Component.', 'error');
			return;
		}
		
		if(VM_VERSION < 3)
		{
			$app->enqueueMessage($this->extension_name . ' is compatible to VirtueMart 3 and above.', 'error');
		}
		
		// Check plugin status
		$xml = $this->form->getXml();
		
		if($xml instanceof SimpleXMLElement && !empty($xml->config))
		{
			$state = 1;
			
			foreach($xml->config->children() as $fields)
			{
				if($fields->attributes()->name == 'params' && isset($fields->fieldset))
				{
					// Getting the fieldset tags
					$fieldsets = $fields->fieldset;
					
					// Iterating through the fieldsets:
					foreach ($fieldsets as $fieldset)
					{
						if (!count($fieldset->children()))
						{
							// Either the tag does not exist or has no children therefore we return zero files processed.
							continue;
						}
						
						// Iterating through the fields and collecting the name/default values:
						foreach ($fieldset as $field)
						{
							$default = (string) $field->attributes()->default;
							
							if ($field->attributes()->name == 'download_key')
							{
								if($field->attributes()->type != 'vpdownloadkey' || ($this->updateEnabled() && $field->attributes()->required != 'true') || !empty($default))
								{
									$state--;
								}
							}
							elseif ($field->attributes()->name == 'adminhelper')
							{
								if($field->attributes()->validate != 'vpsystem' || !empty($default))
								{
									$state--;
								}
							}
						}
					}
				}
			}
			
			if($state < 1)
			{
				throw new Exception('The plugin files are not installed properly in your site. Please download a fresh copy of plugin and reinstall it in your site.');
			}
		}
		
		// Ask Admin to enable "Reload Payment Methods after Shipment Selection" option
		// in VP One Page Checkout plugin if not enabled and if the plugin is enabled.
		if(JPluginHelper::isEnabled('system', 'vponepagecheckout'))
		{
			$vpopc = JPluginHelper::getPlugin('system', 'vponepagecheckout');
			
			$vpopc->params = new JRegistry($vpopc->params);
			
			if($vpopc->params->get('reload_payment_on_shipment_selection', 0) != 1)
			{
				$app->enqueueMessage('Please enable "<b>Reload Payment Methods after Shipment Selection</b>" option under Advanced Options in <b>VP One Page Checkout</b> plugin settings.', 'notice');
			}
			
			VmConfig::loadConfig();
			
			if(VmConfig::get('set_automatic_payment') > 0)
			{
				$app->enqueueMessage('It is adviced that you change "<b>Enable Automatic Selected Payment</b>" option to "<b>No preference</b>" or "<b>None</b>" in <b>VirtueMart Configuration</b> for better handling of the payment methods while using VP Payment by Shipment plugin and VP One Page Checkout plugin together.', 'notice');
			}
		}
		
		$doc  = JFactory::getDocument();
		$root = JUri::root(true);
		
		if(version_compare(JVERSION, '3.0.0', 'ge'))
		{
			$staticJS  = $this->extension_url . '/assets/admin/js/j3/admin.js';
			$staticCSS = $this->extension_url . '/assets/admin/css/j3/admin.css';
		}
		else
		{
			$staticJS = array();
			$staticJS[] = $this->extension_url . '/assets/admin/js/jquery.min.js';
			$staticJS[] = $this->extension_url . '/assets/admin/js/jquery-noconflict.js';
			$staticJS[] = $this->extension_url . '/assets/admin/js/jquery-migrate.min.js';
			$staticJS[] = $this->extension_url . '/assets/admin/js/j2.5/admin.js';
			
			$staticCSS = $this->extension_url . '/assets/admin/css/j2.5/admin.css';
		}
		
		$scripts     = !empty($this->element['scripts']) ? $this->element['scripts'] : $staticJS;
		$styleSheets = !empty($this->element['styleSheets']) ? $this->element['styleSheets'] : $staticCSS;
		
		if(!empty($scripts))
		{
			if(is_string($scripts))
			{
				if(strpos($scripts, ',') !== false)
				{
					$scripts = explode(',', $scripts);
				}
				else
				{
					$scripts = (array) $scripts;
				}
			}
			
			foreach($scripts as $script)
			{
				$path = JPath::clean(JPATH_ROOT . '/' . $script);
				
				if(is_file($path))
				{
					$version = strpos($script, 'j2.5') || strpos($script, 'j3') ? '?ver=' . $this->extension_version : '';
					$doc->addScript($root . '/' . trim($script) . $version);
				}
			}
		}

		if(!empty($styleSheets))
		{
			if(is_string($styleSheets))
			{
				if(strpos($styleSheets, ',') !== false)
				{
					$styleSheets = explode(',', $styleSheets);
				}
				else
				{
					$styleSheets = array($styleSheets);
				}
			}
			
			foreach($styleSheets as $styleSheet)
			{
				$path = JPath::clean(JPATH_ROOT . '/' . $styleSheet);

				if(is_file($path))
				{
					$version = strpos($styleSheet, 'j2.5') || strpos($styleSheet, 'j3') ? '?ver=' . $this->extension_version : '';
					$doc->addStyleSheet($root . '/' . trim($styleSheet) . $version);
				}
			}
		}
		
		return null;
	}
	
	public function getLabel() 
	{
		return null;
	}
	
	protected function updateEnabled()
	{
		$file = JPATH_ROOT . '/plugins/system/vppaymentbyshipment/vppaymentbyshipment.xml';
		
		if(!file_exists($file))
		{
			return true;
		}
		
		if(version_compare(JVERSION, '3.0.0', 'ge'))
		{
			$xml        = JFactory::getXML($file);
			$liveupdate = (int) $xml->liveupdate;
		}
		else
		{
			$parser = JFactory::getXMLParser('Simple');
			
			$parser->loadFile($file);
			
			$doc        = $parser->document;
			$element    = $doc->getElementByPath('liveupdate');
			$liveupdate = (int) $element->data();
		}

		if($liveupdate > 1)
		{
			return false;
		}
		
		return true;
	}
}