<?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('Restricted access');

$user = JFactory::getUser();
$priceAuth = ($user->guest) ? (($params->get('price_restrict', '0') == '1' || !empty($item_cursor->price_restrict)) ? false : true) : true;

$onStock = (bool)( ($item_cursor->onstock == 1 && $item_cursor->stock > 0) || $item_cursor->onstock >= 2 );
$canCheckout = (bool)($params->get('cart_enabled', false) && (($onStock && $priceAuth  && $item_cursor->final_price > 0.0) || $cart_variant_fields));
$canQuery = (bool)($params->get('cart_query_enabled', 1));
$stockHandling = $params->get('show_outstock_info', 0);
if ($stockHandling > 0 && $item_cursor->product_type != 'tangible' && $item_cursor->onstock < 3 && $canQuery == false) {
	$stockHandling = 1;
} else if ($item_cursor->onstock == 3) {
	$stockHandling = 0;
}

?>

<?php if (($canCheckout || $canQuery) && $item_cursor->available) {
	$return_url = base64_encode(JUri::getInstance()->__toString());
	$button_value = $canCheckout ? JText::_('COM_DJCATALOG2_ADD_TO_CART') : JText::_('COM_DJCATALOG2_ADD_TO_QUOTE_CART');
	$button_class = $canCheckout ? 'djc_addtocart_btn' : 'djc_addtoquote_btn';
	$button_disabled = '';

	$results = JFactory::getApplication()->triggerEvent('onDJCatalog2BeforeCart', array($item_cursor, $params, 'items.'.$params->get('list_layout','items')));
	foreach($results as $html){
		echo $html;
	}

	?>
	<form action="<?php echo JRoute::_('index.php'); ?>" method="post" class="djc_form_addtocart" data-itemid="<?php echo $item_cursor->id; ?>">
		<?php if ($item_cursor->parent_id == 0) { ?>
			<div class="djc_cart_variants">
				<?php if (count($cart_variant_fields)) { ?>
					<?php foreach ($cart_variant_fields as $field) {
						$variant_field_cursor = $field;
						echo $loadTemplate('addtocart_variantfields');
					} ?>
				<?php } ?>
			</div>

		<?php if (count($all_customisations) > 0 && $customisations_form) {?>
			<div class="djc_cart_customisations">
				<?php foreach($customisations_form->getFieldset() as $field) {?>
					<?php echo $field->renderField(); ?>
				<?php } ?>
			</div>
			<script>
                (function($){
                    $(document).ready(function(){
                        function toggleRequiredCustoms() {
                            var elms = $('[data-custom-required]');
                            $(elms).each(function(){
                                var element = $(this);
                                if (element.is(':visible')) {
                                    element.addClass('required').attr('required', 'required').attr('aria-required', 'true');
                                } else {
                                    element.removeClass('required').removeAttr('required').removeAttr('aria-required');
                                }
                            });
                        }

                        var custShowOns = $('.djc_cart_customisations').find('[data-showon]');
                        $(custShowOns).each(function(){
                            var wrapper = $(this);
                            var required = wrapper.find('.required');
                            required.attr('data-custom-required', 'required');
                        });

                        toggleRequiredCustoms();

                        var customisations = $('#customisation').find('input[type="checkbox"][name="customisation[]"]');
                        $(customisations).change(function(){
                            setTimeout(function(){toggleRequiredCustoms();}, 600);
                        });
                    });
                })(jQuery);
			</script>
		<?php } ?>
		<?php } ?>

		<div class="djc_addtocart">
			<?php

			$unit = DJCatalog2HelperQuantity::getUnit($item_cursor->unit_id);
			echo DJCatalog2HelperQuantity::renderInput($unit, $item_cursor, array('cart_button'=>array('type'=>'input', 'value' => $button_value, 'class' => 'btn btn-primary '.$button_class, 'attributes' => $button_disabled)));
			?>
		</div>

		<input type="hidden" name="option" value="com_djcatalog2" />
		<input type="hidden" name="task" value="cart.add" />
		<input type="hidden" name="return" value="<?php echo $return_url; ?>" />
		<input type="hidden" name="item_id" value="<?php echo (int)$item_cursor->id; ?>" />
		<input type="hidden" name="combination_id" value="" />

		<?php echo JHtml::_( 'form.token' ); ?>
	</form>
<?php } ?>

<?php
if (!$onStock && ($params->get('stock_notifications', false) && (JFactory::getUser()->id > 0 || $params->get('stock_notifications_registered', false) == false))) {
	$stockNotify = array('item' => $item_cursor, 'params' => $params);
	$layout = new JLayoutFile('com_djcatalog2.stocknotify', DJCatalog2ThemeHelper::getLayoutBasePath(), array('component'=> 'com_djcatalog2'));
	echo $layout->render($stockNotify);
}
?>

