<?php
/**
 * HBFWC Template
 *
 * Functions for the templating system.
 *
 * @package  HBFWC\Functions
 * @version  1.0.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * Filter button text.
 *
 * @return string
 */
function hbfwc_filter_button_text() {
	return apply_filters( 'hbfwc_filter_button_text', __( 'Find Room', 'hotel-booking-for-woocommerce' ) );
}

if ( ! function_exists( 'hbfwc_template_shortcode_wrapper' ) ) {

	/**
	 * Output the start of the shortcode wrapper.
	 *
	 * @param array $query_args The query args.
	 */
	function hbfwc_template_shortcode_wrapper( $query_args ) {
		wc_get_template(
			'hbfwc/availability-wrapper-start.php',
			array(
				'query_args' => $query_args,
			)
		);
	}
}

if ( ! function_exists( 'hbfwc_template_shortcode_wrapper_end' ) ) {

	/**
	 * Output the end of the shortcode wrapper.
	 */
	function hbfwc_template_shortcode_wrapper_end() {
		wc_get_template( 'hbfwc/availability-wrapper-end.php' );
	}
}

if ( ! function_exists( 'hbfwc_template_availability_filter_form' ) ) {

	/**
	 * Output vailability check filter form.
	 *
	 * @param array $query_args The query args.
	 */
	function hbfwc_template_availability_filter_form( $query_args ) {
		wc_get_template(
			'hbfwc/availability-filter-form.php',
			array(
				'query_args' => $query_args,
			)
		);
	}
}

if ( ! function_exists( 'hbfwc_template_availability_loop_not_found' ) ) {

	/**
	 * Output not found message.
	 */
	function hbfwc_template_availability_loop_not_found() {
		wc_get_template( 'hbfwc/not-found.php' );
	}
}

if ( ! function_exists( 'hbfwc_template_availability_loop_content' ) ) {

	/**
	 * Output the item loop.
	 *
	 * @param int   $product_id The product ID.
	 * @param array $query_args The query args.
	 */
	function hbfwc_template_availability_loop_content( $product_id, $query_args ) {
		$product            = wc_get_product( absint( $product_id ) );
		$GLOBALS['product'] = $product;

		wc_get_template(
			'hbfwc/availability-loop.php',
			array(
				'query_args' => $query_args,
			)
		);
	}
}

if ( ! function_exists( 'hbfwc_template_availability_get_cart' ) ) {

	/**
	 * Output the mini cart
	 */
	function hbfwc_template_availability_get_cart() {
		wc_get_template( 'hbfwc/availability-cart.php' );
	}
}

if ( ! function_exists( 'hbfwc_template_show_product_images' ) ) {

	/**
	 * Show product images.
	 */
	function hbfwc_template_show_product_images() {
		wc_get_template( 'hbfwc/product-gallery.php' );
	}
}

if ( ! function_exists( 'hbfwc_template_show_product_information' ) ) {

	/**
	 * Show product information.
	 */
	function hbfwc_template_show_product_information() {
		wc_get_template( 'hbfwc/product-information.php' );
	}
}

if ( ! function_exists( 'hbfwc_template_product_amenities_teaser' ) ) {

	/**
	 * Room amenities.
	 */
	function hbfwc_template_product_amenities_teaser() {
		wc_get_template( 'hbfwc/product-amenities-teaser.php' );
	}
}

if ( ! function_exists( 'hbfwc_template_product_amenities' ) ) {

	/**
	 * Room amenities.
	 */
	function hbfwc_template_product_amenities() {
		wc_get_template( 'hbfwc/product-amenities.php' );
	}
}

if ( ! function_exists( 'hbfwc_template_available_rates' ) ) {

	/**
	 * Show the active rates for a product.
	 *
	 * @param array $query_args The query args.
	 */
	function hbfwc_template_available_rates( $query_args ) {
		wc_get_template(
			'hbfwc/rates/active-rates.php',
			array(
				'query_args' => $query_args,
			)
		);
	}
}

if ( ! function_exists( 'hbfwc_template_ajax_mini_form' ) ) {

	/**
	 * Form to support add to cart ajax.
	 *
	 * @param int   $term_id The term ID.
	 * @param array $query_args The query args.
	 */
	function hbfwc_template_ajax_mini_form( $term_id, $query_args ) {
		wc_get_template(
			'hbfwc/rates/add-to-cart.php',
			array(
				'rate_id'    => $term_id,
				'query_args' => $query_args,
			)
		);
	}
}

