<?php
/**
 *---------------------------------------------------------------------------------------
 * @package      VP Conversion Tracking - Joomla! System Plugin
 * @subpackage   For VirtueMart 3+
 *---------------------------------------------------------------------------------------
 * @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('_JEXEC') or die();

class JFormFieldVPDynamic extends JFormField
{
	protected $type = 'vpdynamic';
	
	protected $fieldXml = null;
	
	protected $context = 'plg_system_vpconversiontracking';
	
	protected static $loaded = array();
	
	protected function getInput()
	{
		$sets           = (int) !empty($this->element['defaultsets']) ? $this->element['defaultsets'] : 1;
		$this->context  = !empty($this->element['context']) ? $this->element['context'] : $this->context . '_' . $this->name;
		$this->value    = !empty($this->value) ? (array) $this->value : array();
		$this->cont_id  = $this->id . '-vpdynamic-container';

		self::_prepareJS($this->id, $this->name, $this->fieldname, $sets, $this->cont_id);
		
		$html  = '<span id="' . $this->id . '"></span>';
		
		if(version_compare(JVERSION, '3.0.0', 'ge'))
		{
			$html .= '</div></div>';
		}
		else
		{
			$html .= '</li></ul>';
		}
		
		$html .= '<ul id="' . $this->cont_id . '" class="vpdynamic-cont adminformlist">';
	
		$html .= '<div class="vpdynamic-toolbar">';
		
		if(!empty($this->element['description']))
		{
			$html .= '<div class="vpdynamic-desc">' . JText::_($this->element['description']) . '</div>';
		}
		
		$html .= '<button type="button" class="btn btn-small btn-success vpdynamic-addnew-button">' . JText::_('PLG_SYSTEM_VPCONVERSIONTRACKING_ADD_NEW') . '</button>';
		$html .= '</div>';
		$html .= $this->getFieldSets();
		$html .= '</ul>';
		
		if(version_compare(JVERSION, '3.0.0', 'ge'))
		{
			$html .= '<div><div>';
		}
		else
		{
			$html .= '<ul class="adminformlist"><li>';
		}
		
		return $html;
	}
	
	protected function getFieldSets()
	{
		$forms = $this->getDynamicForms();
		
		if(empty($forms) || !is_array($forms))
		{
			return '';
		}
		
		$html     = array();
		$set_name = !empty($this->element['setlabel']) ? JText::_($this->element['setlabel']) . ': ' : 'Rule: ';

		foreach($forms as $form)
		{
			foreach ($form->getFieldsets() as $group => $fieldset)
			{
				$fields = $form->getFieldset($group);
				
				if (count($fields))
				{
					$html[] = '<li>';
					$html[] = '<fieldset class="vpdynamic-fields-set" data-ordering="' . $fieldset->label . '">';
					
					$html[] = '<legend>' . $set_name . '<span class="vpdynamic-set-index">' . ($fieldset->label + 1) . '</span></legend>';
					
					$html[] = '<div class="vpdynamic-fields-button-cont">';
					$html[] = '<button type="button" class="btn btn-small vpdynamic-remove-button" title="Remove"><i class="icon-trash"></i> ' . JText::_('PLG_SYSTEM_VPCONVERSIONTRACKING_REMOVE') . '</button>';
					$html[] = '</div>';
					
					foreach ($fields as $field)
					{
						if ($field->hidden)
						{
							$html[] = $field->getInput();
						}
						else
						{
							$html[] = '<div class="control-group">';
							$html[] = '<div class="control-label">';
							$html[] = $field->getLabel();
							$html[] = '</div>';
							$html[] = '<div class="controls">';
							$html[] = $field->getInput();
							$html[] = '</div>';
							$html[] = '</div>';
						}
					}
					
					$html[] = '</fieldset>';
					$html[] = '</li>';
				}
			}
		}
		
		return implode($html);
	}
	
	protected function getDynamicForms()
	{
		$app = JFactory::getApplication();
		
		if($this->fieldXml === null)
		{
			$xml       = JPath::clean(dirname(__FILE__) . '/vpdynamic/fields.xml');
			$customXml = !empty($this->element['form']) ? JPath::clean(JPATH_ROOT . '/' . $this->element['form']) : null;

			if(!empty($customXml) && is_file($customXml))
			{
				$xml = $customXml;
			}
			
			$this->fieldXml = file_get_contents($xml);
		}
		
		$forms    = array();
		$count    = (int) !empty($this->element['defaultsets']) ? $this->element['defaultsets'] : 1;
		$value    = (array) $this->value;
		$count    = !empty($value) ? count($value) : $count;
		
		for($i = 0; $i < $count; $i++)
		{
			$xml  = '<?xml version="1.0" encoding="utf-8"?>';
			$xml .= '<form>';
			$xml .= '<fieldset name="set_' . $i . '" label="' .$i . '">';
			$xml .= $this->fieldXml;
			$xml .= '</fieldset>';
			$xml .= '</form>';
			
			$form = JForm::getInstance($this->context . '.fields.' . $i, $xml, array('control' => $this->name . '[' . $i . ']'));
			
			if(isset($value[$i]))
			{
				$form->bind($value[$i]);
			}
			
			$forms[] = $form;
		}
		
		return $forms;
	}
	
	protected static function _prepareJS($id, $name, $fieldname, $sets, $cont_id)
	{
		// Only load once
		if (isset(static::$loaded[$id]))
		{
			return;
		}
		
		$joomla3 = version_compare(JVERSION, '3.0.0', 'ge') ? '1' : '0';
		
		JHtml::_('behavior.framework', true);
		
		$js = "
		jQuery(document).ready(function($) {
			var joomla3 = " . $joomla3 . ",
				container = $('#" . $cont_id . "');
			if(joomla3) {
				$('span#" . $id . "').closest('.control-group').hide();
			} else {
				$('span#" . $id . "').closest('li').hide();
			}
			container.on('sortupdate', function(event, ui) {
				var fieldset, oldOrdering;
				$(this).children('li').each(function(index, element) {
					fieldset = $('fieldset.vpdynamic-fields-set', this);
					oldOrdering = fieldset.data('ordering');
					fieldset.data('ordering', index).attr('data-ordering', index);
					$(this).find('label, input, select, textarea, a, div.chzn-container').each(function() {
						if($(this).attr('name')) {
							$(this).attr('name', $(this).attr('name').replace('" . $name . "[' + oldOrdering + ']', '" . $name . "[' + index  + ']'));
						}
						if($(this).attr('id')) {
							$(this).attr('id', $(this).attr('id').replace('" . $fieldname . "__' + oldOrdering, '" . $fieldname . "__' + index));
						}
						if($(this).attr('href')) {
							$(this).attr('href', $(this).attr('href').replace('" . $fieldname . "__' + oldOrdering, '" . $fieldname . "__' + index));
						}
						if($(this).attr('onclick')) {
							$(this).attr('onclick', $(this).attr('onclick').replace('" . $fieldname . "__' + oldOrdering, '" . $fieldname . "__' + index));
						}
						if($(this).attr('for')) {
							$(this).attr('for', $(this).attr('for').replace('" . $fieldname . "__' + oldOrdering, '" . $fieldname . "__' + index));
						}
					});
					$('.vpdynamic-set-index', this).fadeOut(function() {
						$(this).text(index + 1).fadeIn();
					});
				});
				if($(this).children('li').length <= " . $sets . ") {
					$('.vpdynamic-remove-button', this).attr('disabled', true);
				} else {
					$('.vpdynamic-remove-button', this).removeAttr('disabled');
				}
			});
			container.trigger('sortupdate');
			$('.vpdynamic-addnew-button', container).click(function(){
				var group = $(this).closest('.vpdynamic-cont');
				if(joomla3) {
					$('select', group).each(function(){
						$(this).chosen('destroy');
					})
					$('.hasTooltip', group).each(function(){
						$(this).tooltip('destroy');
					});
					$('.hasPopover', group).each(function(){
						$(this).popover('destroy');
					});
				}
				var newSet = $('li:last-child', group).clone(true);
				$('select', newSet).prop('selectedIndex', '');
				$('select[multiple]', newSet).val('');
				$('input:text,textarea', newSet).val('');
				group.append(newSet);
				group = $(this).closest('.vpdynamic-cont');
				group.trigger('sortupdate');
				if(joomla3) {
					$('select', group).each(function(){
						$(this).chosen({'disable_search_threshold':10,'allow_single_deselect':true,'placeholder_text_multiple':'Select some options','placeholder_text_single':'Select an option','no_results_text':'No results match'});
					});
					$('.hasTooltip', group).each(function(){
						$(this).tooltip({'html': true,'container': 'body'});
					});
					$('.hasPopover', group).each(function(){
						$(this).popover({'html': true,'trigger': 'hover focus','container': 'body'});
					});
				}
				$('html,body').animate({
					scrollTop: $('li:last-child', group).offset().top - 200
				}, 500);
			});
			$('.vpdynamic-remove-button', container).click(function(){
				var group = $(this).closest('.vpdynamic-cont');
				$(this).closest('li').animate({'opacity' : 0}, 500, function(){
					$(this).remove();
					group.trigger('sortupdate');
				});
			})
		});
		";
		
		$css = "ul.vpdynamic-cont{list-style:none;padding:0;margin:0}.vpdynamic-fields-set{position:relative}.vpdynamic-fields-button-cont{position:absolute;top:0;right:0}.vpdynamic-fields-button-cont .btn{margin-left:10px}.vpdynamic-toolbar{margin-bottom:20px}.vpdynamic-toolbar .btn{padding-left:35px;padding-right:35px}.vpdynamic-move-button{padding:3px 4px 1px;cursor:move}.vpdynamic-fields-set{background-color:#FFF;opacity:1}.ui-sortable-helper .vpdynamic-fields-set{opacity:0.8}.vpdynamic-toolbar{text-align:right}.vpdynamic-desc{float:left;margin-bottom:10px;text-align:left; width: -webkit-calc(100% - 200px); width: -moz-calc(100% - 200px); width: calc(100% - 200px);}";

		$doc = JFactory::getDocument();
		
		$doc->addScriptDeclaration($js);
		$doc->addStyleDeclaration($css);
	}
}