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

?>

<div class="inspector-form" id="inspector-food-item-form">

	<div class="inspector-fieldset">

		<!-- ITEM -->

		<?php
		$itemsDropdown = $this->formFactory->createField()
			->type('hidden')
			->id('auto-bill-food-item-sel')
			->required(true);

		// wrap hidden field into a control
		echo $this->formFactory->createField()
			->label(JText::translate('VRMANAGETKMENU3'))
			->control(['class' => 'auto-fill-food-add-only'])
			->required(true)
			->render(function($data, $input) use ($itemsDropdown) {
				echo $itemsDropdown;
			});

		echo $this->formFactory->createField()
			->type('text')
			->id('auto-bill-food-item-name')
			->label(JText::translate('VRMANAGETKMENU3'))
			->readonly(true)
			->control(['class' => 'auto-fill-food-edit-only']);
		?>

		<!-- PRICE -->

		<?php
		echo $this->formFactory->createField()
			->type('text')
			->id('auto-bill-food-item-price')
			->label(JText::translate('VRMANAGETKMENU5'))
			->readonly(true)
			->control(['class' => 'auto-fill-food-add-only'])
			->render(new E4J\VikRestaurants\Form\Renderers\InputGroupFieldRenderer([
				'before' => $this->params['currencysymb'],
			]));
		?>

		<!-- UNITS -->

		<?php
		echo $this->formFactory->createField()
			->type('select')
			->id('auto-bill-food-item-qty-mode')
			->label(JText::translate('VRMANAGETKDEAL18'))
			->options([
				'guests' => JText::translate('VRPEOPLEALLOPT3'),
				'as' => JText::translate('VRPEOPLEALLOPT2'),
			]);

		echo $this->formFactory->createField()
			->type('number')
			->id('auto-bill-food-item-qty-units')
			->hiddenLabel(true)
			->min(1)
			->step(1)
			->control([
				'class' => 'auto-bill-food-item-qty-mode-child qty-mode-as',
			]);
		?>

	</div>

	<input type="hidden" id="auto-bill-food-item-id" value="0" />
	<input type="hidden" id="auto-bill-food-item-id-var" value="0" />

</div>

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

		w.fillFoodItemForm = (data) => {
			w.foodItemsValidator.unsetInvalid($('#auto-bill-food-item-sel'));

			if (data.id) {
				// edit
				w.foodItemsValidator.unregisterFields($('#auto-bill-food-item-sel'));
				$('.auto-fill-food-add-only').hide();
				$('.auto-fill-food-edit-only').show();
				$('#auto-bill-food-item-name').val(data.name || '');
			} else {
				// add
				w.foodItemsValidator.registerFields($('#auto-bill-food-item-sel'));
				$('.auto-fill-food-edit-only').hide();
				$('.auto-fill-food-add-only').show();
				$('#auto-bill-food-item-sel').select2('val', null).trigger('change');
			}

			if (typeof data.units === 'undefined') {
				data.units = 0;
			} else {
				data.units = parseInt(data.units);
			}

			// set quantity
			$('#auto-bill-food-item-qty-mode').select2('val', data.units ? 'as' : 'guests').trigger('change');
			$('#auto-bill-food-item-qty-units').val(Math.max(1, data.units));

			// fulfill primary keys
			$('#auto-bill-food-item-id').val(data.id || 0);
			$('#auto-bill-food-item-id-var').val(data.idVar || 0);
		}

		w.getFoodItemData = () => {
			let data = {};

			// fetch primary keys
			data.id = parseInt($('#auto-bill-food-item-id').val());
			data.idVar = parseInt($('#auto-bill-food-item-id-var').val());

			// fetch item name
			data.name = $('#auto-bill-food-item-name').val();

			// fetch units
			const qtyMode = $('#auto-bill-food-item-qty-mode').select2('val');

			if (qtyMode === 'as') {
				data.units = parseInt($('#auto-bill-food-item-qty-units').val());
			} else {
				// equal to guests
				data.units = 0;
			}

			return data;
		}

		$(function() {
			w.foodItemsValidator = new VikFormValidator('#inspector-food-item-form');

			$('#auto-bill-food-item-sel').select2({
				placeholder: '--',
				allowClear: true,
				width: '100%',
				minimumInputLength: 2,
				ajax: {
					url: '<?php echo VREFactory::getPlatform()->getUri()->ajax('index.php?option=com_vikrestaurants&task=menusproduct.search'); ?>',
					dataType: 'json',
					type: 'POST',
					quietMillis: 50,
					data: (term) => {
						return {
							term: term,
						};
					},
					results: (data) => {
						return {
							results: $.map(data, (item) => {
								const data = {
									id: [item.id, item.option_id].filter(s => s).join('-'),
									text: item.text,
									idProd: item.id,
									idVar: parseInt(item.option_id) || 0,
									price: item.totalPrice,
								};
								
								// disable option in case it has been already added
								data.disabled = $('input[name="bill_items_auto[]"]')
									.map((i,f) => JSON.parse($(f).val())).toArray()
									.some(needle => needle.id == data.idProd && needle.idVar == data.idVar);
								
								return data;
							}),
						};
					},
				},
				formatSelection: (data) => {
					return data.text;
				},
			}).on('change', function() {
				const item = $(this).select2('data') || {};
				$('#auto-bill-food-item-name').val(item.text || '');
				$('#auto-bill-food-item-price').val(item.price || '');
				$('#auto-bill-food-item-id').val(item.idProd || 0);
				$('#auto-bill-food-item-id-var').val(item.idVar || 0);
			});

			$('#auto-bill-food-item-qty-mode').select2({
				minimumResultsForSearch: -1,
				allowClear: false,
				width: '100%',
			}).on('change', function() {
				const qtyMode = $(this).select2('val');

				$('.auto-bill-food-item-qty-mode-child').hide();
				$('.auto-bill-food-item-qty-mode-child.qty-mode-' + qtyMode).show();
			});

			onInstanceReady(() => {
				return w.configObserver;
			}).then(() => {
				// exclude fields under bill item inspector
            	w.configObserver.exclude('#inspector-food-item-form input')
            		.exclude('#inspector-food-item-form select');
			});
		});
	})(jQuery, window);
</script>