if ( ! function_exists( 'hbfwc_template_mini_cart_total' ) ) {
	/**
	 * Output to view cart subtotal.
	 *
	 * @since 1.0.0
	 */
	function hbfwc_template_mini_cart_total() {
		echo '<strong>' . esc_html__( 'Total:', 'hotel-booking-for-woocommerce' ) . '</strong> ' . WC()->cart->get_cart_subtotal(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	}
}

if ( ! function_exists( 'hbfwc_template_mini_cart_button_view_cart' ) ) {

	/**
	 * View cart button.
	 */
	function hbfwc_template_mini_cart_button_view_cart() {
		echo '<a href="' . esc_url( wc_get_cart_url() ) . '" class="button wc-forward wp-element-button hbfwc-expand-cart">' . esc_html__( 'View cart', 'hotel-booking-for-woocommerce' ) . '</a>';
	}
}

if ( ! function_exists( 'hbfwc_template_mini_cart_proceed_to_checkout' ) ) {

	/**
	 * To checkout button.
	 */
	function hbfwc_template_mini_cart_proceed_to_checkout() {
		$wp_button_class = wc_wp_theme_get_element_class_name( 'button' ) ? ' ' . wc_wp_theme_get_element_class_name( 'button' ) : '';
		echo '<a href="' . esc_url( wc_get_checkout_url() ) . '" class="button checkout wc-forward wp-element-button ' . esc_attr( $wp_button_class ) . '">' . esc_html__( 'Book Now', 'hotel-booking-for-woocommerce' ) . '</a>';
	}
}

if ( ! function_exists( 'hbfwc_template_embed_product_popup' ) ) {

	/**
	 * Embed html for product pop-up.
	 */
	function hbfwc_template_embed_product_popup() {
		global $product;
		wc_get_template( 'hbfwc/product-popup.php' );
	}
}

if ( ! function_exists( 'hbfwc_template_product_popup_header' ) ) {

	/**
	 * Product popup header.
	 */
	function hbfwc_template_product_popup_header() {
		global $product;
		echo '<div class="hbfwc-product-popup__header">';
		echo '<h3>' . esc_html( $product->get_name() ) . ' <a href="' . esc_url( get_permalink( $product->get_id() ) ) . '" target="_blank" rel="noopener noreferrer" aria-label="' . esc_attr__( 'Open product in a new tab', 'hotel-booking-for-woocommerce' ) . '"><i class="fas fa-external-link-alt"></i></a></h3>';
		echo '<a class="hbfwc-product__popup-close" href="#">&times;</a>';
		echo '</div>';
	}
}

/**
 * Product description.
 */
function hbfwc_template_product_popup_description() {
	global $product;

	echo '<div class="hbfwc-product-popup__description">';
	echo wp_kses_post( $product->get_description() );
	echo '</div>';
}

/**
 * Loop start.
 */
function hbfwc_template_loop_start() {
	wc_get_template( 'hbfwc/availability-loop-start.php' );
}

/**
 * Loop mid.
 */
function hbfwc_template_loop_before_sidebar() {
	wc_get_template( 'hbfwc/availability-loop-mid.php' );
}

/**
 * Loop end.
 */
function hbfwc_template_loop_end() {
	wc_get_template( 'hbfwc/availability-loop-end.php' );
}

/**
 * Link to product details popup.
 */
function hbfwc_template_link_to_popup() {
	global $product;

	echo '<a href="' . esc_url( $product->get_permalink() ) . '" class="hbfwc-button__popup">' . esc_html__( 'Room details', 'hotel-booking-for-woocommerce' ) . '</a>';
}

/**
 * Link to rate details popup.
 *
 * @param int $rate_id The rate ID.
 * @return void
 */
function hbfwc_template_rate_link_to_popup( $rate_id ) {
	global $product;

	echo '<a href="' . esc_url( $product->get_permalink() ) . '" class="hbfwc-button__rate-popup" data-rate_id="' . esc_attr( $rate_id ) . '">' . esc_html__( 'Rate details', 'hotel-booking-for-woocommerce' ) . '</a>';
}

/**
 * Rate detils pop-up content.
 *
 * @param int $rate_id The rate ID.
 * @return void
 */
function hbfwc_template_rate_detail_html( $rate_id ) {
	$rate = get_term_by( 'term_id', $rate_id, 'rate_plan' );

	if ( $rate ) {
		?>
	<div class="hbfwc-rate__popup" id="hbfwc-rate-popup-<?php echo esc_attr( $rate->term_id ); ?>">
		<div class="hbfwc-rate__popup-wrapper">
			<div class="hbfwc-rate__popup-heading">
				<h3><?php print esc_html( $rate->name ); ?></h3>
				<a class="hbfwc-rate__popup-close" href="#">&times;</a>
			</div>
			<div class="hbfwc-rate__popup-content">
				<div class="hbfwc-rate__popup-content-inner">
					<?php hbfwc_template_show_rate_features( $rate->term_id ); ?>
					<div class="hbfwc-rate__popup-content-description">
						<?php
							echo wp_kses_post( wpautop( do_shortcode( $rate->description ) ) );
						?>
					</div>
				</div>
			</div>
		</div>
	</div>
		<?php
	}
}

/**
 * Call via hook.
 * Embed rate pop-up html.
 */
function hbfwc_template_embed_rates_popup_html() {
	global $post, $product;

	if ( ! hbfwc_is_page_post() ) {
		return;
	}

	$rates = hbfwc_get_rateplans();

	if ( $rates ) {
		foreach ( $rates as $rate ) {
			hbfwc_template_rate_detail_html( $rate->term_id );
		}
	}
}

/**
 * Get all attachment ids for gallery.
 *
 * @return array
 */
function hbfwc_get_all_attachment_ids() {
	global $product;
	$attachment_ids = $product->get_gallery_image_ids();

	if ( $product->get_image_id() ) {
		if ( empty( $attachment_ids ) ) {
			$attachment_ids = array( $product->get_image_id() );
		} else {
			$attachment_ids = array_values( $attachment_ids );
			array_unshift( $attachment_ids, $product->get_image_id() );

			$attachment_ids = array_unique( $attachment_ids );
		}
	}

	return $attachment_ids;
}

/**
 * Get HTML for a gallery image.
 *
 * @param int $attachment_id Attachment ID.
 *
 * @return string
 */
function hbfwc_get_gallery_image_html( $attachment_id ) {
	$full_src = wp_get_attachment_image_src( $attachment_id, 'full' );
	$image    = wp_get_attachment_image(
		$attachment_id,
		'woocommerce_single',
		false,
		array(
			'title'                   => _wp_specialchars( get_post_field( 'post_title', $attachment_id ), ENT_QUOTES, 'UTF-8', true ),
			'data-caption'            => _wp_specialchars( get_post_field( 'post_excerpt', $attachment_id ), ENT_QUOTES, 'UTF-8', true ),
			'data-src'                => esc_url( $full_src[0] ),
			'data-large_image'        => esc_url( $full_src[0] ),
			'data-large_image_width'  => esc_attr( $full_src[1] ),
			'data-large_image_height' => esc_attr( $full_src[2] ),
			'class'                   => '',
		)
	);

	return '<div class="hbfwc-product-gallery__image"><a href="' . esc_url( $full_src[0] ) . '">' . $image . '</a></div>';
}

/**
 * Embed a simple js template helper.
 */
function hbfwc_template_embed_js_template() {
	if ( ! empty( $GLOBALS['hbfwc-avail-form'] ) ) {
		print '<script type="text/template" id="hbfwc-children-age-slider-template">
		<div class="hhbfwc-children-age-slider" id="hhbfwc-children-age-slider__{{number}}">
			<span class="hhbfwc-children-age-slider__label">' . sprintf(
				/* translators: Number of children */
			esc_html__( 'Children #%s age', 'hotel-booking-for-woocommerce' ),
			'{{number}}'
		) . '</span>
			<span class="hhbfwc-children-age-slider__input">
				<input type="range" id="children_age_{{number}}" name="children_age[]" value="6" min="0" max="' . esc_attr( hbfwc_get_max_children_age() ) . '" step="1" oninput="this.nextElementSibling.innerHTML = this.value" />
				<label for="children_age_{{number}}">6</label>
			</span>
		</div>
		</script>' . "\n";
	}
}

