<?php


/** 
 *------------------------------------------------------------------------------
 * @package       T4 Page Builder for Joomla!
 *------------------------------------------------------------------------------
 * @copyright     Copyright (C) 2004-2020 JoomlArt.com. All Rights Reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @authors       JoomlArt
 * @forum:		  https://www.joomlart.com/forums/t/t4-builder
 * @Link:         https://demo.t4-builder.joomlart.com/
 *------------------------------------------------------------------------------
 */

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Form\FormHelper;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Form\Field\ListField;
use Joomla\CMS\Access\Exception\NotAllowed;

FormHelper::loadFieldClass('list');

if (!class_exists('ListFieldLegacy')) {
	if (version_compare(JVERSION, 4, 'ge')) {
		class ListFieldLegacy extends ListField
		{
		}
	} else {
		class ListFieldLegacy extends JFormFieldList
		{
		}
	}
}

class JFormFieldPagesmodal extends ListFieldLegacy
{
	protected $type = 'pagesmodal' ;
	
	protected function getInput()
	{
		$allowNew       = ((string) $this->element['new'] == 'true');
		$allowEdit      = ((string) $this->element['edit'] == 'true');
		$allowClear     = ((string) $this->element['clear'] != 'false');
		$allowSelect    = ((string) $this->element['select'] != 'false');
		$attrDismis = version_compare(JVERSION, '4', 'ge') ? " data-bs-dismiss='modal' " : ' data-dismiss="modal" ';
		// Load language
		Factory::getLanguage()->load('com_t4pagebuilder', JPATH_ADMINISTRATOR);

		// The active article id field.
		$value = (int) $this->value > 0 ? (int) $this->value : '';
		if(version_compare(JVERSION, '4', 'ge')){
			/** @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');
		}else{
			// Add the modal field script to the document head.
			HTMLHelper::_('jquery.framework');
			HTMLHelper::_('script', 'system/modal-fields.js', array('version' => 'auto', 'relative' => true));
		}
		// 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]))
			{
				Factory::getDocument()->addScriptDeclaration("
				function jSelectArticle_" . $this->id . "(id, title, catid, object, url, language) {
					window.processModalSelect('Article', '" . $this->id . "', id, title, catid, object, url, language);
				}
				");

				Text::script('JGLOBAL_ASSOCIATIONS_PROPAGATE_FAILED');

				$scriptSelect[$this->id] = true;
			}
		}

		// Build the script.
		$script = array();

		// Select button script
		$script[] = '	function JASelectArticle_' . $this->id . '(id, title, catid, object) { console.log(id);';
		$script[] = '		document.getElementById("' . $this->id . '_id").value = id;';
		$script[] = '		document.getElementById("' . $this->id . '_name").value = title;';

		if ($allowEdit)
		{
			$script[] = '		if (id == "' . $value . '") {';
			$script[] = '			jQuery("#' . $this->id . '_edit").removeClass("hidden");';
			$script[] = '		} else {';
			$script[] = '			jQuery("#' . $this->id . '_edit").addClass("hidden");';
			$script[] = '		}';
		}

		if ($allowClear)
		{
			$script[] = '		jQuery("#' . $this->id . '_clear").removeClass("hidden");';
		}

		$script[] = '		jQuery("#articleSelect' . $this->id . 'Modal").modal("hide");';

		if ($this->required)
		{
			$script[] = '		document.formvalidator.validate(document.getElementById("' . $this->id . '_id"));';
			$script[] = '		document.formvalidator.validate(document.getElementById("' . $this->id . '_name"));';
		}

		$script[] = '	}';

		// Edit button script
		$script[] = '	function JAEditArticle_' . $value . '(title) {';
		$script[] = '		document.getElementById("' . $this->id . '_name").value = title;';
		$script[] = '	}';


		// Add the script to the document head.
		Factory::getDocument()->addScriptDeclaration(implode("\n", $script));

		// Setup variables for display.
		$html = array();

		$linkArticles = 'index.php?option=com_t4pagebuilder&amp;view=pages&amp;layout=modal&amp;tmpl=component'
			. '&amp;function=jSelectArticle_' . $this->id;
		$input = Factory::getApplication()->input;
		$Itemid = $input->get('id');
		$linkArticle  = 'index.php?option=com_t4pagebuilder&amp;view=page&amp;';

		if (isset($this->element['language']))
		{
			$linkArticles .= '&amp;forcedLanguage=' . $this->element['language'];
			$linkArticle  .= '&amp;forcedLanguage=' . $this->element['language'];
		}

		$urlSelect = $linkArticles . '&amp;' . Session::getFormToken() . '=1';
		$urlEdit   = $linkArticle . 'task=page.edit&amp;id=' . $value ;

		if ($value)
		{
			$db    = Factory::getDbo();
			$query = $db->getQuery(true)
				->select($db->quoteName('title'))
				->from($db->quoteName('#__jae_item'))
				->where($db->quoteName('id') . ' = ' . (int) $value);
			$db->setQuery($query);

			try
			{
				$title = $db->loadResult();
			}
			catch (RuntimeException $e)
			{
				throw new NotAllowed($e->getMessage(), 500);
			}
		}

		if (empty($title))
		{
			$title = Text::_('COM_T4PAGEBUIDLER_SELECT_A_PAGE');
		}

		$title = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');
		$spanAttr = version_compare(JVERSION, '4',"ge") ? 'input-group' : 'input-append';
		$inputAttr = version_compare(JVERSION, '4',"ge") ? 'form-control' : 'input-medium';
		// The current article display field.
		$html[] = '<span class="'.$spanAttr.'">';
		$html[] = '<input class="'.$inputAttr.'" id="' . $this->id . '_name" type="text" value="' . $title . '" disabled="disabled" size="35" />';
		$attrModal = version_compare(JVERSION, '4', 'ge') ? ' data-bs-toggle="modal"' : ' data-toggle="modal"';
		// if($allowSelect){
		// 	$btnSelectCls = version_compare(JVERSION, '4', 'ge') ? "btn btn-primary " . ($value ? 'hidden' : '') : 'btn hasTooltip' . ($value ? 'hidden' : '');
		// 	// Select article button
		// 	$html[] = '<a'
		// 		. ' class="'.$btnSelectCls.'"'
		// 		. $attrModal 
		// 		. ' role="button"'
		// 		. ' href="#articleSelect' . $this->id . 'Modal"'
		// 		. ' title="' . HTMLHelper::tooltipText(Text::_('COM_T4PAGEBUILDER_CHANGE_PAGE')) . '">'
		// 		. '<span class="icon-file"></span> ' . Text::_('JSELECT')
		// 		. '</a>';
		// }
		// Select article button
		if ($allowSelect)
		{
			$btnSelectCls = version_compare(JVERSION, '4', 'ge') ? "btn btn-primary " . ($value ? 'hidden' : '') : 'btn hasTooltip' . ($value ? 'hidden' : '');
			$select_modal_target = version_compare(JVERSION, '4', 'ge') ? ' data-bs-target="#articleSelect' . $this->id . 'Modal"' : ' data-target="#articleSelect' . $this->id . 'Modal"';
			$html[] .= '<button'
				. ' type="button"'
				. ' class="' . $btnSelectCls . '"'
				. ' id="' . $this->id . '_select"'
				. $attrModal
				. $select_modal_target
				. ' title="' . HTMLHelper::tooltipText('COM_T4PAGEBUILDER_CHANGE_PAGE') . '">'
				. '<span class="icon-file" aria-hidden="true"></span> ' . Text::_('JSELECT')
				. '</button>';
		}
		// Edit article button
		if ($allowEdit)
		{
			$text_edit =  version_compare(JVERSION, '4', 'ge') ? Text::_('COM_T4PAGEBUILDER_EDIT_ITEM') : '<span class="icon-edit"></span> ' . Text::_('COM_T4PAGEBUILDER_EDIT_ITEM');
			$btnEditCls = version_compare(JVERSION, '4', 'ge') ? "btn btn-primary " . ($value ? '' : 'hidden') : 'btn hasTooltip' . ($value ? '' : 'hidden');
			$html[] = '<a'
				. ' class="' . $btnEditCls . '"'
				. ' id="' . $this->id . '_edit"'
				. ' href="' . $urlEdit . '"'
				. ' target="_Blank"'
				. ' title="' . HTMLHelper::tooltipText(Text::_('COM_T4PAGEBUILDER_EDIT_ITEM')) . '">'
				. $text_edit
				. '</a>';
		}

		// Clear article button
		if ($allowClear)
		{
			$btnClearCls = version_compare(JVERSION, '4', 'ge') ? "btn btn-secondary " . ($value ? '' : ' hidden') : 'btn hasTooltip' . ($value ? '' : ' hidden');
			$html[] .= '<button'
				. ' class="' . $btnClearCls . '"'
				. ' id="' . $this->id . '_clear"'
				. ' type="button"'
				. ' onclick="window.processModalParent(\'' . $this->id . '\'); return false;">'
				. '<span class="icon-times" aria-hidden="true"></span> ' . Text::_('JCLEAR')
				. '</button>';
		}

		$html[] = '</span>';

		// Select article modal
		$html[] = HTMLHelper::_(
			'bootstrap.renderModal',
			'articleSelect' . $this->id . 'Modal',
			array(
				'title'       => Text::_('COM_T4PAGEBUILDER_CHANGE_PAGE'),
				'url'         => $urlSelect,
				'height'      => '400px',
				'width'       => '800px',
				'bodyHeight'  => '70',
				'modalWidth'  => '80',
				'footer'      => '<button type="button" class="btn" '
						. $attrDismis
						.' aria-hidden="true">'
						. Text::_("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 . ' name="' . $this->name . '" value="' . $value . '" />';

		return implode("\n", $html);
	}
	
	protected function getLabel()
	{
		return str_replace($this->id, $this->id . '_id', parent::getLabel());
	}
	
}