<?php
/** 
 * @package     VikAppointments
 * @subpackage  core
 * @author      E4J s.r.l.
 * @copyright   Copyright (C) 2021 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!');

$order = $this->order;

$currency = VAPFactory::getCurrency();

$dispatcher = VAPFactory::getEventDispatcher();

$forms = array();

foreach (array('before', 'top', 'actions', 'order', 'payment', 'fields', 'bottom', 'after') as $location)
{
	/**
	 * Trigger event to let the plugins add custom HTML contents within the order details box.
	 *
	 * @param 	string  $location  The HTML will be always placed after the specified location.
	 * @param 	object  $order     The object holding the order details.
	 *
	 * @return 	string  The HTML to display.
	 *
	 * @since 	1.7
	 */
	$html = array_filter($dispatcher->trigger('onDisplayOrderDetails', array($location, $order)));

	// display all returned blocks, separated by a new line
	$forms[$location] = implode("\n", $html);
}

?>

<!-- Define role to detect the supported hook -->
<!-- {"rule":"customizer","event":"onDisplayOrderDetails","type":"sitepage","key":"before"} -->

<?php
// display custom HTML before the summary block
echo $forms['before'];
?>

<div class="vaporderboxcontent">

	<!-- BOX TITLE -->
				
	<div class="vap-order-first">

		<h3 class="vaporderheader vap-head-first"><?php echo JText::translate('VAPORDERTITLE1'); ?></h3>

		<?php
		// check whether the customer is allowed to print the orders
		if (VAPFactory::getConfig()->getBool('printorders'))
		{
			?>
			<div class="vap-printable">
				<a 
					href="<?php echo JRoute::rewrite('index.php?option=com_vikappointments&task=order.doprint&id=' . $order->id . '&sid=' . $order->sid . '&tmpl=component' . ($this->itemid ? '&Itemid=' . $this->itemid : '')); ?>" 
					target="_blank"
					title="<?php echo $this->escape(JText::translate('VAPORDERPRINTACT')); ?>"
				>
					<i class="fas fa-print"></i>
				</a>
			</div>
			<?php
		}

		// check whether we should display the link to download the invoice
		if ($order->invoice)
		{
			?>
			<div class="vap-printable">
				<a
					href="<?php echo $order->invoice->uri; ?>"
					target="_blank"
					title="<?php echo $this->escape(JText::translate('VAPORDERINVOICEACT')); ?>"
				>
					<i class="fas fa-file-pdf"></i>
				</a>
			</div>
			<?php
		}
		?>

		<!-- Define role to detect the supported hook -->
		<!-- {"rule":"customizer","event":"onDisplayOrderDetails","type":"sitepage","key":"actions"} -->

		<?php
		// display custom HTML within the actions toolbar
		echo $forms['actions'];
		?>

	</div>

	<!-- LEFT SIDE -->

	<div class="vaporderboxleft">

		<div class="vapordercontentinfo">

			<!-- Define role to detect the supported hook -->
			<!-- {"rule":"customizer","event":"onDisplayOrderDetails","type":"sitepage","key":"top"} -->

			<?php
			// display custom HTML at the beginning of the order details
			echo $forms['top'];
			?>

			<div class="vaporderinfo">
				<span class="vaporderinfo-lbl"><?php echo JText::translate('VAPORDERNUMBER'); ?></span>
				<span class="vaporderinfo-value"><?php echo $order->id; ?></span>
			</div>

			<div class="vaporderinfo">
				<span class="vaporderinfo-lbl"><?php echo JText::translate('VAPORDERKEY'); ?></span>
				<span class="vaporderinfo-value"><?php echo $order->sid; ?></span>
			</div>

			<div class="vaporderinfo">
				<span class="vaporderinfo-lbl"><?php echo JText::translate('VAPORDERSTATUS'); ?></span>
				<span class="vaporderinfo-value">
					<?php
					echo JHtml::fetch('vaphtml.status.display', $order->status);

					/**
					 * Check whether the user is able to self-confirm the appointment.
					 * 
					 * @since 1.7.1
					 */
					if (VikAppointments::canUserApproveOrder($order))
					{
						// display a tooltip to inform the user that the appointment should
						// be confirmed by clicking the apposite link received via e-mail
						JHtml::fetch('bootstrap.tooltip', '.status-help');

						?>
						<i class="fas fa-question-circle status-help" title="<?php echo $this->escape(JText::translate('VAP_ORDER_APPROVE_HELP')); ?>"></i>
						<?php
					}
					?>
				</span>
			</div>

			<!-- Define role to detect the supported hook -->
			<!-- {"rule":"customizer","event":"onDisplayOrderDetails","type":"sitepage","key":"order"} -->

			<?php
			// display custom HTML within the order section, after the status
			echo $forms['order'];
			?>

			<br clear="all" />
				
			<?php
			if ($order->payment)
			{
				?>
				<div class="vaporderinfo">
					<span class="vaporderinfo-lbl"><?php echo JText::translate('VAPORDERPAYMENT'); ?></span>
					<span class="vaporderinfo-value">
						<?php
						echo $order->payment->name;

						if ($order->totals->payCharge > 0)
						{
							echo ' (' . $currency->format($order->totals->payCharge + $order->totals->payTax) . ')';
						}
						?>
					</span>
				</div>

				<?php
				if ($this->payment && $order->statusRole == 'PENDING')
				{
					?>
					<div class="vaporderinfo">
						<span class="vaporderinfo-lbl"><?php echo JText::translate('VAPORDERRESERVATIONCOST'); ?></span>
						<span class="vaporderinfo-value"><?php echo $currency->format($this->payment['total_to_pay']); ?></span>
					</div>
					<?php
				}
			}

			if ($order->totals->gross > 0)
			{
				?>
				<div class="vaporderinfo">
					<span class="vaporderinfo-lbl"><?php echo JText::translate('VAPORDERDEPOSIT'); ?></span>
					<span class="vaporderinfo-value">
						<?php
						echo $currency->format($order->totals->gross);

						if ($order->coupon)
						{
							// display the coupon code next to the total gross
							echo ' (' . $order->coupon->code . ')';
						}
						?>
					</span>
				</div>

				<?php
				if ($order->totals->paid > 0)
				{
					?>
					<div class="vaporderinfo">
						<span class="vaporderinfo-lbl"><?php echo JText::translate('VAPORDERTOTALPAID'); ?></span>
						<span class="vaporderinfo-value"><?php echo $currency->format($order->totals->paid); ?></span>
					</div>
					<?php
				}
			}
			?>

			<!-- Define role to detect the supported hook -->
			<!-- {"rule":"customizer","event":"onDisplayOrderDetails","type":"sitepage","key":"payment"} -->

			<?php
			// display custom HTML within the payment section
			echo $forms['payment'];
			?>

		</div>

		<?php
		/**
		 * In case of PENDING status, display a countdown to inform the users that they need
		 * to pay/confirm their appointments within the specified range of time.
		 *
		 * @since 1.7
		 * @since 1.7.9 In case of partially paid appointment, the countdown doesn't appear any longer.
		 */
		if ($order->statusRole == 'PENDING' && VAPFactory::getConfig()->getBool('showcountdown') && (float) $order->totals->paid == 0)
		{
			// the template will be shown only if explicitly enabled from the configuration
			echo $this->loadTemplate('countdown');
		}
		?>

		<!-- Define role to detect the supported hook -->
		<!-- {"rule":"customizer","event":"onDisplayOrderDetails","type":"sitepage","key":"bottom"} -->

		<?php
		// display custom HTML at the end of the order details
		echo $forms['bottom'];
		?>

	</div>

	<!-- RIGHT SIDE -->

	<div class="vaorderboxright" id="order-summary-custfields">
		<?php foreach ($order->displayFields as $key => $val): ?>
			<div class="vaporderinfo">
				<span class="vaporderinfo-lbl"><?php echo $key; ?></span>
				<span class="vaporderinfo-value"><?php echo nl2br($val); ?></span>
			</div>
		<?php endforeach; ?>

		<!-- Define role to detect the supported hook -->
		<!-- {"rule":"customizer","event":"onDisplayOrderDetails","type":"sitepage","key":"fields"} -->

		<?php
		// display custom HTML within the user fields section
		echo $forms['fields'];

		/**
		 * Check whether the customer is allowed to edit the custom fields.
		 * 
		 * @since 1.7.7
		 */
		if ($this->editableFields)
		{
			?>
			<br />
			<button type="button" class="vap-btn blue" id="edit-custfields-toggle"><?php echo JText::translate('VAPEDIT'); ?></button>
			<?php
		}
		?>
	</div>

	<?php if ($this->editableFields): ?>
		<div class="vaorderboxright" id="order-summary-custfields-edit" style="display: none;">
			<div class="vapcustomfields">
				<?php
				// render the custom fields form by using the apposite helper
				VAPLoader::import('libraries.customfields.renderer');
				echo VAPCustomFieldsRenderer::display($this->editableFields, array_merge((array) $order->fields, (array) $order->uploads));
				?>

				<div style="flex-basis: 100%;">
					<button type="button" class="vap-btn blue" id="edit-custfields-submit"><?php echo JText::translate('VAPSAVE'); ?></button>
					<button type="button" class="vap-btn" id="edit-custfields-cancel"><?php echo JText::translate('VAPCANCEL'); ?></button>
				</div>
			</div>
		</div>
	<?php endif; ?>

