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

defined('PHP_EOL') or define('PHP_EOL', "\n");

JLoader::register('VPComDlkHelper', dirname(__FILE__) . '/vpcomdlk/helper.php');

class JFormFieldVPComDlk extends JFormField
{
	protected $type = 'VPComDlk';
	
	protected $_plugin_name = null;
	
	protected function getInput()
	{
		$doc        = JFactory::getDocument();
		$app        = JFactory::getApplication();
		$today      = JFactory::getDate();
		$rel_path   = dirname(__FILE__);
		$rel_path   = str_replace(JPATH_ROOT, '', $rel_path);
		$root       = JUri::root(true) . '/';
		$base_url   = $root . ltrim(str_replace('\\', '/', $rel_path), '/');
		$assets_url = $base_url . '/vpcomdlk/assets';
		$jquery_url = isset($this->element['jqueryurl']) ? $this->element['jqueryurl'] : null;
		$html       = array();

		if (version_compare(JVERSION, '3.0.0', 'ge'))
		{
			JHtml::_('jquery.framework');
		}
		elseif ($jquery_url)
		{
			$doc->addScript($root . $jquery_url . '/jquery.min.js');
			$doc->addScript($root . $jquery_url . '/jquery-noconflict.js');
			$doc->addScript($root . $jquery_url . '/jquery-migrate.min.js');
		}
		
		// Load CSS
		$doc->addStyleSheet($assets_url . '/css/style.css');
		
		// Load JS
		$doc->addScript($assets_url . '/js/script.min.js?ver=1.0');
		
		// Check for available adapters
		$options      = new JRegistry(array('follow_location' => true));
		$adapter      = JHttpFactory::getAvailableDriver($options);
		$enabled      = $this->isEnabled();
		$this->value  = empty($this->value) && (!$enabled || empty($adapter)) ? 'dummy' : $this->value;
		$data         = VPComDlkHelper::decodeData($this->value);
		$last_checked = $data['last_checked'] ? JFactory::getDate($data['last_checked']) : $today;
		$required     = isset($this->element['required']) && $this->element['required'] == 'true' ? ' required="required"' : '';
		$required     = (!$enabled || empty($adapter)) ? '' : $required;
		$btn_class    = !empty($data['dlk']) ? ' vpdk-show-edit' : '';
		$clear_class  = !empty($data['dlk']) ? '' : ' vpdk-hide';
		$interval     = date_diff($last_checked, $today);
		$interval     = (int) $interval->format('%R%a'); // Interval in days
		$revalidate   = ($last_checked != $today) && ($interval > 7) ? ' data-vpdkvalidate="auto"' : '';
		$access_class = !empty($data['dlk']) && !$data['access'] ? '' : ' vpdk-hide';
		$valid_class  = !empty($data['dlk']) && $data['access'] > 0 ? '' : ' vpdk-hide';
		$def_class    = empty($data['dlk']) ? '' : ' vpdk-hide';
		$data_access  = !$data['access'] ? ' data-vpdkaccess="0"' : ' data-vpdkaccess="1"';
		
		$html[] = '<input type="password" id="' . $this->id . '" value="'
		          . htmlspecialchars($data['dlk'], ENT_COMPAT, 'UTF-8') . '" data-vpdk="validate"' . $required . $data_access 
		          . ' autocomplete="off" spellcheck="false" readonly="readonly" />';
		$html[] = '<input type="hidden" id="' . $this->id . '-hidden" name="' . $this->name . '" value="' . $this->value . '" />';
		
		if (!$enabled)
		{
			$html[] = '<div class="vpdk-info-box">';
			$html[] = '<div class="vpdk-info-default">';
			
			if ($this->_plugin_name)
			{
				JError::raiseWarning(100, 'Please enable "' . $this->_plugin_name . '" plugin.');
				
				$html[] = '<p>Please enable "' . $this->_plugin_name . '" plugin.</p>';
			}
			else
			{
				JError::raiseWarning(100, 'Please enable the system plugin of the component.');
				
				$html[] = '<p>Please enable the system plugin of the component.</p>';
			}
			
			$html[] = '</div>';
			$html[] = '</div>';
		}
		elseif (empty($adapter))
		{
			JError::raiseWarning(100, 'JHttpFactory not present. Please upgrade your version of Joomla!.');
		}
		else
		{
			$html[] = '<button type="button" id="' . $this->id . '-button" class="btn' . $btn_class . '" data-vpdktarget="' . $this->id . '-tmpl-modal">';
			$html[] = '<span class="vpdk-add-text">Add</span>';
			$html[] = '<span class="vpdk-edit-text">Edit</span>';
			$html[] = '</button>';
			$html[] = '<button type="button" id="' . $this->id . '-clear-button" class="btn' . $clear_class . '">Clear</button>';
			$html[] = '<button type="button" id="' . $this->id . '-reval-button" class="btn btn-primary vpdk-reval-button' . $clear_class . '"' . $revalidate . '>Revalidate<span class="vpk-btn-overlay"></span></button>';
			$html[] = '<div class="vpdk-info-box">';
			$html[] = '<div class="vpdk-info-noaccess' . $access_class . '">';
			$html[] = '<p>You don\'t have access to the latest updates for this ' . $app->input->getCmd('view', 'extension') . '. Your subscription may have expired or you may not have a valid subscription for this item. To learn more about your subscription plan please visit your <a href="https://www.virtueplanet.com/dashboard" target="_blank">Dashboard</a>.</p>';
			
			if ($last_checked != $today)
			{
				$html[] = '<small>Key verified on: ' . JHtml::_('date', $last_checked, 'F d, Y H:i:s') . '</small>';
			}
			
			$html[] = '</div>';
			$html[] = '<div class="vpdk-info-valid' . $valid_class . '">';
			$html[] = '<p>Your subscription is active and you also have access to live updates.</p>';
			
			if ($last_checked != $today)
			{
				$html[] = '<small>Key verified on: ' . JHtml::_('date', $last_checked, 'F d, Y H:i:s') . '</small>';
			}
			
			$html[] = '</div>';
			$html[] = '<div class="vpdk-info-default' . $def_class . '">';
			$html[] = '<p><a class="muted" href="https://www.virtueplanet.com/download-key/" target="_blank">Forgot Download Key?</a></p>';
			$html[] = '</div>';
			$html[] = '</div>';
			$html[] = $this->getFormTemplate($this->id . '-tmpl');
		}

		return implode(PHP_EOL, $html);
	}
	
