<?php
/**
 * --------------------------------------------------------------------------------------------
 * VP Responsive Slider - Joomla! 3 Module for VirtueMart 3.0
 * --------------------------------------------------------------------------------------------
 * @package    VP Responsive Slider Module
 * @author     Abhishek Das
 * @copyright  Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license    GNU General Public License version 2. http://www.gnu.org/licenses/gpl-2.0.html
 * @link       http://www.virtueplanet.com
 * --------------------------------------------------------------------------------------------
*/
// No direct access
defined('_JEXEC') or die();

JFormHelper::loadFieldClass('Media');

class JFormFieldVPFDynamic extends JFormFieldMedia
{
	protected $type = 'VPFDynamic';
	protected $raw_fields = null;
	protected $original_id = null;
	protected $original_value = null;
	protected $original_name = null;
	
	protected static $animations = null;
	
	protected static $loaded = array();
	
	protected function getInput()
	{
		$this->original_id = $this->id;
		$this->original_value = (array) $this->value;
		$this->original_name = $this->name;
		$default_sets = (int) !empty($this->element['defaultsets']) ? $this->element['defaultsets'] : 2;
		self::_prepareJS($this->original_id, $this->original_name, $default_sets);
		
		$html  = '<span id="' . $this->original_id . '"></span>';
		$html .= '</div></div>';
		
		$html .= '<ul class="vpfdynamic-cont">';
		$html .= '<div class="vpfdynamic-toolbar"><button type="button" class="btn btn-small btn-success vpfdynamic-addnew-button">Add New</button></div>';
		$html .= $this->getFieldSets($this->original_value);
		$html .= '</ul>';
		
		$html .= '<div><div>';
		
		return $html;
	}
	