/**
 * Get rate features.
 *
 * @param int  $rate_id The rate id.
 * @param bool $printout Wether to echo or return the value.
 * @return string
 */
function hbfwc_template_show_rate_features( $rate_id, $printout = true ) {
	$features = get_term_meta( $rate_id, 'features', true );
	$html     = '';
	if ( $features ) {
		$features = explode( ',', $features );
		$html    .= '<ul class="hbfwc-rate__feature-list">' . "\n";
		foreach ( $features as $feature ) {
			$html .= '<li><i class="ion-ios-checkmark-circle-outline"></i> ' . trim( $feature ) . '</li>' . "\n";
		}
		$html .= '</ul>' . "\n";
	}

	if ( $printout ) {
		echo wp_kses_post( $html );
	} else {
		return $html;
	}
}

/**
 * Custom mini cart.
 */
function hbfwc_mini_cart() {
	wc_get_template( 'hbfwc/cart/mini-cart.php' );
}

/**
 * Check if we run with PRO add-on in legacy version.
 *
 * @return bool
 */
function hbfwc_in_legacy_pro() {
	return defined( 'HBFWC_PRO_VERSION' ) && version_compare( HBFWC_PRO_VERSION, HBFWC_LEGACY_VER, '<' );
}

/**
 * Generate the cart key for internal purpose.
 *
 * @param array $args
 * @return string
 */
