<?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;

$foodLayout = new JLayoutFile('blocks.card');

/**
 * 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 "onDisplayViewConfigresGlobalFood". The event method
 * receives the view instance as argument.
 *
 * @since 1.9
 */
$forms = $this->onDisplayView('GlobalFood');

?>

<div class="config-fieldset">

	<!-- SETTINGS -->

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

	<div class="config-fieldset-body">
		
		<!-- CHOOSABLE MENUS - Checkbox -->

		<?php
		echo $this->formFactory->createField([
			'type'        => 'checkbox',
			'name'        => 'choosemenu',
			'checked'     => $params['choosemenu'],
			'label'       => JText::translate('VRMANAGECONFIG39'),
			'description' => JText::translate('VRMANAGECONFIG39_DESC'),
		]);
		?>

		<!-- DISHES ORDERING - Select -->

		<?php
		echo $this->formFactory->createField([
			'type'        => 'select',
			'name'        => 'orderfood',
			'value'       => $params['orderfood'],
			'class'       => 'medium',
			'label'       => JText::translate('VRMANAGECONFIG94'),
			'description' => JText::translate('VRMANAGECONFIG94_HELP'),
			'options'     => [
				JHtml::fetch('select.option', 0, JText::translate('VRTKCONFIGOVERLAYOPT0')),
				JHtml::fetch('select.option', 1, JText::translate('VROPTIONATREST')),
				JHtml::fetch('select.option', 2, JText::translate('VRTKCONFIGOVERLAYOPT2')),
			],
		]);
		?>

		<!-- EDIT FOOD - Checkbox -->

		<?php
		echo $this->formFactory->createField([
			'type'        => 'checkbox',
			'name'        => 'editfood',
			'checked'     => $params['editfood'],
			'label'       => JText::translate('VRMANAGECONFIG95'),
			'description' => JText::translate('VRMANAGECONFIG95_HELP'),
			'control'     => [
				'class' => 'order-food-child',
				'style' => $params['orderfood'] ? '' : 'display: none;',
			],
		]);
		?>

		<!-- SERVING NUMBER - Checkbox -->

		<?php
		echo $this->formFactory->createField([
			'type'        => 'checkbox',
			'name'        => 'servingnumber',
			'checked'     => $params['servingnumber'],
			'label'       => JText::translate('VRMANAGECONFIG98'),
			'description' => JText::translate('VRMANAGECONFIG98_HELP'),
			'control'     => [
				'class' => 'order-food-child',
				'style' => $params['orderfood'] ? '' : 'display: none;',
			],
		]);
		?>

		<!-- CLOSE BILL - Checkbox -->

		<?php
		echo $this->formFactory->createField([
			'type'        => 'checkbox',
			'name'        => 'canclosebill',
			'checked'     => $params['canclosebill'],
			'label'       => JText::translate('VRMANAGECONFIG99'),
			'description' => JText::translate('VRMANAGECONFIG99_HELP'),
			'control'     => [
				'class' => 'order-food-child',
				'style' => $params['orderfood'] ? '' : 'display: none;',
			],
		]);
		?>

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

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

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

	</div>

</div>

<div class="config-fieldset">

	<!-- BILL -->

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

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

		<?php
		echo $this->formFactory->createField([
			'type'        => 'alert',
			'style'       => 'info',
			'hiddenLabel' => true,
			'text'        => JText::translate('VRE_BILL_FOOD_ITEM_AUTO_DESC'),
		]);
		?>

		<div class="vre-cards-container cards-food-items" id="cards-food-items">

			<?php
			$foodItems = (array) (!empty($params['bill_items_auto']) ? json_decode($params['bill_items_auto'], true) : []);

			foreach ($foodItems as $i => $item): ?>
				<div class="vre-card-fieldset up-to-3" id="food-item-fieldset-<?php echo (int) $i; ?>">

					<?php
					$displayData = [];

					// fetch primary text
					$displayData['primary'] = $item['name'];

					if (!$item['units'])
					{
						$units = JText::translate('VRPEOPLEALLOPT3');
					}
					else
					{
						$units = 'x' . $item['units'];
					}
				
					// fetch secondary text
					$displayData['secondary'] = '<span class="badge badge-info">' . $units . '</span>';

					// fetch edit button
					$displayData['edit'] = 'vreOpenFoodItemCard(\'' . $i . '\');';

					// render layout
					echo $foodLayout->render($displayData);
					?>
					
					<input type="hidden" name="bill_items_auto[]" value="<?php echo $this->escape(json_encode($item)); ?>" />

				</div>
			<?php endforeach; ?>

			<!-- ADD PLACEHOLDER -->

			<div class="vre-card-fieldset up-to-3 add add-food-item">
				<div class="vre-card compress">
					<i class="fas fa-plus"></i>
				</div>
			</div>

		</div>

		<div style="display:none;" id="food-item-struct">
	
			<?php
			// create food item structure for new items
			$displayData = array();
			$displayData['class']     = '';
			$displayData['primary']   = '';
			$displayData['secondary'] = '';
			$displayData['edit']      = true;

			echo $foodLayout->render($displayData);
			?>

		</div>

	</div>