	protected function getFormTemplate($id, $html = array())
	{
		$app       = JFactory::getApplication();
		$input     = $app->input;
		$plugin    = !empty($this->element['plugin']) ? (string) $this->element['plugin'] : 'vpem';
		$component = !empty($this->element['component']) ? (string) $this->element['component'] : $input->getCmd('component', '');
		$package   = !empty($this->element['package']) ? (string) $this->element['package'] : '';
		
		if (strpos($plugin, ':') !== false)
		{
			$parts  = explode(':', $plugin);
			$plugin = $parts[1];
		}

		$params    = JComponentHelper::getParams($component);
		$pid       = (int) $params->get('pid', 0);
		
		if (empty($pid) && !empty($component))
		{
			$manifest = JPath::clean(JPATH_ADMINISTRATOR . '/components/' . $component . '/vpem.xml');
			
			if (is_file($manifest))
			{
				$xml = JFactory::getXML($manifest);

				if (!empty($xml) && !empty($xml->pid))
				{
					$pid = (int) $xml->pid;
				}
			}
		}

		if (empty($pid))
		{
			JFactory::getDocument()->addScriptDeclaration("
			jQuery(document).ready(function($) {
				$(document).trigger('vpcom.save.config', $('input#" . $this->id . "'));
			});
			");
		}
		
		$url = JRoute::_('index.php?option=com_ajax&plugin=' . $plugin . '&format=json&' . JSession::getFormToken() . '=1&component=' . $component . '&package=' . $package, true);
		
		$html[] = '<script id="' . $id . '" type="text/x-jquery-tmpl">';
		$html[] = '<div id="' . $id . '-modal" class="vpdk-modal">';
		$html[] = '<div class="vpdk-modal-dialog">';
		$html[] = '<div class="vpdk-modal-inner">';
		$html[] = '<form data-action="' . $url . '">';
		$html[] = '<div class="vpdk-modal-header">';
		$html[] = '<button type="button" class="vpdk-modal-close" title="Close">';
		$html[] = '<span aria-hidden="true">&times;</span>';
		$html[] = '</button>';
		$html[] = '<h4>Validate &amp Add Download Key</h4>';
		$html[] = '</div>';
		$html[] = '<div class="vpdk-modal-body">';
		$html[] = '<div class="vpdk-modal-message"></div>';
		$html[] = '<div class="vpdk-form-group">';
		$html[] = '<label for="' . $id . '-uname">VirtuePlanet Username</label>';
		$html[] = '<input type="text" id="' . $id . '-uname" name="uname" class="vpdk-form-control" placeholder="Username" autocomplete="off" spellcheck="false" required />';
		$html[] = '</div>';
		$html[] = '<div class="vpdk-form-group">';
		$html[] = '<label for="' . $id . '-dlk">Download Key</label>';
		$html[] = '<input type="text" id="' . $id . '-dlk" name="dlk" class="vpdk-form-control" placeholder="Download Key" autocomplete="off" spellcheck="false" required />';
		$html[] = '</div>';
		$html[] = '<div class="vpdk-modal-buttons">';
		$html[] = '<button type="button" id="' . $id . '-button" class="vpdk-btn vpdk-btn-lg vpdk-btn-primary"><i class="vpdk-button-loading"></i>Submit</button>';
		$html[] = '<button type="reset" id="' . $id . '-cancel" class="vpdk-btn vpdk-btn-lg vpdk-btn-default">Cancel</button>';
		$html[] = '</div>';
		$html[] = '</div>';
		$html[] = '<div class="vpdk-modal-footer">';
		$html[] = '<ul>';
		$html[] = '<li><a href="https://www.virtueplanet.com/lost-user-name/" target="_blank">Forgot Username?</a></li>';
		$html[] = '<li><a href="https://www.virtueplanet.com/download-key/" target="_blank">Forgot Download Key?</a></li>';
		$html[] = '</ul>';
		$html[] = '</div>';
		$html[] = '</form>';
		$html[] = '</div>';
		$html[] = '<div class="vpdk-modal-inner-bg"></div>';
		$html[] = '</div>';
		$html[] = '</div>';
		$html[] = '</script>';
		
		return implode(PHP_EOL, $html);
	}
	
	protected function isEnabled()
	{
		$plugin = !empty($this->element['plugin']) ? (string) $this->element['plugin'] : 'vpinstaller';
		$folder = null;
		
		if (strpos($plugin, ':') !== false)
		{
			$parts  = explode(':', $plugin);
			$folder = $parts[0];
			$plugin = $parts[1];
		}
		
		$db    = JFactory::getDbo();
		$query = $db->getQuery(true);
		
		$query->select(array($db->quoteName('extension_id'), $db->quoteName('name'), $db->quoteName('enabled')))
		      ->from($db->quoteName('#__extensions'))
		      ->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
		      ->where($db->quoteName('element') . ' = ' . $db->quote($plugin));
		
		if ($folder)
		{
			$query->where($db->quoteName('folder') . ' = ' . $db->quote($folder));
		}
		
		$db->setQuery($query);
		$plugin = $db->loadObject();
		
		$this->_plugin_name = !empty($plugin->name) ? $plugin->name : '';
		
		if (!empty($plugin->extension_id) && $plugin->enabled)
		{
			return true;
		}
		
		return false;
	}
}