function hbfwc_generate_booking_cart_key( $args ) {
	$params = wp_parse_args(
		$args,
		[
			'room_id'       => 0,
			'rate_id'       => 0,
			'check_in'      => '',
			'check_out'     => '',
			'adults'        => 0,
			'children'      => 0,
			'children_ages' => [],
			'room_numbers'  => [],
		]
	);

	$parts = [];
	array_walk_recursive(
		$params,
		static function ( $value ) use ( &$parts ) {
			$value = strval( $value );
			if ( '' === $value ) {
				return;
			}

			$parts[] = $value;
		}
	);

	if ( hbfwc_in_legacy_pro() ) {
		$key = implode( '-', $parts );
	} else {
		$key = md5( wp_json_encode( $parts ) );
	}

	return apply_filters( 'hbfwc_generate_booking_cart_key', $key, $args );
}

/**
 * Check if the combination of product, rate & query args is part of item in the cart.
 *
 * @param object $product Product object.
 * @param int    $rate_id Rate ID.
 * @param array  $args The query args.
 *
 * @return mixed. Bool if not exists, array with cart key and quantity if exists.
 */
function hbfwc_item_in_cart( $product, $rate_id, $args ) {
	$cart_key_parts = array(
		'room_id'       => $product->get_id(),
		'rate_id'       => $rate_id,
		'check_in'      => $args['checkin'] ?? '',
		'check_out'     => $args['checkout'] ?? '',
		'adults'        => $args['adults'] ?? 0,
		'children'      => $args['children'] ?? 0,
		'children_ages' => $args['child_ages'] ?? [],
		'room_numbers'  => $args['room_numbers'] ?? [],
	);

	$cart_key_parts   = apply_filters( 'hbfwc_possible_cart_id', $cart_key_parts, $product->get_id(), $rate_id, $args );
	$possible_cart_id = hbfwc_generate_booking_cart_key( $cart_key_parts );

	$found = [];
	if ( ! is_null( WC()->cart ) && ! WC()->cart->is_empty() ) {
		foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
			if ( isset( $cart_item['_hbfwc_cart_id'] ) && $cart_item['_hbfwc_cart_id'] === $possible_cart_id ) {
				$found = array(
					'key' => $cart_item_key,
					'qty' => $cart_item['quantity'],
				);
				break;
			}
		}
	}

	return $found;
}

/**
 * Get the button label.
 *
 * @return string
 */
function hbfwc_get_addtocart_button_label() {
	$settings = get_option( 'woocommerce_hbfwc_settings', array() );
	return isset( $settings['addtocart_label'] ) ? $settings['addtocart_label'] : esc_html__( 'Book Your Stay Now', 'hotel-booking-for-woocommerce' );
}

/**
 * Get all active booking add-on.
 * @return array
 */
function hbfwc_get_available_booking_addon() {
	$all_addon_posts = get_posts( [
		'post_type'      => 'booking_addon',
		'post_status'    => 'publish',
		'numberposts'    => -1,
		'meta_query'     => [
			[
				'key'     => 'active',
				'value'   => 'yes',
				'compare' => '='
			]
		],
		'orderby'        => 'meta_value_num',
		'meta_key'       => 'priority',
		'order'          => 'ASC',
	] );
	return $all_addon_posts;
}

/**
 * Check whether the minimum stay should be shown or not.
 * @return bool
 */
function hbfwc_show_min_stay_info() {
	$show = true; // Default is show the min stay info.
	return apply_filters( 'hbfwc_show_min_stay_info', $show );
}