</div>

<?php
$footer  = '<button type="button" class="btn btn-success" data-role="save">' . JText::translate('JAPPLY') . '</button>';
$footer .= '<button type="button" class="btn btn-danger" data-role="delete" style="float:right;">' . JText::translate('VRDELETE') . '</button>';

// render inspector to manage food item
echo JHtml::fetch(
	'vrehtml.inspector.render',
	'food-items-inspector',
	[
		'title'       => JText::translate('VRMANAGETKRES16'),
		'closeButton' => true,
		'keyboard'    => true,
		'footer'      => $footer,
		'width'       => 400,
	],
	$this->loadTemplate('global_food_modal')
);

JText::script('VRPEOPLEALLOPT3');
?>

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

<?php
/**
 * Iterate remaining forms to be displayed as new fieldsets
 * within the Global > Food tab.
 *
 * @since 1.9
 */
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
}
?>

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

		$(function() {
			$('select[name="orderfood"]').on('change', function() {
				if ($(this).val() != 0) {
					$('.order-food-child').show();
				} else {
					$('.order-food-child').hide();
				}
			});
		})

		let FOOD_ITEMS_COUNT   = <?php echo count($foodItems); ?>;
		let SELECTED_FOOD_ITEM = null;

		$(function() {
			// open inspector for new food items
			$('.vre-card-fieldset.add-food-item').on('click', () => {
				vreOpenFoodItemCard();
			});

			// fill the form before showing the inspector
			$('#food-items-inspector').on('inspector.show', () => {
				let json = [];

				// fetch JSON data
				if (SELECTED_FOOD_ITEM) {
					const fieldset = $('#' + SELECTED_FOOD_ITEM);

					json = fieldset.find('input[name="bill_items_auto[]"]').val();

					try {
						json = JSON.parse(json);
					} catch (err) {
						json = {};
					}
				}

				if (json.id === undefined) {
					// creating new record, hide delete button
					$('#food-items-inspector [data-role="delete"]').hide();
				} else {
					// editing existing record, show delete button
					$('#food-items-inspector [data-role="delete"]').show();
				}

				fillFoodItemForm(json);
			});

			// apply the changes
			$('#food-items-inspector').on('inspector.save', function() {
				// validate form
				if (!foodItemsValidator.validate()) {
					return false;
				}

				// get saved record
				let data = getFoodItemData();

				let fieldset;

				if (SELECTED_FOOD_ITEM) {
					fieldset = $('#' + SELECTED_FOOD_ITEM);
				} else {
					fieldset = vreAddFoodItemCard(data);
				}

				if (fieldset.length == 0) {
					// an error occurred, abort
					return false;
				}

				// save JSON data
				fieldset.find('input[name="bill_items_auto[]"]').val(JSON.stringify(data));

				// refresh card details
				vreRefreshFoodItemCard(fieldset, data);

				// auto-close on save
				$(this).inspector('dismiss');
			});

			// delete the record
			$('#food-items-inspector').on('inspector.delete', function() {
				const fieldset = $('#' + SELECTED_FOOD_ITEM);

				// auto delete fieldset
				fieldset.remove();

				// auto-close on delete
				$(this).inspector('dismiss');
			});
		});

		w.vreOpenFoodItemCard = (index) => {
			if (typeof index !== 'undefined') {
				SELECTED_FOOD_ITEM = 'food-item-fieldset-' + index;
			} else {
				SELECTED_FOOD_ITEM = null;
			}

			// open inspector
			vreOpenInspector('food-items-inspector');
		}

		const vreAddFoodItemCard = (data) => {
			let index = FOOD_ITEMS_COUNT++;

			SELECTED_FOOD_ITEM = 'food-item-fieldset-' + index;

			let html = $('#food-item-struct').clone().html();

			html = html.replace(/{id}/, index);

			$(
				'<div class="vre-card-fieldset" id="food-item-fieldset-' + index + '">' + html + '</div>'
			).insertBefore($('.vre-card-fieldset.add-food-item').last());

			// get created fieldset
			let fieldset = $('#' + SELECTED_FOOD_ITEM);

			fieldset.vrecard('edit', 'vreOpenFoodItemCard(' + index + ')');

			// create input to hold JSON data
			let input = $('<input type="hidden" name="bill_items_auto[]" />').val(JSON.stringify(data));

			// append input to fieldset
			fieldset.append(input);

			return fieldset;
		}

		const vreRefreshFoodItemCard = (elem, data) => {
			// update primary text
			elem.vrecard('primary', data.name);

			// append units label
			let secondary = $('<span class="badge badge-info"></span>').text(data.units ? 'x' + data.units : Joomla.JText._('VRPEOPLEALLOPT3'));

			// update secondary text
			elem.vrecard('secondary', secondary);
		}
	})(jQuery, window);
</script>