<?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!');

$params = $this->params;

$vik = VREApplication::getInstance();

/**
 * Trigger event to display custom HTML.
 * In case it is needed to include any additional fields,
 * it is possible to create a plugin and attach it to an event
 * called "onDisplayViewConfigtkGlobalUpselling". The event method
 * receives the view instance as argument.
 *
 * @since 1.11
 */
$forms = $this->onDisplayView('GlobalUpselling');

?>

<!-- SETTINGS -->

<div class="config-fieldset">

	<div class="config-fieldset-head">
		<h3><?php echo JText::translate('VRE_SETTINGS_FIELDSET'); ?></h3>
	</div>

	<div class="config-fieldset-body">
	
		<!-- ENABLE UPSELLING -->

		<?php
		echo $this->formFactory->createField()
			->type('checkbox')
			->name('enableupselling')
			->checked((bool) $params['enableupselling'])
			->label(JText::translate('VRMANAGECONFIGTK41'))
			->description(JText::translate('VRMANAGECONFIGTK41_DESC'))
			->onchange('upsellingValueChanged(this.checked)');
		?>

		<!-- TOP ITEMS -->

		<?php
		echo $this->formFactory->createField()
			->type('number')
			->name('upselling_topn')
			->value($params['upselling_topn'])
			->label(JText::translate('VRMANAGECONFIGTK42'))
			->description(JText::translate('VRMANAGECONFIGTK42_DESC'))
			->min(1)
			->step(1)
			->control([
				'visible' => (bool) $params['enableupselling'],
				'class' => 'upselling-child',
			]);
		?>

		<!-- TRAINING SINCE -->

		<?php
		echo $this->formFactory->createField()
			->type('date')
			->name('upselling_training_since')
			->value($params['upselling_training_since'])
			->label(JText::translate('VRMANAGECONFIGTK43'))
			->description(JText::translate('VRMANAGECONFIGTK43_DESC'))
			->control([
				'visible' => (bool) $params['enableupselling'],
				'class' => 'upselling-child',
			]);
		?>

		<!-- TRAINED UP TO DATE -->

		<?php
		echo $this->formFactory->createField()
			->type('html')
			->control([
				'visible' => (bool) $params['enableupselling'],
				'class' => 'upselling-child',
			])
			->html(
				empty($params['upselling_training_upto'])
				? JText::translate('VRMANAGECONFIGTK43_EMPTY')
				: JText::sprintf('VRMANAGECONFIGTK43_UPTO', strtolower(rtrim(JHtml::fetch('date.relative', $params['upselling_training_upto']), '.')))
			);
		?>

		<!-- SHOW/HIDE ADVANCED SETTINGS -->

		<?php
		echo $this->formFactory->createField()
			->type('button')
			->id('upselling-toggle-adv-settings')
			->text(JText::translate('VR_SHOW_ADVANCED_SETTINGS_BTN'))
			->class('btn-mini')
			->onclick('upsellingToggleAdvancedSettings()')
			->control([
				'visible' => (bool) $params['enableupselling'],
				'class' => 'upselling-child',
			]);
		?>

		<!-- Define role to detect the supported hook -->
		<!-- {"rule":"customizer","event":"onDisplayViewConfigtkGlobalUpselling","key":"basic","type":"field"} -->

		<?php   
		/**
		 * Look for any additional fields to be pushed within
		 * the Global > Upselling > Settings fieldset.
		 *
		 * @since 1.11
		 */
		if (isset($forms['basic']))
		{
			echo $forms['basic'];

			// unset details form to avoid displaying it twice
			unset($forms['basic']);
		}
		?>

	</div>

</div>

<!-- SCORE WEIGHTS SETTINGS -->

<?php
// decode upselling weights
$params['upselling_weights'] = (array) ($params['upselling_weights'] ? json_decode($params['upselling_weights'], true) : []);
?>