</div>

<!-- Define role to detect the supported hook -->
<!-- {"rule":"customizer","event":"onDisplayOrderDetails","type":"sitepage","key":"after"} -->

<?php
// display custom HTML after the summary block
echo $forms['after'];
?>

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

		$(function() {
			// create validator once the document is ready, because certain themes
			// might load the resources after the body
			const fieldsValidator = new VikFormValidator('#orderform', 'vapinvalid');

			// render dropdown elements with Select2 jQuery plugin
			$('.vapcustomfields .cf-value select').each(function() {
				let option = $(this).find('option').first();

				let data = {
					// hide search bar in case the number of options is lower than 10
					minimumResultsForSearch: $(this).find('option').length >= 10 ? 1 : -1,
					// allow clear selection in case the value of the first option is empty
					allowClear: option.val() ? false : true,
					// take the whole space
					width: '100%',
				};

				if (data.allowClear && !$(this).prop('multiple')) {
					// set placeholder by using the option text
					data.placeholder = option.text();

					// unset the text from the option for a correct rendering
					option.text('');
				}

				$(this).select2(data);
			});

			onInstanceReady(() => {
				return fieldsValidator;
			}).then((form) => {
				/**
				 * Overwrite getLabel method to properly access the
				 * label by using our custom layout.
				 *
				 * @param 	mixed  input  The input element.
				 *
				 * @param 	mixed  The label of the input.
				 */
				form.getLabel = (input) => {
					return $(input).closest('.cf-control').find('.cf-label *[id^="vapcf"]');
				}
			});

			$('#edit-custfields-toggle').on('click', () => {
				$('#order-summary-custfields').hide();
				$('#order-summary-custfields-edit').show();
			});

			$('#edit-custfields-cancel').on('click', () => {
				$('#order-summary-custfields-edit').hide();
				$('#order-summary-custfields').show();
			});

			$('#edit-custfields-submit').on('click', function() {
				if (!fieldsValidator.validate()) {
					return false;
				}

				$(this).prop('disabled', true);

				this.form.method = 'post';
				this.form.task.value = 'order.updatefields';
				$(this.form).submit();
			});
		});
	})(jQuery);
</script>