<?php
/**
 * @package DJ-Catalog2
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

defined('_JEXEC') or die();
defined('JPATH_BASE') or die;

jimport('joomla.html.html');
jimport('joomla.form.formfield');

class JFormFieldDJCFieldOptionConfig extends JFormFieldSubform {
	
	protected $type = 'DJCFieldOptionConfig';
	
	static $fields = null;
	
	static $scriptLoaded = array();
	
	protected function getInput()
	{
		$html = $html2 = '';
		
		$fields = static::getDJC2Fields();
		
		$json = json_encode($fields);
		
		$formname = 'form_' . str_replace(array('jform[', '[', ']'), array('', '_', ''), $this->fieldname);
		
		$html .= '<div class="control-group">';
		$html .= '<div class="controls">';
		$html .= '<select data-formparent="'.$formname.'" class="djc_formparent" onchange="DJC2SetOptionsConf_'.$formname.'(this);" name="'.$this->name.'[field_id][]">';
		$html .= '<option value="">'.JText::_('COM_DJCATALOG2_LIST_PLEASE_SELECT').'</option>';
		
		$html2 .= '<fieldset data-formchild="'.$formname.'"  class="djc_formchild checkbox">';
		
		$html2 .= '<table class="table table-bordered">';
		$html2 .= '<thead>';
		$html2 .= '<tr>';
		$html2 .= '<th></th><th colspan="2">'.JText::_('COM_DJCATALOG2_CONFIGURATION_OPT_PRICE_LBL').'</th><th>'.JText::_('COM_DJCATALOG2_CONFIGURATION_OPT_SKU_LBL').'</th><th>'.JText::_('COM_DJCATALOG2_CONFIGURATION_OPT_INFO_LBL').'</th>';
		$html2 .= '</tr>';
		$html2 .= '</thead>';
		
		$html2 .= '<tbody>';
		
		//$value = is_array($this->value) ? $this->value : array($this->value);
		//$this->value = $value;
		
		$v = $this->value;
		
		//echo '<pre>' . print_r($this->value, true) . '</pre>';

		foreach($fields as $field) {
			$selected = false;
			
			if (is_object($v) && is_array($v->field_id) && in_array($field->id, $v->field_id)) {
				$selected = true;
				
				if (isset($v->price) && is_object($v->price)) {
					$v->price = Joomla\Utilities\ArrayHelper::fromObject($v->price);
				}
				if (isset($v->price_mod) && is_object($v->price_mod)) {
					$v->price_mod = Joomla\Utilities\ArrayHelper::fromObject($v->price_mod);
				}
				if (isset($v->info) && is_object($v->info)) {
					$v->info = Joomla\Utilities\ArrayHelper::fromObject($v->info);
				}
				if (isset($v->sku) && is_object($v->sku)) {
					$v->sku = Joomla\Utilities\ArrayHelper::fromObject($v->sku);
				}
			}
			$ii = 0;
			
			$priceModOpts = [['value' => 'add', 'text' => '+'], ['value' => 'multiply', 'text' => 'x']];
			
			foreach($field->options as $option) {
				$optSelected = false;
				if ($selected && is_array($v->option_id) && in_array($option->id, $v->option_id)) {
					$optSelected = true;
				}
				
				$html2 .= '<tr class="djc_checkbox_field_wrap"  style="display: none">';
				$html2 .= '<td  width="20%">';
				$html2 .= '<label class="checkbox">'. $option->value .'<input type="checkbox" id="'.$this->id .'_'. $ii .'" name="'.$this->name.'[option_id][]" value="'.$option->id.'" data-fieldid="'.$field->id.'" '.($optSelected ? 'checked="checked"' : '' ).' /></label>';
				$html2 .= '</td>';
				
				$html2 .= '<td class="djc_opt_input" width="1%">';
				$html2 .= '<input type="number" step="any" class="input input-medium" name="'.$this->name.'[price]['.$option->id.']" '.($optSelected ? 'value="'.htmlspecialchars($v->price[$option->id], ENT_COMPAT) .'"' : 'disabled="disabled"').' placeholder="'.JText::_('COM_DJCATALOG2_CONFIGURATION_OPT_PRICE').'" />';
				$html2 .= '</td>';
				$html2 .= '<td class="djc_opt_input" width="1%">';
				$html2 .= '<select class="input input-mini" name="'.$this->name.'[price_mod]['.$option->id.']" '.($optSelected ? '' : 'disabled="disabled"').'>';
				
				foreach($priceModOpts as $priceModOpt) {
					$pmSelected = '';
					if($optSelected) {
						$pmSelected = ($v->price_mod[$option->id] == $priceModOpt['value']) ? ' selected="selected" ' : '';
					}
					$html2 .= '<option '.$pmSelected.' value="'.$priceModOpt['value'].'">'.$priceModOpt['text'].'</option>';
				}
				
				$html2 .= '</select>';
				$html2 .= '</td>';
				$html2 .= '<td class="djc_opt_input" width="1%">';
				$html2 .= '<input type="text" class="input input-medium" name="'.$this->name.'[sku]['.$option->id.']" '.($optSelected ? 'value="'.htmlspecialchars($v->sku[$option->id], ENT_COMPAT).'"' : 'disabled="disabled"').' placeholder="'.JText::_('COM_DJCATALOG2_CONFIGURATION_OPT_SKU').'" />';
				$html2 .= '</td>';
				$html2 .= '<td class="djc_opt_input" width="1%">';
				$html2 .= '<input type="text" class="input input-medium" name="'.$this->name.'[info]['.$option->id.']" '.($optSelected ? 'value="'.htmlspecialchars($v->info[$option->id], ENT_COMPAT).'"' : 'disabled="disabled"').' placeholder="'.JText::_('COM_DJCATALOG2_CONFIGURATION_OPT_INFO').'" />';
				$html2 .= '</td>';
				$html2 .= '</tr>';
				
				$ii++;
			}
			
			$html .= '<option value="'.$field->id.'" '.($selected ? 'selected="selected"' : '' ).'>'.$field->name.'</option>';
		}
		
		$html2 .= '</tbody>';
		$html2 .= '</table>';
		
		$html2 .= '</fieldset>';
		$html .= '</select>';
		
		$html .= '</div></div>';
		
		if (!isset(static::$scriptLoaded[$formname])) {
			$script = '
			jQuery(document).ready(function(){
				window.DJC2SetOptionsConf_' . $formname.' = function(elem) {
					var formname = "'.$formname.'";
					var $this = jQuery(elem);
					var parents = jQuery(\'select[data-formparent="'.$formname.'"]\');
					var children = jQuery(\'fieldset[data-formchild="'.$formname.'"]\');
						
					if (parents.length < 1) return;
						
					var counter = 0;
					parents.each(function(){
						if ($this.is(jQuery(this))) {
							var target = children.get(counter);
						
							var field_id = $this.val();
							if (/*!field_id ||*/ target.length < 1) return;
						
							jQuery(target).find("input[type=\"checkbox\"]").each(function(i,e){
								var ee = jQuery(e);
								if (jQuery(ee).attr("data-fieldid") == field_id) {
									ee.parents(".djc_checkbox_field_wrap").css("display", "");
									ee.removeAttr("disabled");
								} else {
									ee.parents(".djc_checkbox_field_wrap").css("display", "none");
									ee.attr("disabled", "disabled");
									ee.removeAttr("checked");
						
									ee.parents(".djc_checkbox_field_wrap").find("td.djc_opt_input input").val("").attr("disabled", "disabled");
									ee.parents(".djc_checkbox_field_wrap").find("td.djc_opt_input select").val("").attr("disabled", "disabled").trigger("liszt:updated");
								}
							});
						
							jQuery(target).find("input[type=\"checkbox\"]").unbind("change");
							jQuery(target).find("input[type=\"checkbox\"]").change(function(){
								if (jQuery(this).is(":checked")) {
									jQuery(this).parents(".djc_checkbox_field_wrap").find("td.djc_opt_input input").removeAttr("disabled");
									jQuery(this).parents(".djc_checkbox_field_wrap").find("td.djc_opt_input select").removeAttr("disabled").trigger("liszt:updated");
								} else {
									jQuery(this).parents(".djc_checkbox_field_wrap").find("td.djc_opt_input input").attr("disabled", "disabled");
									jQuery(this).parents(".djc_checkbox_field_wrap").find("td.djc_opt_input select").attr("disabled", "disabled").trigger("liszt:updated");
								}
							});
						}
						counter++;
					});
				}
						
				jQuery(\'select[data-formparent="'.$formname.'"]\').each(function(i,e){
					DJC2SetOptionsConf_' . $formname.'(e);
				});
			});
			';
			
			JFactory::getDocument()->addScriptDeclaration($script);
			
			static::$scriptLoaded[$formname] = true;
		}
		return $html . $html2;
		
	}
	
	protected static function getDJC2Fields() {
		if (is_null(static::$fields)) {
			$db = JFactory::getDbo();
			$query = $db->getQuery(true);
			$query->select('o.*, f.name as field_name');
			$query->from('#__djc2_items_extra_fields_options AS o');
			$query->join('INNER', '#__djc2_items_extra_fields AS f ON f.id = o.field_id');
			$query->order('f.ordering, o.ordering');
			$query->where('f.cart_variant=2');
			$db->setQuery($query);
			
			$fields = array();
			
			$rows = $db->loadObjectList();
			foreach($rows as $row) {
				$field = new stdClass();
				if (isset($fields[$row->field_id])) {
					$field = $fields[$row->field_id];
				} else {
					$field->id = $row->field_id;
					$field->name = $row->field_name;
					$field->options = array();
				}
				
				$field->options[] = $row;
				
				$fields[$row->field_id] = $field;
			}
			static::$fields = $fields;
		}
		
		return static::$fields;
	}
}
?>