<div class="config-fieldset advanced-settings" style="display: none;">

	<div class="config-fieldset-head">
		<h3>Score Weights</h3>
	</div>

	<div class="config-fieldset-body">

		<!-- CONFIDENCE WEIGHT (ALPHA) -->

		<?php
		echo $this->formFactory->createField()
			->type('number')
			->name('upselling_weights[alpha]')
			->value($params['upselling_weights']['alpha'] ?? 0.5)
			->label('Confidence (α)')
			->description('Adjusts how much the likelihood of two products being ordered together affects the upselling score. Higher values give more weight to products that are frequently bought together.')
			->min(0)
			->max(2)
			->step('any')
			->class('restoreable')
			->setData('default', 0.5);
		?>

		<!-- LIFT WEIGHT (BETA) -->

		<?php
		echo $this->formFactory->createField()
			->type('number')
			->name('upselling_weights[beta]')
			->value($params['upselling_weights']['beta'] ?? 0.5)
			->label('Lift (β)')
			->description('Adjusts how much the strength of the product pairing compared to random chance affects the upselling score. Higher values favor suggesting product pairs that complement each other well.')
			->min(0)
			->max(2)
			->step('any')
			->class('restoreable')
			->setData('default', 0.5);
		?>

		<!-- PROMO BOOST WEIGHT (GAMMA) -->

		<?php
		echo $this->formFactory->createField()
			->type('number')
			->name('upselling_weights[gamma]')
			->value($params['upselling_weights']['gamma'] ?? 0.5)
			->label('Promotion (γ)')
			->description('Adjusts how much promotions boost the priority of suggested products. Higher values make promoted items more visible and favored in the recommendations.')
			->min(0)
			->max(2)
			->step('any')
			->class('restoreable')
			->setData('default', 0.5)
			->onchange('upsellingPromoBoostWeightValueChanged(this.value)');
		?>

		<!-- PROMO BOOST - FLAG WEIGHT (w1) -->

		<?php
		$promoWeightField = $this->formFactory->createField()
			->type('number')
			->name('upselling_weights[promo][w1]')
			->value($params['upselling_weights']['promo']['w1'] ?? 0.6)
			->hidden(true)
			->min(0)
			->max(2)
			->step('any')
			->class('restoreable')
			->setData('default', 0.6);

		$configurePromoButton = $this->formFactory->createField()
			->type('link')
			->text('Configure')
			->href('index.php?option=com_vikrestaurants&task=tkdeal.add&type=upsellingpromo')
			->target('_blank')
			->hidden(true);

		echo $this->formFactory->createField()
			->label('Active Promo (w1)')
			->description('Defines how much the presence of an active promotion (yes/no) affects the final score.')
			->control([
				'visible' => ($params['upselling_weights']['gamma'] ?? 0.5) > 0,
				'class' => 'upselling-gamma-w-child',
			])
			->render(function($data, $input) use ($promoWeightField, $configurePromoButton) {
				?>
				<div class="multi-field">
					<?php echo $promoWeightField; ?>
					<?php echo $configurePromoButton; ?>
				</div>
				<?php
			});
		?>

		<!-- PROMO BOOST - DISCOUNT WEIGHT (w2) -->

		<?php
		$discountWeightField = $this->formFactory->createField()
			->type('number')
			->name('upselling_weights[promo][w2]')
			->value($params['upselling_weights']['promo']['w2'] ?? 0.3)
			->hidden(true)
			->min(0)
			->max(2)
			->step('any')
			->class('restoreable')
			->setData('default', 0.3);

		$configureDiscountButton = $this->formFactory->createField()
			->type('link')
			->text('Configure')
			->href('index.php?option=com_vikrestaurants&task=tkdeal.add&type=discountitem')
			->target('_blank')
			->hidden(true);

		echo $this->formFactory->createField()
			->label('Discount Percentage (w2)')
			->description('Defines how much the product\'s discount percentage contributes to the score. Higher values give more importance to items with bigger discounts.')
			->control([
				'visible' => ($params['upselling_weights']['gamma'] ?? 0.5) > 0,
				'class' => 'upselling-gamma-w-child',
			])
			->render(function($data, $input) use ($discountWeightField, $configureDiscountButton) {
				?>
				<div class="multi-field">
					<?php echo $discountWeightField; ?>
					<?php echo $configureDiscountButton; ?>
				</div>
				<?php
			});
		?>

		<!-- PROMO BOOST - RECENCY WEIGHT (w3) -->

		<?php
		echo $this->formFactory->createField()
			->type('number')
			->name('upselling_weights[promo][w3]')
			->value($params['upselling_weights']['promo']['w3'] ?? 0.4)
			->label('Recency (w3)')
			->description('Defines how much the "freshness" of the promotion influences the score. Higher values give more visibility to recently published items.')
			->min(0)
			->max(2)
			->step('any')
			->class('restoreable')
			->setData('default', 0.4)
			->control([
				'visible' => ($params['upselling_weights']['gamma'] ?? 0.5) > 0,
				'class' => 'upselling-gamma-w-child',
			]);
		?>

		<!-- Define role to detect the supported hook -->
		<!-- {"rule":"customizer","event":"onDisplayViewConfigtkGlobalUpselling","key":"advanced","type":"field"} -->

		<?php   
		/**
		 * Look for any additional fields to be pushed within
		 * the Global > Upselling > Advanced fieldset.
		 *
		 * @since 1.11
		 */
		if (isset($forms['advanced']))
		{
			echo $forms['advanced'];

			// unset details form to avoid displaying it twice
			unset($forms['advanced']);
		}
		?>

		<!-- RESTORE FACTORY SETTINGS -->

		<?php
		echo $this->formFactory->createField()
			->type('button')
			->id('upselling-restore-factory-settings')
			->text(JText::translate('VRMAPGPRESTOREBUTTON'))
			->onclick('upsellingRestoreFactorySettings()');
		?>

	</div>