	protected static function _prepareJS($original_id, $original_name, $default_sets)
	{
		// Only load once
		if (isset(static::$loaded[__METHOD__]))
		{
			return;
		}
		
		JHtml::_('behavior.framework', true);
		JHtml::_('jquery.ui', array('core', 'sortable'));
		JHtml::_('script', 'jui/sortablelist.js', false, true);
		JHtml::_('stylesheet', 'jui/sortablelist.css', false, true, false);
		
		$newMedia  = version_compare(JVERSION, '3.7.0', 'ge') ? 'true' : 'false';
		
		$doc = JFactory::getDocument();
		
		$js = "
		jQuery(document).ready(function($) {
			var newMedia = " . $newMedia . ";
			$('span#" . $original_id . "').parents('.control-group').hide();
			$('.vpfdynamic-cont').sortable({
				axis: 'y'
			});
			$('.vpfdynamic-cont').on('sortupdate', function(event, ui) {
				var fieldset, oldOrdering;
				$(this).children('li').each(function(index, element) {
					fieldset = $('fieldset.vpfdynamic-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, div.modal').each(function() {
						if($(this).attr('name')) {
							$(this).attr('name', $(this).attr('name').replace('" . $original_name . "[' + oldOrdering + ']', '" . $original_name . "[' + index  + ']'));
						}
						if($(this).attr('id')) {
							$(this).attr('id', $(this).attr('id').replace('" . $original_id . "_' + oldOrdering, '" . $original_id . "_' + index));
						}
						if($(this).attr('href')) {
							$(this).attr('href', $(this).attr('href').replace('" . $original_id . "_' + oldOrdering, '" . $original_id . "_' + index));
						}
						if($(this).attr('onclick')) {
							$(this).attr('onclick', $(this).attr('onclick').replace('" . $original_id . "_' + oldOrdering, '" . $original_id . "_' + index));
						}
						if($(this).attr('for')) {
							$(this).attr('for', $(this).attr('for').replace('" . $original_id . "_' + oldOrdering, '" . $original_id . "_' + index));
						}
					});
					$('.vpfdynamic-set-index', this).fadeOut(function() {
						$(this).text(index + 1).fadeIn();
					});
				});
				if($(this).children('li').length <= " . $default_sets . ") {
					$('.vpfdynamic-remove-button', this).attr('disabled', true);
				} else {
					$('.vpfdynamic-remove-button', this).removeAttr('disabled');
				}
			});
			$('.vpfdynamic-cont').trigger('sortupdate');
			$('.vpfdynamic-addnew-button').click(function(){
				var group = $(this).parents('.vpfdynamic-cont');
				$('.vpfdynamic-cont select').each(function(){
					$(this).chosen('destroy');
				})
				$('.vpfdynamic-cont .hasTooltip').each(function(){
					$(this).tooltip('destroy');
				});
				if(newMedia) {
					var newSet = $('li:last-child', group).clone();
					$('select', newSet).prop('selectedIndex', '');
					$('input:text,textarea', newSet).val('');
					group.append(newSet);
					group = $(this).parents('.vpfdynamic-cont');
					group.trigger('sortupdate');
					$('.field-media-wrapper').fieldMedia();					
				} else {
					var newSet = $('li:last-child', group).clone(true);
					$('select', newSet).prop('selectedIndex', '');
					$('input:text,textarea', newSet).val('');
					group.append(newSet);
					group = $(this).parents('.vpfdynamic-cont');
					group.trigger('sortupdate');
					SqueezeBox.assign($('.vpfdynamic-cont a.modal').get(), {
						parse: 'rel'
					});
				}
				$('.vpfdynamic-cont select').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'});
				});
				$('.vpfdynamic-cont .hasTooltip').each(function(){
					$(this).tooltip({'html': true,'container': 'body'});
				});
				$('html,body').animate({
					scrollTop: $('li:last-child', group).offset().top - 200
				}, 500);
			});
			$('.vpfdynamic-remove-button').click(function(){
				var group = $(this).parents('.vpfdynamic-cont');
				$(this).parents('li').animate({'opacity' : 0}, 500, function(){
					$(this).remove();
					group.trigger('sortupdate');
				});
			})
		});
		";
		
		$css = "ul.vpfdynamic-cont{list-style:none;padding:0;margin:0}.vpfdynamic-fields-set{position:relative}.vpfdynamic-fields-button-cont{position:absolute;top:0;right:0}.vpfdynamic-fields-button-cont .btn{margin-left:10px}.vpfdynamic-toolbar{margin-bottom:20px}.vpfdynamic-toolbar .btn{padding-left:35px;padding-right:35px}.vpfdynamic-move-button{padding:3px 4px 1px;cursor:move}.vpfdynamic-fields-set{background-color:#FFF;opacity:1}.ui-sortable-helper .vpfdynamic-fields-set{opacity:0.8}";
		
		$doc->addScriptDeclaration($js);
		$doc->addStyleDeclaration($css);
	}
	
	protected function prepareFields($setorder, $data)
	{
		$app = JFactory::getApplication();
		
		if($this->raw_fields === null)
		{
			$configFile = JPath::clean(__DIR__ . '/vpfdynamic.ini');
			$customConfigFile = !empty($this->element['config']) ? JPath::clean(JPATH_BASE . '/' . $this->element['config']) : null;
			
			if(!empty($customConfigFile) && file_exists($customConfigFile))
			{
				$configFile = $customConfigFile;
			}
			
			$this->raw_fields = parse_ini_file($configFile, true);
			
			if(empty($this->raw_fields))
			{
				$app->enqueueMessage('VPFDynamic::prepareFields could not parse ' . $configFile . ' file', 'error');
				return false;
			}
		}

		$fields = $this->raw_fields;
		$html = array();
		
		foreach($fields as $field_name => $field)
		{
			$field = (object) $field;
			$field->id = $this->original_id . '_' . $setorder . '_' . $field_name;
			$field->name = $this->original_name . '[' . $setorder . '][' . $field_name . ']';
			$field->title = addslashes('<strong>' . $field->label . '</strong><br/>' . $field->description);
			$value = isset($data[$field_name]) ? $data[$field_name] : $field->default;
			$field->type = strtolower($field->type);
			
			$html[] = '<div class="control-group">';
			
			$html[] = '<div class="control-label">';
			$html[] = '<label id="' . $field->id . '-lbl" for="' . $field->id . '" class="hasTooltip" title="' . $field->title . '">';
			$html[] = JText::_($field->label);
			$html[] = '</label>';
			$html[] = '</div>';
			
			$html[] = '<div class="controls">';			
			
			if($field->type == 'list')
			{
				$options = array();
				if (!empty($field->options)) 
				{
					foreach ($field->options as $v => $t) 
					{
						$options[] = JHTML::_('select.option', $v, $t);
					}
				}
				$html[] = JHtml::_('select.genericlist', $options, $field->name, '', 'value', 'text', $value, $field->id);
			}
			elseif($field->type == 'animations')
			{
				$options = array();
				$for = (string) !empty($field->for) ? $field->for : 'entrance';
				
				if (!empty($field->options)) 
				{
					foreach ($field->options as $v => $t) 
					{
						$options[] = JHTML::_('select.option', $v, $t);
					}
				}
				
				$options = $this->getAnimations($for, $options);
				$html[] = JHtml::_('select.genericlist', $options, $field->name, '', 'value', 'text', $value, $field->id);
			}
			elseif($field->type == 'textarea')
			{
				$html[] = '<textarea id="' . $field->id . '" name="' . $field->name . '" rows="5" cols="50">' . $value . '</textarea>';
			}
			elseif($field->type == 'media')
			{
				$this->id = $field->id;
				$this->name = $field->name;
				$this->value = $value;
				$html[] = parent::getInput();
			}
			elseif($field->type == 'hidden')
			{
				$html[] = '<input type="hidden" id="' . $field->id . '" name="' . $field->name . '" value="' . $value . '"/>';
			}
			else
			{
				$html[] = '<input type="text" id="' . $field->id . '" name="' . $field->name . '" value="' . $value . '"/>';
			}
			
			$html[] = '</div>';
			$html[] = '</div>';
			
			$field->display = implode($html);
		}
		
		return implode($html);
	}
	
	protected function getFieldSets($values)
	{
		$values = array_filter($values);
		$set_name = !empty($this->element['setlabel']) ? $this->element['setlabel'] : 'Set: ';
		
		if(empty($values))
		{
			$default_sets = (int) !empty($this->element['defaultsets']) ? $this->element['defaultsets'] : 2;

			for($i=0;$i<$default_sets;$i++)
			{
				$values[$i] = array();
			}
		}
		
		$html = array();
		
		foreach($values as $ordering => $data)
		{
			$html[] = '<li><fieldset class="vpfdynamic-fields-set" data-ordering="' . $ordering . '">';
			$html[] = '<legend>' . $set_name . '<span class="vpfdynamic-set-index">' . ($ordering + 1) . '</span></legend>';
			$html[] = '<div class="vpfdynamic-fields-button-cont">';
			$html[] = '<button type="button" class="btn btn-small vpfdynamic-remove-button hasTooltip" title="Remove"><i class="icon-trash"></i> Remove</button>';
			$html[] = '<div class="btn btn-small vpfdynamic-move-button hasTooltip" title="Move"><i class="icon-menu"></i></div>';
			$html[] = '</div>';
			$html[] = $this->prepareFields($ordering, $data);
			$html[] = '</fieldset></li>';
		}
		
		return implode($html);
	}
	
	public function getAnimations($for = 'entrance', $options = array())
	{
		$for = strtolower($for);
		$animationGroups = self::_getAnimations();

		if($for != 'all')
		{
			$escape_1 = ($for == 'entrance') ? 'exit' : 'entrance';
			$escape_2 = ($for == 'entrance') ? 'out' : 'in';
			
			foreach($animationGroups as $group => $animations)
			{
				if(strpos($group, $escape_1) === false)
				{
					foreach($animations as $animation => $active)
					{
						if($active && strpos(strtolower($animation), $escape_2) === false)
						{
							$options[] = JHtml::_('select.option', $animation, preg_replace('/(?<!\ )[A-Z]/', ' $0', ucfirst($animation)), 'value', 'text');
						}
					}
				}
			}
		}
		else
		{
			foreach($animationGroups as $group => $animations)
			{
				$group = ucwords(str_replace('_', ' ', $group));
				
				if(!isset($options[$group]))
				{
					$options[$group] = array();
				}
				
				foreach($animations as $animation => $active)
				{
					if($active)
					{
						$options[$group][] = JHtml::_('select.option', $animation, preg_replace('/(?<!\ )[A-Z]/', ' $0', ucfirst($animation)), 'value', 'text');
					}
				}
			}
		}
		
		return $options;
	}	
	
	protected static function _getAnimations()
	{		
		if (static::$animations === null)
		{
			$app = JFactory::getApplication();
			$json = JPath::clean(__DIR__ . '/vpfanimation/animate-config.json');
			
			if(!file_exists($json))
			{
				$app->enqueueMessage('JFormFieldVPFAnimation::_getAnimations missing file ' . $json, 'error');
				return false;
			}
			
			$string = file_get_contents($json);
			
			if(!$string)
			{
				$app->enqueueMessage('JFormFieldVPFAnimation::_getAnimations no data found in ' . $json, 'error');
				return false;
			}
			
			if(is_string($string))
			{
				static::$animations = json_decode($string, true);
			}
			else
			{
				static::$animations = array();
			}
		}

		return static::$animations;
	}	
}