<?php
/**
 *---------------------------------------------------------------------------------------
 * @package       VirtuePlanet Framework for Joomla!
 *---------------------------------------------------------------------------------------
 * @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('JPATH_BASE') or die;

jimport('joomla.form.formfield');
JFormHelper::loadFieldClass('text');

class JFormFieldVPIcons extends JFormFieldText
{
	public $type = 'VPIcons';
	
	protected static $vpIcons = null;
	protected static $faIcons = null;
	protected static $iconNames = array();
	protected static $initialised = false;
	
	protected function getInput()
	{
		if (!self::$initialised)
		{
			// Include jQuery
			JHtml::_('jquery.framework');
			JHtml::script('vpframework/vpframework.js', false, true);
			JHtml::script('vpframework/icons-admin.js', false, true);
			JHtml::stylesheet('vpframework/icons-admin.css', array(), true);
			
			// Build the script.
			$script = array();
			$script[] = '	function vpInsertFieldValue(value, id) {';
			$script[] = '		var $ = jQuery.noConflict();';
			$script[] = '		var old_value = $("#" + id).val();';
			$script[] = '		if (old_value != value) {';
			$script[] = '			var $elem = $("#" + id);';
			$script[] = '			$elem.val(value);';
			$script[] = '			$elem.trigger("change");';
			$script[] = '			if (typeof($elem.get(0).onchange) === "function") {';
			$script[] = '				$elem.get(0).onchange();';
			$script[] = '			}';
			$script[] = '			var prevDoc = $("iframe#" + id + "-selected-preview-frame").get()[0].contentWindow.document;';
			$script[] = '			if(prevDoc) {';
			$script[] = '				$(prevDoc).find(".vpicon-selected").removeClassPrefix("icon-").addClass(value);';
			$script[] = '			}';
			$script[] = '		}';
			$script[] = '		var $modal = $("#" + id + "-preview-modal");';
			$script[] = '		if($modal.hasClass("in")) {';
			$script[] = '			$modal.modal("hide");';
			$script[] = '		}';
			$script[] = '	}';
			
			JFactory::getDocument()->addScriptDeclaration(implode("\n", $script));
			self::$initialised = true;
		}
		
		$this->readonly = true;
		$this->class = 'vpicon-inputbox input-small ' . $this->class;  
		$html = array();
		$html[] = '<div class="input-prepend input-append">';
		$html[] = '<div class="vpicon-preview add-on">';
		$html[] = $this->getSelectedPreview();
		$html[] = '</div>';
		$html[] = $this->getPreview();
		$html[] = parent::getInput();
		
		// The button.
		if ($this->disabled != true)
		{
			JHtml::_('bootstrap.tooltip');

			$html[] = '<a class="btn" data-toggle="modal" title="' . JText::_('JLIB_FORM_BUTTON_SELECT') . '" href="#' . $this->id . '-preview-modal">'
				. JText::_('JLIB_FORM_BUTTON_SELECT') . '</a><a class="btn hasTooltip" title="'
				. JText::_('JLIB_FORM_BUTTON_CLEAR') . '" href="#" onclick="vpInsertFieldValue(\'\', \'' . $this->id . '\');return false;'
				. '"><i class="icon-remove"></i></a>';
		}
		$html[] = '</div>';

		return implode("\n", $html);
	}
	
	protected function getIcons()
	{
		$app = JFactory::getApplication();
		
		if(self::$vpIcons === null)
		{
			$icon_css_file = JPath::clean(JPATH_SITE . '/media/vpframework/css/icons.css');
			self::$vpIcons = array();
			$startFrom = 'icon-file-eye';
			$started = false;
			
			if(!file_exists($icon_css_file))
			{
				$app->enqueueMessage('Icon field could to find icon css file.');
				return parent::getOptions();
			}
			
			$string = @file_get_contents($icon_css_file);
			
			if(empty($string))
			{
				$app->enqueueMessage('Icon field could to parse icon css file.');
				return parent::getOptions();
			}
			
			$result = preg_match_all('/[a-zAZ0-9-]+/', $string, $matches);
			
			if(!empty($matches[0]))
			{
				foreach($matches[0] as $value)
				{
					if(strpos($value, 'icon-') === 0 && strlen($value) > 5)
					{
						if($value == $startFrom)
						{
							$started = true;
						}
						if($started)
						{
							self::$vpIcons[] = $value;
						}
					}
				}
				asort(self::$vpIcons);
			}
		}
		
		return self::$vpIcons;
	}
	
	protected function getFAIcons()
	{
		$app = JFactory::getApplication();
		
		if(self::$faIcons === null)
		{
			$icon_css_file = JPath::clean(JPATH_SITE . '/media/vpframework/css/font-awesome.css');
			self::$vpIcons = array();
			$startFrom = 'fa-glass';
			$started = false;
			
			if(!file_exists($icon_css_file))
			{
				$app->enqueueMessage('Icon field could to find Font Awesome icon css file.');
				return parent::getOptions();
			}
			
			$string = @file_get_contents($icon_css_file);
			
			if(empty($string))
			{
				$app->enqueueMessage('Icon field could to parse Font Awesome icon css file.');
				return parent::getOptions();
			}
			
			$result = preg_match_all('/[a-zAZ0-9-]+/', $string, $matches);
			
			if(!empty($matches[0]))
			{
				foreach($matches[0] as $value)
				{
					if(strpos($value, 'fa-') === 0 && strlen($value) > 3)
					{
						if($value == $startFrom)
						{
							$started = true;
						}
						if($started)
						{
							self::$faIcons[] = 'fa ' . $value;
						}
					}
				}//vpdump(self::$faIcons);exit;
				//asort(self::$faIcons);
			}
		}
		
		return self::$faIcons;
	}
	
	protected function getPreview()
	{
		list($selection, $active) = $this->getTemplateSelection();
		
		$doc = JFactory::getDocument();
		$icons = array();
		$fa_icons = array();
		
		if(!empty($selection))
		{
			$icons = $this->getIcons();
			$icons = !empty($icons) ? $icons : array();
			$fa_icons = $this->getFAIcons();
			$fa_icons = !empty($fa_icons) ? $fa_icons : array();
		}
		elseif($active == 'fa')
		{
			$fa_icons = $this->getFAIcons();
			$fa_icons = !empty($fa_icons) ? $fa_icons : array();
		}
		else
		{
			$icons = $this->getIcons();
			$icons = !empty($icons) ? $icons : array();
		}
		
		if(empty($icons) && empty($fa_icons))
		{
			return null;
		}
		
		$selectBox = $selection ? '<div class="select-vpicon-set pure-form ">
		<label for="vpicon_template">Select Template: &nbsp;</label>' . $selection . '</div>' : '';
		
		$bodyClass = !empty($selectBox) ? ' has-selection' : '';
		
		$html = '
		<!DOCTYPE html>
		<html>
			<head>
				<meta http-equiv="content-type" content="text/html; charset=utf-8" />
				<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
				<title>VP Icons Preview</title>
				<link rel="stylesheet" href="' . JUri::root() . 'media/vpframework/css/pure.min.css"/>
				<link rel="stylesheet" href="' . JUri::root() . 'media/vpframework/css/icons.css"/>
				<link rel="stylesheet" href="' . JUri::root() . 'media/vpframework/css/font-awesome.css"/>
				<link rel="stylesheet" href="' . JUri::root() . 'media/vpframework/css/icons-admin.css"/>
			</head>
			<body class="iframe-body' . $bodyClass . '">
				<div class="content-wrapper">
					<div class="content">' . $selectBox . '
						<ul id="default-icon-set" class="list-vpicons"' . ($active == 'icon' ? '' : ' style="display:none;"') . '>';
							foreach($icons as $icon)
							{
								$html .= '<li>';
								$html .= '	<a href="#" onclick="return parent.vpInsertFieldValue(\'' . $icon . '\', \'' . $this->id . '\');"><i class="' . $icon . '"></i><span class="icon-name">' . $icon . '</span></a>';
								$html .= '</li>';
							}
	$html .= '
						</ul>
						<ul id="fa-icon-set" class="list-vpicons"' . ($active == 'fa' ? '' : ' style="display:none;"') . '>';
							foreach($fa_icons as $icon)
							{
								$html .= '<li>';
								$html .= '	<a href="#" onclick="return parent.vpInsertFieldValue(\'' . $icon . '\', \'' . $this->id . '\');"><i class="' . $icon . '"></i><span class="icon-name">' . $icon . '</span></a>';
								$html .= '</li>';
							}
	$html .= '
						</ul>
					</div>
				</div>
			</body>
		</html>
		';
		
		$html  = '<script id="' . $this->id . '-hidden-preview" type="text/x-tmpl">' . $html . '</script>';
		$html .= '
		<div id="' . $this->id . '-preview-modal" class="modal hide fade" tabindex="-1" role="dialog" aria-hidden="true">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
				<h3>Click on a icon to select</h3>
			</div>
			<div class="modal-body" style="max-height: 100%;">
				<iframe src="about:blank" id="' . $this->id . '-preview-frame" class="vpicons-preview-frame" border="0" width="100%"></iframe>
			</div>
		</div>';
		
		$doc->addScriptDeclaration("
		jQuery(document).ready(function($) {
			var html = $('#" . $this->id . "-hidden-preview').html();
			$('iframe#" . $this->id . "-preview-frame').get()[0].contentWindow.document.write(html);
			$('iframe#" . $this->id . "-preview-frame').get()[0].contentDocument.close();
		});
		");
		
		return $html;
	}
	
	protected function getSelectedPreview()
	{
		$html = '
		<!DOCTYPE html>
		<html>
			<head>
				<meta http-equiv="content-type" content="text/html; charset=utf-8" />
				<link rel="stylesheet" href="' . JUri::root() . 'media/vpframework/css/icons.css"/>
				<link rel="stylesheet" href="' . JUri::root() . 'media/vpframework/css/font-awesome.css"/>
				<link rel="stylesheet" href="' . JUri::root() . 'media/vpframework/css/icons-admin.css"/>
			</head>
			<body class="iframe-body">
				<i class="vpicon-selected ' . $this->value . '"></i>
			</body>
		</html>
		';
		
		$html  = '<script id="' . $this->id . '-selected-hidden-preview" type="text/x-tmpl">' . $html . '</script>';
		$html .= '<iframe src="about:blank" id="' . $this->id . '-selected-preview-frame" class="vpicons-selected-preview-frame" border="0"></iframe>';
		
		JFactory::getDocument()->addScriptDeclaration("
		jQuery(document).ready(function($) {
			var html = $('#" . $this->id . "-selected-hidden-preview').html();
			$('iframe#" . $this->id . "-selected-preview-frame').get()[0].contentWindow.document.write(html);
			$('iframe#" . $this->id . "-selected-preview-frame').get()[0].contentDocument.close();
		});
		");
		
		return $html;
	}
	
	protected function getTemplateSelection()
	{
		$helper    = plgSystemVPFrameworkHelper::getInstance();
		$templates = $helper->getTemplates();
		$select    = null;
		$selected  = null;
		$homeIcon  = null;
		$options   = array();
		$home      = array();
		
		if(!empty($templates))
		{
			foreach($templates as $template)
			{
				$vpicon = $template->params->get('vpficon', 'icon');
				$vpicon = ($vpicon == 'font-awesome') ? 'fa' : $vpicon;
				$name   = $template->template;
				$name   = str_replace('vp_', 'VP ', $name);
				$name   = ucwords($name);
				$selected = $vpicon;
				
				if(!empty($template->home))
				{
					$home[] = JHtml::_('select.option', $vpicon, ucwords($name));
					$homeIcon = $vpicon;
				}
				else
				{
					$options[] = JHtml::_('select.option', $vpicon, ucwords($name));
				}
			}
			
			$options = array_merge($home, $options);
			
			if($homeIcon)
			{
				$selected = $homeIcon;
			}
			
			if(count($options) > 1)
			{
				$select = JHtml::_('select.genericlist', $options, 'vpicon_template', 'onchange="return parent.changeVPIconSet(document, this);"', 'value', 'text', '');
			}
		}
		
		return array($select, $selected);
	}
}