</div>

<!-- TEST -->

<div class="config-fieldset upselling-child" style="<?php echo ($params['enableupselling'] ? '' : 'display: none;'); ?>">

	<div class="config-fieldset-head">
		<h3><?php echo JText::translate('VRMANAGECONFIG31'); ?></h3>
	</div>

	<div class="config-fieldset-body">
	
		<!-- CART ITEMS -->

		<?php
		$itemsDropdown = $this->formFactory->createField()
			->type('hidden')
			->id('upselling-cart-items-sel');

		$searchButton = $this->formFactory->createField()
			->type('button')
			->text(JText::translate('VRMANAGECONFIG31'))
			->id('upselling-search-btn')
			->onclick('getUpsellingHints(this)')
			->hidden(true);

		// wrap hidden field into a control
		echo $this->formFactory->createField()
			->hiddenLabel(true)
			->description(JText::translate('VRMANAGECONFIGTK44_DESC'))
			->render(function($data, $input) use ($itemsDropdown, $searchButton) {
				?>
				<div class="multi-field">
					<?php echo $itemsDropdown; ?>
					<?php echo $searchButton; ?>
				</div>
				<?php
			});
		?>

		<div id="vr-customf-select-choose">
			
		</div>

		<div class="vre-cards-container cards-tkmenu-products" id="upselling-suggested-items">

		</div>

	</div>

</div>

<!-- Define role to detect the supported hook -->
<!-- {"rule":"customizer","event":"onDisplayViewConfigtkGlobalUpselling","type":"fieldset"} -->

<?php
/**
 * Iterate remaining forms to be displayed as new fieldsets
 * within the Global > Upselling tab.
 *
 * @since 1.11
 */
foreach ($forms as $formTitle => $formHtml)
{
	?>
	<div class="config-fieldset">
		
		<div class="config-fieldset-head">
			<h3><?php echo JText::translate($formTitle); ?></h3>
		</div>

		<div class="config-fieldset-body">
			<?php echo $formHtml; ?>
		</div>
		
	</div>
	<?php
}

