<?php
/**
 * --------------------------------------------------------------------------------------------
 * VP Custom Filter Module - Joomla! 3 Module for VirtueMart 3.0
 * --------------------------------------------------------------------------------------------
 * @package    VP Custom Filter 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
 * --------------------------------------------------------------------------------------------
*/
defined('_JEXEC') or die();

// Register VirtueMart config to Joomla autoloader
JLoader::register('VmConfig', JPATH_ROOT . '/administrator/components/com_virtuemart/helpers/config.php');

// Load VirtueMart Config and language
VmConfig::loadConfig();
VmConfig::loadJLang('com_virtuemart');

class JFormFieldVmpricerange extends JFormField
{
	protected $type = 'vmpricerange';
	
	protected $fieldXml = null;
	
	protected $customfields = null;
	
	protected $context = 'vmpricerange';
	
	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->value   = !empty($this->value) ? (array) $this->value : array();

		self::_prepareJS($this->id, $this->name, $this->fieldname, $sets);
		
		$html  = '<span id="' . $this->id . '"></span>';
		
		if(version_compare(JVERSION, '3.0.0', 'ge'))
		{
			$html .= '</div></div>';
		}
		else
		{
			$html .= '</li></ul>';
		}
		
		$html .= '<ul class="vppricerange-cont adminformlist">';
	
		$html .= '<div class="vppricerange-toolbar">';
		
		if(!empty($this->element['description']))
		{
			$html .= '<div class="vppricerange-desc">' . JText::_($this->element['description']) . '</div>';
		}
		
		$html .= '<button type="button" class="btn btn-small btn-success vppricerange-addnew-button">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']) . ': ' : 'Custom Price Range: ';

		foreach($forms as $form)
		{
			foreach ($form->getFieldsets() as $group => $fieldset)
			{
				$fields = $form->getFieldset($group);
				
				if (count($fields))
				{
					$html[] = '<li>';
					$html[] = '<fieldset class="vppricerange-fields-set" data-ordering="' . $fieldset->label . '">';
					
					$html[] = '<legend>' . $set_name . '<span class="vppricerange-set-index">' . ($fieldset->label + 1) . '</span></legend>';
					
					$html[] = '<div class="vppricerange-fields-button-cont">';
					$html[] = '<button type="button" class="btn btn-small vppricerange-remove-button" title="Remove"><i class="icon-trash"></i> 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__) . '/vmpricerange/fields.xml');
			$customXml = !empty($this->element['form']) ? JPath::clean(JPATH_BASE . '/' . $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)
	{
		// Only load once
		if (isset(static::$loaded[__METHOD__]))
		{
			return;
		}
		
		$joomla3 = version_compare(JVERSION, '3.0.0', 'ge') ? '1' : '0';
		
		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);
		
		$js = "
		jQuery(document).ready(function($) {
			var joomla3 = " . $joomla3 . ";
			if(joomla3) {
				$('span#" . $id . "').closest('.control-group').hide();
			} else {
				$('span#" . $id . "').closest('li').hide();
			}
			$('.vppricerange-cont').on('sortupdate', function(event, ui) {
				var fieldset, oldOrdering;
				$(this).children('li').each(function(index, element) {
					fieldset = $('fieldset.vppricerange-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));
						}
					});
					$('.vppricerange-set-index', this).fadeOut(function() {
						$(this).text(index + 1).fadeIn();
					});
				});
				if($(this).children('li').length <= " . $sets . ") {
					$('.vppricerange-remove-button', this).attr('disabled', true);
				} else {
					$('.vppricerange-remove-button', this).removeAttr('disabled');
				}
			});
			$('.vppricerange-cont').trigger('sortupdate');
			$('.vppricerange-addnew-button').click(function(){
				var group = $(this).parents('.vppricerange-cont');
				if(joomla3) {
					$('.vppricerange-cont select').each(function(){
						$(this).chosen('destroy');
					})
					$('.vppricerange-cont .hasTooltip').each(function(){
						$(this).tooltip('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).parents('.vppricerange-cont');
				group.trigger('sortupdate');
				if(joomla3) {
					$('.vppricerange-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'});
					});
					$('.vppricerange-cont .hasTooltip').each(function(){
						$(this).tooltip({'html': true,'container': 'body'});
					});
				}
				$('html,body').animate({
					scrollTop: $('li:last-child', group).offset().top - 200
				}, 500);
			});
			$('.vppricerange-remove-button').click(function(){
				var group = $(this).parents('.vppricerange-cont');
				$(this).parents('li').animate({'opacity' : 0}, 500, function(){
					$(this).remove();
					group.trigger('sortupdate');
				});
			})
		});
		";
		
		$css = "ul.vppricerange-cont{list-style:none;padding:0;margin:0}.vppricerange-fields-set{position:relative}.vppricerange-fields-button-cont{position:absolute;top:0;right:0}.vppricerange-fields-button-cont .btn{margin-left:10px}.vppricerange-toolbar{margin-bottom:20px}.vppricerange-toolbar .btn{padding-left:35px;padding-right:35px}.vppricerange-move-button{padding:3px 4px 1px 5px;cursor:move}.vppricerange-fields-set{background-color:#FFF;opacity:1}.ui-sortable-helper .vppricerange-fields-set{opacity:0.8}.vppricerange-toolbar{text-align:right}.vppricerange-desc{float:left;margin-bottom:10px;text-align:left}";

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