<?php if ($item_cursor->parent_id == 0 && count($cart_variant_fields) > 0) {
	$prevCursor = $item_cursor;

	$handleStockNotifications = false;
	if ($params->get('stock_notifications', false) && (JFactory::getUser()->id > 0 || $params->get('stock_notifications_registered', false) == false)) {
		$handleStockNotifications = true;
	}

	$priceOpts = array(
		'when_not_null' => $params->get('show_price_item') == 1,
		'display_always' => $params->get('show_price_item') == 2,
		'restricted_note' => $params->get('restricted_price_info', 1),
		'show_old' => $params->get('show_old_price_item', 1),
		'structured_data' => true
	);

	foreach ($item_cursor->_combinations as &$combination) {
		$cursor = new stdClass();
		$cursor->id = $item->id;
		$cursor->price = ($combination->price == 0.0) ? $item->price : $combination->price;
		$cursor->final_price = (isset($combination->final_price)) ? $combination->final_price : (($combination->price == 0.0) ? $item->final_price : $combination->price);
		$cursor->tax_rule_id = $item->tax_rule_id;

		$item_cursor = $cursor;

		$priceData = array('item' => $item_cursor, 'params' => $params, 'options' => $priceOpts);
		$layout = new JLayoutFile('com_djcatalog2.price', DJCatalog2ThemeHelper::getLayoutBasePath(), array('component' => 'com_djcatalog2'));
		$combination->price_html = $layout->render($priceData);

		$combination->stock_notify_html = '';
		if ($handleStockNotifications && $combination->stock <= 0.0000) {
			$stockNotify = array('item' => $combination, 'item_type' => 'combination', 'params' => $params);
			$layout = new JLayoutFile('com_djcatalog2.stocknotify', DJCatalog2ThemeHelper::getLayoutBasePath(), array('component'=> 'com_djcatalog2'));

			$combination->stock_notify_html = $layout->render($stockNotify);
		}


	}
	unset($combination);
	$item_cursor = $prevCursor;
	?>
	<script>
        (function($){

            var DJCatalog2CombinationSelector = function(itemId, combinations) {
                var self = this;

                self.combinations = JSON.parse(combinations);
                //console.log(self.combinations);
                self.itemId = itemId;
                self.form = $('.djc_form_addtocart[data-itemid="'+itemId+'"]');
                self.inputs = self.form.find('.djc_cart_variants').find('select.has_combo,input.has_combo[type="radio"]');
                self.inputOpts =  self.form.find('.djc_cart_variants').find('select.has_combo option,input.has_combo[type="radio"]');
                self.cartBtn =  self.form.find('.djc_addtocart input[type="submit"]');

                self.cartBtnValue = self.cartBtn.val();
                self.outOfStockInfo = '<?php echo JText::_('COM_DJCATALOG2_PRODUCT_OUT_OF_STOCK'); ?>';
                self.inStockInfo = '<?php echo JText::_('COM_DJCATALOG2_PRODUCT_IN_STOCK'); ?>';
                self.inStockInfoNum = '<?php echo JText::sprintf('COM_DJCATALOG2_PRODUCT_IN_STOCK_QTY', '###'); ?>';
                self.handleStock = <?php echo $params->get('cart_enabled', false) ? $stockHandling : 'false'; ?>;
                self.handleStockNotifications = <?php echo ( $params->get('stock_notifications', false) && (JFactory::getUser()->id > 0 || $params->get('stock_notifications_registered', false) == false) ) ? 'true' : 'false' ?>;

                $('.djc_cartvariant_colors label').keypress(function (e) {
                    var key = e.which;
                    if (key == 13)  // the enter key code
                    {
                        $(this).click();
                        return false;
                    }
                });

                $('[data-fieldoption]').each(function(){
                    var opt = $(this);
                    var fieldId = opt.attr('data-fieldid');
                    var optionId = opt.attr('data-fieldoption');
                    var optionCombinations = opt.attr('data-optioncombinations');

                    if (fieldId && optionId && optionCombinations) {
                        self.optCombinations[optionId] = JSON.parse(optionCombinations);
                    }
                });

                self.inputs.change(function(){
                    var input = this;

                    // self.cartBtn.attr('disabled', 'disabled').addClass('disabled');
                    self.cartBtn.val(self.cartBtnValue);
                    self.form.find('input[name="combination_id"]').val('');

                    setTimeout(function() {
                        self.toggleOptions($(input));
                        self.discoverCombinations();
                    }, 50);
                });

                self.inputs.filter('input[type=radio]').each(function(){
                    $(this).mousedown(function() {
                        if (this.checked) {
                            $(this).mouseup(function(e) {
                                var radio = this;
                                setTimeout(function() {
                                    radio.checked = false;
                                    $(radio).trigger('change');
                                }, 5);
                                $(this).unbind('mouseup');
                            });
                        }
                    });

                    var lblRadio = this;
                    $(lblRadio).parent('label').mousedown(function() {
                        if (lblRadio.checked) {
                            $(this).mouseup(function(e) {
                                setTimeout(function() {
                                    lblRadio.checked = false;
                                    $(lblRadio).trigger('change');
                                }, 5);
                                $(this).unbind('mouseup');
                            });
                        }
                    });
                });

                var selected = self.inputs.filter('select,:checked');
                if (selected.length == 0) {
                    // assuming that first attribute is radio/color
                    self.inputs.first().attr('checked', 'checked');
                } else {
                    // assuming that we're dealing with select field
                    self.inputs.first().trigger('change');
                }

                this.temp = $('<div />').css('display', 'none');
                $(document.body).append(this.temp);

                self.discoverCombinations();
            };

            DJCatalog2CombinationSelector.prototype = {
                constructor: DJCatalog2CombinationSelector,
                itemId: 0,
                combinations: {},
                optCombinations: {},
                optParams: {},
                fieldParams: {},
                xhr: null,
                temp: null,
                getOptParams: function(input) {
                    var type = input[0].nodeName;
                    var optParams = (type == 'SELECT') ? input.find(':selected').attr('data-optioncombinations')  : input.attr('data-optioncombinations');
                    if (typeof optParams == 'undefined' || !optParams || optParams == '') {
                        false;
                    }
                    return JSON.parse(optParams);
                },
                getFieldParams: function(input) {
                    var type = input[0].nodeName;
                    var params = (type == 'SELECT') ? input.attr('data-combinations') : input.parents('.djc_cartvariant_colors').attr('data-combinations');
                    if (typeof params == 'undefined' || !params || params == '') {
                        return false;
                    }
                    return JSON.parse(params);
                },
                toggleOptions: function(input){
                    var self = this;
                    var fieldId = input.attr('data-fieldid');
                    var value = (input.is(':checked') || input.is('select')) ? input.val() : false;

                    $('table.djc_combinations-table[data-optionid]').hide();

                    if (!value) {
                        var firstSelected = null;
                        self.inputOpts.filter(':selected,:checked').each(function(){
                            if ($(this).val() != '') {
                                firstSelected = $(this);
                            }
                        });

                        if (firstSelected == null) {
                            self.inputOpts.removeAttr('disabled').removeClass('disabled');
                        } else {
                            //console.log(self.inputOpts);
                            self.inputOpts.each(function(){
                                var opt = $(this);
                                if (opt.attr('data-fieldid') == firstSelected.attr('data-fieldid')) {
                                    opt.removeAttr('disabled').removeClass('disabled');
                                }
                            });
                            firstSelected.trigger('change');
                        }
                    } else {
                        var possibleCombinations = self.optCombinations[value];
                        if (typeof possibleCombinations != 'undefined') {
                            self.inputOpts.each(function(){
                                var other = $(this);
                                if (other.attr('data-fieldid') != fieldId) {
                                    var disabled = other.is(':disabled');

                                    var otherOption = other.attr('data-fieldoption');
                                    var otherCombinations =  self.optCombinations[otherOption];
                                    if (typeof otherCombinations == 'undefined') {
                                        disabled = true;
                                    } else {
                                        var foundMatch = false;
                                        $.each(possibleCombinations, function(i1, e1){
                                            $.each(otherCombinations, function(i2, e2){
                                                if (e1 == e2) {
                                                    foundMatch = true;
                                                    return;
                                                }
                                            });
                                            if (foundMatch) return;
                                        });

                                        if (!foundMatch) {
                                            disabled = true;
                                        } else {
                                            disabled = false;
                                        }
                                    }

                                    if (disabled && other.val() != '') {
                                        other.attr('disabled', 'disabled').addClass('disabled').removeAttr('selected').removeAttr('checked');
                                    } else {
                                        other.removeAttr('disabled').removeClass('disabled');
                                    }
                                }
                            });
                        }

                        $('table.djc_combinations-table[data-optionid='+value+']').show();
                    }
                },
                getMatchingCombinations: function() {
                    var self = this;
                    var candidates = [];


                    self.inputs.filter('select,:checked').each(function(){
                        var possibleCombinations = self.optCombinations[$(this).val()];
                        if (typeof possibleCombinations != 'undefined') {
                            candidates.push(possibleCombinations);

                            jQuery(this).removeClass('djc-invalid');

                        }

                    });

                    if (candidates.length == 0) {
                        return [];
                    }

                    var matches = candidates.shift().filter(function(v) {
                        return candidates.every(function(a) {
                            return a.indexOf(v) !== -1;
                        });
                    });


                    return matches;
                },
                discoverCombinations: function(){
                    var self = this;
                    var matches = self.getMatchingCombinations();

                    if (matches.length == 0) {
                        // it technically should not be possible, but just in case....
                    } else if (matches.length > 1) {
                        this.loadImages(0);
                        // more than one combination available - means that user needs to select more options
                    } else {
                        // bingo!
                        var combinationId = matches.shift();


                        if (parseFloat(self.combinations[combinationId].stock) <= 0.0000 && self.handleStock) {
                            // self.cartBtn.attr('disabled', 'disabled').addClass('disabled');
                            self.cartBtn.val(self.outOfStockInfo);
                            self.form.find('input[name="combination_id"]').val('');
                        } else {
                            self.cartBtn.val(self.cartBtnValue);
                            self.cartBtn.removeAttr('disabled').removeClass('disabled');
                            self.form.find('input[name="combination_id"]').val(combinationId);
                        }

                        // update price wrapper
                        //$('div.djc_price[data-itemid='+self.combinations[combinationId].item_id+']').html(self.combinations[combinationId].price_html).show();
                        $('div.djc_price[data-itemid='+self.combinations[combinationId].item_id+']').replaceWith(self.combinations[combinationId].price_html).show();

                        if (self.handleStockNotifications && self.combinations[combinationId].stock_notify_html != '') {
                            $('div.djc_price[data-itemid='+self.combinations[combinationId].item_id+']').append(self.combinations[combinationId].stock_notify_html).show();
                        }

                        if (self.handleStock) {
                            var stockWrap = $('<span/>', {'class': 'djc_stock_info'});
                            if (parseFloat(self.combinations[combinationId].stock) <= 0.0000) {
                                stockWrap.text(self.outOfStockInfo);
                                stockWrap.addClass('djc_out_stock');
                            } else {
                                if (self.handleStock == 2 || self.handleStock == 1) {
                                    stockWrap.text(self.inStockInfo);
                                } else {
                                    var text = self.inStockInfoNum;
                                    text = text.replace('###', parseFloat(self.combinations[combinationId].stock).toString());
                                    stockWrap.text(text);
                                }
                                stockWrap.addClass('djc_in_stock');
                            }
                            $('#djcatalog p.djc_stock').html($(stockWrap));
                        }

                        // update images
                        if (typeof self.combinations[combinationId].images != 'undefined' && self.combinations[combinationId].images.length > 0){
                            this.loadImages(combinationId);
                        } else {
                            this.loadImages(0);
                        }
                    }
                },
                loadImages: function(combinationId) {
                    var self = this;

                    if (this.xhr && this.xhr.state() == 'pending') {
                        this.xhr.abort();
                    }
                    var data = 'layout=default_images&tmpl=component';
                    if (parseInt(combinationId) > 0)  {
                        data += '&combination_id=' + combinationId;
                    }
                    self.request = $.ajax({
                        url: '<?php echo JRoute::_(DJCatalog2HelperRoute::getItemRoute($item_cursor->slug, $item_cursor->catslug), false);?>',
                        method: 'get',
                        data: data,
                        dataType: 'html',
                    }).done(function(data, status, xhr){
                        var respBody = data.match(/<body[^>]*>([\w|\W]*)<\/body>/im);
                        if (respBody){
                            respBody = respBody[1].replace(new RegExp('<script[^>]*>([\\S\\s]*?)<\/script\\s*>', 'img'), '');
                            //respBody = respBody[1];
                        }
                        var curImages = $('#djcatalog.djc_item .djc_images').first();
                        curImages.empty();

                        self.temp.html(respBody);

                        var images = self.temp.find('.djc_images');
                        curImages.replaceWith(images);

                        self.temp.empty();

                        $('#djcatalog').trigger('ajaxFilter:loadItems');
                        DJCatImageSwitcher();
                    });
                }
            };

            $(document).ready(function(){
                var combinations = '<?php echo addslashes(json_encode($item_cursor->_combinations))?>';
                comboSelector = new DJCatalog2CombinationSelector(<?php echo $item_cursor->id; ?>, combinations);
            });
        })(jQuery);
	</script>

<?php } ?>
