<?php
/** 
 * @package     VikRestaurants
 * @subpackage  core
 * @author      E4J s.r.l.
 * @copyright   Copyright (C) 2023 E4J s.r.l. All Rights Reserved.
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @link        https://vikwp.com
 */

// No direct access
defined('ABSPATH') or die('No script kiddies please!');

$itemid = isset($displayData['Itemid']) ? $displayData['Itemid'] : null;

if (is_null($itemid))
{
	$itemid = JFactory::getApplication()->input->get('Itemid', null, 'uint');
}

$checkoutUrl = JRoute::rewrite('index.php?option=com_vikrestaurants&view=takeawayconfirm' . ($itemid ? '&Itemid=' . $itemid : ''));

?>

<div class="vr-overlay" id="vrupselloverlay" style="display: none;">

	<div class="vr-modal-box">

		<div class="vr-modal-head">

			<div class="vr-modal-head-title">
				<h3><?php echo JText::translate('VRE_UPSELLING_MODAL_TITLE'); ?></h3>
			</div>

			<div class="vr-modal-head-dismiss">
				<a href="javascript:void(0)" onClick="vrCloseUpsellingOverlay();" data-role="dismiss">
					<span class="visually-hidden"><?php echo JText::translate('VRCLOSE'); ?></span>
					<span aria-hidden="true">×</span>
				</a>
			</div>

		</div>

		<div class="vr-modal-body">

			<div class="vre-overlay-upselling-items">
				
			</div>

			<div class="vrtk-additem-bottom dish-item-overlay-footer">

				<!-- CHECKOUT LINK -->

				<a href="<?php echo $checkoutUrl; ?>" id="vrtk-checkout-button" class="vre-btn success">
					<?php echo JText::translate('VRE_GO_CHECKOUT_BTN'); ?>
				</a>
				
			</div>

		</div>

	</div>

</div>

<?php
JText::script('VRTKADDITEMERR2');
JText::script('VRE_ARIA_ADD_ITEM_CART');
?>

<script>
	(function($) {
		'use strict';

		window.vrOpenUpsellingOverlay = (ref) => {
			const overlay = $('#' + (ref || 'vrupselloverlay'));
			
			// add loading image
			overlay.find('.vre-overlay-upselling-items').html(
				'<div class="vr-modal-overlay-loading">\n'+
					'<img id="img-loading" src="<?php echo VREASSETS_URI . 'css/images/hor-loader.gif'; ?>" />\n'+
				'</div>\n'
			);

			// show modal
			overlay.show();

			// prevent body from scrolling
			$('body').css('overflow', 'hidden');
			
			// make request to load the eligible items for upselling
			vrOverlayRefreshUpselling(overlay);
		}

		window.vrCloseUpsellingOverlay = (ref) => {
			const overlay = $('#' + (ref || 'vrupselloverlay'));

			// make body scrollable again
			$('body').css('overflow', 'auto');

			// hide overlay
			overlay.hide();
			// clear overlay body
			overlay.find('.vre-overlay-upselling-items').html('');
		}

		const vrOverlayRefreshUpselling = (overlay) => {
			// call promise defined by the component
			window.vrRefreshUpselling().then((data) => {
				if (typeof vrRefreshUpselling !== 'function') {
					throw 'Missing [vrRefreshUpselling] function! Possible outdated override.';
				}

				if (!(data.menus || []).length) {
					throw 'No items eligible for upselling.';
				}

				const upsellingContainer = $('.vre-overlay-upselling-items');
				upsellingContainer.html('');

				const currency = VRECurrency.getInstance();

				data.menus.forEach((menu) => {
					menu.products.forEach((item) => {
						if ((item.options || []).length == 0) {
							// normalize options with a placeholder
							item.options.push({
								id: 0,
								name: '',
								price: 0,
							});
						}

						item.options.forEach((option) => {
							const itemBox = $('<div class="overlay-upselling-item"></div>');

							const itemFullName = item.name + (option.name ? ' - ' + option.name : '');
							const itemPrice = parseFloat(item.price) + parseFloat(option.price);

							if (item.image) {
								const imageBox = $('<div class="upselling-item-image"></div>').html(item.image);
								imageBox.on('click', function() {
									const imgTag = $(this).find('img');

									$.fancybox.open({
										src:  imgTag.attr('src'),
										type: 'image',
										opts: {
											caption: imgTag.attr('alt') || itemFullName,
										},
									});
								});

								itemBox.append(imageBox);
							}

							const body = $('<div class="upselling-item-body"></div>');

							const details = $('<div class="upselling-item-details"></div>');

							const detailsTop = $('<div class="upselling-item-details-top"></div>');
							detailsTop.append($('<div class="upselling-item-details-name"></div>').html(itemFullName));

							if ((item.attributes || []).length) {
								const detailsAttributes = $('<div class="upselling-item-details-attributes"></div>');
								item.attributes.forEach((attr) => {
									detailsAttributes.append(attr.image);
								});
								detailsTop.append(detailsAttributes);
							}

							details.append(detailsTop);

							if (item.description) {
								details.append($('<div class="upselling-item-details-desc"></div>').html(item.description));
							}

							body.append(details);

							const priceBox = $('<div class="upselling-item-pricing"></div>');

							priceBox.append($('<div class="upselling-item-details-price"></div>').html(currency.format(itemPrice)));

							const addButton = $('<a href="javascript:void(0)" class="upselling-item-add"></a>');
							addButton.append($('<i class="fas fa-plus-square"></i>').attr('aria-label', Joomla.JText._('VRE_ARIA_ADD_ITEM_CART').replace(/%s/, itemFullName)))
							addButton.on('click', () => {
								vrOpenOverlay('vrnewitemoverlay', itemFullName, item.id, option.id, -1, 'upselling');
							});

							priceBox.append(addButton);

							body.append(priceBox);

							itemBox.append(body);

							upsellingContainer.append(itemBox);
						});
					});
				});
			}).catch((error) => {
				// unable to fetch the eligible items for upselling... immediately move to the checkout page
				document.location.href = '<?php echo preg_replace("/&amp;/", '&', $checkoutUrl); ?>';
			});
		}

		$(function() {
			$('.vr-modal-box').on('click', function(e) {
				// ignore outside click
				e.stopPropagation();
			});

			$('.vr-overlay').on('click', function() {
				// close overlay when the background is clicked
				$(this).find('[data-role="dismiss"]').trigger('click');
			});
		});
	})(jQuery);
</script>