JText::script('VR_SHOW_ADVANCED_SETTINGS_BTN');
JText::script('VR_HIDE_ADVANCED_SETTINGS_BTN');
JText::script('VRE_CUSTOMIZER_RESTORE_FACTORY_SETTINGS');
?>

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

		w.upsellingValueChanged = (checked) => {
			if (checked) {
				$('.upselling-child').show();
			} else {
				$('.upselling-child').hide();

				if ($('.config-fieldset.advanced-settings').is(':visible')) {
					upsellingToggleAdvancedSettings();
				}
			}
		}

		w.upsellingToggleAdvancedSettings = () => {
			const fieldset = $('.config-fieldset.advanced-settings');

			if (fieldset.is(':visible')) {
				fieldset.hide();
				$('#upselling-toggle-adv-settings').text(Joomla.JText._('VR_SHOW_ADVANCED_SETTINGS_BTN'));
			} else {
				fieldset.show();
				$('#upselling-toggle-adv-settings').text(Joomla.JText._('VR_HIDE_ADVANCED_SETTINGS_BTN'));
			}
		}

		w.upsellingPromoBoostWeightValueChanged = (value) => {
			if (parseFloat(value) > 0) {
				$('.upselling-gamma-w-child').show();
			} else {
				$('.upselling-gamma-w-child').hide();
			}
		}

		w.upsellingRestoreFactorySettings = () => {
			// ask for a confirmation before to proceed
			const r = confirm(Joomla.JText._('VRE_CUSTOMIZER_RESTORE_FACTORY_SETTINGS'));

			if (!r) {
				return false;
			}

			$('.restoreable[data-default]').each(function() {
				const def = $(this).attr('data-default');

				if ($(this).is('select')) {
					$(this).select2('val', def);
				} else {
					$(this).val(def);
				}
			});
		}

		w.getUpsellingHints = (button) => {
			if ($(button).prop('disabled')) {
				return false;
			}

			$(button).prop('disabled', true);
			let prevText = $(button).text();
			$(button).html('<i class="fas fa-spinner fa-spin"></i>');

			let items = [];

			$('#vr-customf-select-choose').find('input[data-id]').each(function() {
				items.push(parseInt($(this).attr('data-id')));
			});

			const container = $('#upselling-suggested-items').html('');

			UIAjax.do(
				'<?php echo VREFactory::getPlatform()->getUri()->ajax('index.php?option=com_vikrestaurants&task=configtk.upsell'); ?>',
				{
					items: items,
					options: {
						topn: $('input[name="upselling_topn"]').val(),
						since: $('input[name="upselling_training_since"]').val(),
						weights: {
							alpha: $('input[name="upselling_weights[alpha]"]').val(),
							beta: $('input[name="upselling_weights[beta]"]').val(),
							gamma: $('input[name="upselling_weights[gamma]"]').val(),
							promo: {
								w1: $('input[name="upselling_weights[promo][w1]"]').val(),
								w2: $('input[name="upselling_weights[promo][w2]"]').val(),
								w3: $('input[name="upselling_weights[promo][w3]"]').val(),
							},
						},
					},
				},
				(data) => {
					container.html(data.html);
					container.find('.hasTooltip').tooltip();

					$('html,body').animate({
						scrollTop: container.offset().top - 20,
					});

					$(button).prop('disabled', false).text(prevText);
				},
				(err) => {
					$(button).prop('disabled', false).text(prevText);

					setTimeout(() => {
						alert(err.responseText || err.statusText || 'Connection lost!');
					}, 32)
				}
			);
		}

		$(function() {
			$('#upselling-cart-items-sel').select2({
				placeholder: '--',
				allowClear: true,
				width: '100%',
				minimumInputLength: 2,
				ajax: {
					url: '<?php echo VREFactory::getPlatform()->getUri()->ajax('index.php?option=com_vikrestaurants&task=tkentry.search'); ?>',
					dataType: 'json',
					type: 'POST',
					quietMillis: 50,
					data: (term) => {
						return {
							term: term,
						};
					},
					results: (data) => {
						return {
							results: $.map(data, (item) => {
								return {
									text: item.text,
									id: item.id,
									disabled: $('#vr-customf-select-choose').find('input[data-id="' + item.id + '"]').length > 0,
								};
							}),
						};
					},
				},
				formatSelection: (data) => {
					return data.text;
				},
			}).on('change', function() {
				const item = $(this).select2('data');
				$(this).select2('val', null);

				const row = $('<div class="vr-customf-choose input-prepend input-append"></div>');
				row.append($('<input type="text" readonly />').val(item.text).attr('data-id', item.id));

				const delButton = $('<button type="button" class="btn"><i class="fas fa-trash"></i></button>');
				delButton.on('click', () => { 
					// remove row
					row.remove();
					// clear suggestions box as soon as we remove something from the cart
					$('#upselling-suggested-items').html('');
				});

				row.append(delButton);

				// clear suggestions box as soon as we add something into the cart
				$('#upselling-suggested-items').html('');

				$('#vr-customf-select-choose').append(row).trigger('select.option.add');
			});
		});
	})(jQuery, window);
</script>
