<?php
/**
 * @package DJ-Catalog2
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

use Joomla\CMS\Factory;
use Joomla\CMS\Form\FormField;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\LanguageHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Session\Session;
use Joomla\Database\ParameterType;

defined('JPATH_BASE') or die;

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


class JFormFieldDJFieldModal extends JFormField {
	
	protected $type = 'DJFieldModal';
	
	protected function getInput()
	{
		$allowClear     = ((string) $this->element['clear'] != 'false');
		$allowSelect    = ((string) $this->element['select'] != 'false');
		$allowPropagate = ((string) $this->element['propagate'] == 'true');
		
		$languages = LanguageHelper::getContentLanguages(array(0, 1), false);
		
		// The active article id field.
		$value = (int) $this->value > 0 ? (int) $this->value : '';
		
		// Create the modal id.
		$modalId = 'FieldModal_' . $this->id;
		
		/** @var \Joomla\CMS\WebAsset\WebAssetManager $wa */
		$wa = Factory::getApplication()->getDocument()->getWebAssetManager();
		
		// Add the modal field script to the document head.
		$wa->useScript('field.modal-fields');
		
		// Script to proxy the select modal function to the modal-fields.js file.
		if ($allowSelect)
		{
			static $scriptSelect = null;
			
			if (is_null($scriptSelect))
			{
				$scriptSelect = array();
			}
			
			if (!isset($scriptSelect[$this->id]))
			{
				JFactory::getDocument()->addScriptDeclaration("
				function jSelectDJCatalog2Field_" . $this->id . "(id, title) {
					window.processModalSelect('FieldModal', '" . $this->id . "', id, title);
				}
				");
				
				JText::script('JGLOBAL_ASSOCIATIONS_PROPAGATE_FAILED');
				
				$scriptSelect[$this->id] = true;
			}
		}
		
		// Setup variables for display.
		$linkArticles = 'index.php?option=com_djcatalog2&amp;view=fields&amp;layout=modal&amp;tmpl=component&amp;' . JSession::getFormToken() . '=1';
		$linkArticle  = 'index.php?option=com_djcatalog2&amp;view=fields&amp;layout=modal&amp;tmpl=component&amp;' . JSession::getFormToken() . '=1';
		
		if (isset($this->element['language']))
		{
			$linkArticles .= '&amp;forcedLanguage=' . $this->element['language'];
			$linkArticle  .= '&amp;forcedLanguage=' . $this->element['language'];
			$modalTitle    = JText::_('COM_DJCATALOG2_CHANGE_FIELD') . ' &#8212; ' . $this->element['label'];
		}
		else
		{
			$modalTitle    = JText::_('COM_DJCATALOG2_CHANGE_FIELD');
		}
		
		$urlSelect = $linkArticles . '&amp;function=jSelectDJCatalog2Field_' . $this->id;
		
		if ((int) $this->value > 0)
		{
			$db	= JFactory::getDbo();
			$query = $db->getQuery(true)
			->select($db->quoteName('name'))
			->from($db->quoteName('#__djc2_items_extra_fields'))
			->where($db->quoteName('id') . ' = ' . (int) $this->value);
			$db->setQuery($query);
			
			try
			{
				$title = $db->loadResult();
			}
			catch (RuntimeException $e)
			{
				JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');
			}
		}
		
		$title = empty($title) ? JText::_('COM_DJCATALOG2_SELECT_FIELD') : htmlspecialchars($title, ENT_QUOTES, 'UTF-8');
		
		
		// The current article display field.
		$html  = '';
		
		if ($allowSelect || $allowClear)
		{
			$html .= '<span class="input-group">';
		}
		
		$html .= '<input class="form-control" id="' . $this->id . '_name" type="text" value="' . $title . '" readonly size="35">';
		
		// Select article button
		if ($allowSelect)
		{
			$html .= '<button'
				. ' class="btn btn-primary ' . ($value ? ' hidden' : '') . '"'
					. ' id="' . $this->id . '_select"'
						. ' data-bs-toggle="modal"'
							. ' type="button"'
								. ' data-bs-target="#ModalSelect' . $modalId . '">'
									. '<span class="icon-file" aria-hidden="true"></span> ' . Text::_('JSELECT')
									. '</button>';
		}
		
		// Clear article button
		if ($allowClear)
		{
			$html .= '<button'
				. ' class="btn btn-primary btn-secondary' . ($value ? '' : ' hidden') . '"'
					. ' id="' . $this->id . '_clear"'
						. ' type="button"'
							. ' onclick="window.processModalParent(\'' . $this->id . '\'); return false;">'
								. '<span class="icon-times" aria-hidden="true"></span> ' . Text::_('JCLEAR')
								. '</button>';
		}
		
		// Propagate article button
		if ($allowPropagate && count($languages) > 2)
		{
			// Strip off language tag at the end
			$tagLength = (int) strlen($this->element['language']);
			$callbackFunctionStem = substr("jSelectArticle_" . $this->id, 0, -$tagLength);
			
			$html .= '<button'
				. ' class="btn btn-primary ' . ($value ? '' : ' hidden') . '"'
					. ' type="button"'
						. ' id="' . $this->id . '_propagate"'
							. ' title="' . Text::_('JGLOBAL_ASSOCIATIONS_PROPAGATE_TIP') . '"'
								. ' onclick="Joomla.propagateAssociation(\'' . $this->id . '\', \'' . $callbackFunctionStem . '\');">'
									. '<span class="icon-sync" aria-hidden="true"></span> ' . Text::_('JGLOBAL_ASSOCIATIONS_PROPAGATE_BUTTON')
									. '</button>';
		}
		
		
		if ($allowSelect || $allowClear)
		{
			$html .= '</span>';
		}
		
		// Select article modal
		if ($allowSelect)
		{
			$html .= Joomla\CMS\HTML\HTMLHelper::_(
				'bootstrap.renderModal',
				'ModalSelect' . $modalId,
				array(
					'title'       => $modalTitle,
					'url'         => $urlSelect,
					'height'      => '400px',
					'width'       => '800px',
					'bodyHeight'  => '70',
					'modalWidth'  => '80',
					'footer'      => '<button type="button" class="btn btn-primary" data-dismiss="modal">' . JText::_('JLIB_HTML_BEHAVIOR_CLOSE') . '</button>',
				)
				);
		}
		
		// Note: class='required' for client side validation.
		$class = $this->required ? ' class="required modal-value"' : '';
		
		$html .= '<input type="hidden" id="' . $this->id . '_id" ' . $class . ' data-required="' . (int) $this->required . '" name="' . $this->name
		. '" data-text="' . htmlspecialchars(JText::_('COM_DJCATALOG2_SELECT_FIELD'), ENT_COMPAT, 'UTF-8') . '" value="' . $value . '" />';
		
		return $html;
	}
	
	/**
	 * Method to get the field label markup.
	 *
	 * @return  string  The field label markup.
	 *
	 * @since   3.4
	 */
	protected function getLabel()
	{
		return str_replace($this->id, $this->id . '_name', parent::getLabel());
	}
}
?>
