<?php

namespace ThemeAtelier\EventfulForElementor\Frontend\Helpers;

if (! defined('ABSPATH')) exit; // Exit if accessed directly

/**
 * The file functions.
 *
 * @package    eventful-for-elementor
 * @subpackage eventful-for-elementor/src/Helpers
 *
 */

/**
 * Event views helper method.
 */
class EventfulForElementorFunctions
{
	/**
	 * WP Version compare
	 *
	 * @param  mixed $version_to_compare version compare.
	 * @param  mixed $operator operator.
	 * @return statement
	 */
	public static function wp_version_compare($version_to_compare, $operator = '>=')
	{
		if (empty($version_to_compare)) {
			return true;
		}
		global $wp_version;

		// Check if using WordPress version 3.7 or higher.
		return version_compare($wp_version, $version_to_compare, $operator);
	}

	/**
	 * Event title character limit.
	 *
	 * @param string  $efpe_title The post title.
	 * @param integer $limit_length The length for the title.
	 * @param string  $efpe_after_string The string after title.
	 * @return statement
	 */
	public static function limit_post_title($efpe_title, $limit_length, $efpe_after_string = '...')
	{
		return mb_strimwidth($efpe_title, 0, $limit_length, apply_filters('efpe_post_title_ellipsis', $efpe_after_string));
	}

	/**
	 * Tag name to full tag conversion.
	 *
	 * @param array $meta_tag Tag option.
	 * @return string
	 */
	public static function short_tag_to_html($meta_tag)
	{
		$exclude_tag_string = '';
		foreach ($meta_tag as $key => $value) {
			$exclude_tag_string .= '<' . $value . '>,';
		}
		return $exclude_tag_string;
	}

	/**
	 * Limit the the text.
	 *
	 * @param mixed  $text The text you want to limit.
	 * @param int    $limit The number of words to display.
	 * @param string $ellipsis The ellipsis at the end of the text.
	 * @return statement
	 */
	public static function efpe_limit_text($text, $limit, $ellipsis = '...')
	{
		$word_arr = explode(' ', $text);
		if (count($word_arr) > $limit) {
			$words = implode(' ', array_slice($word_arr, 0, $limit)) . $ellipsis;
			return $words;
		} else {
			return $text;
		}
	}

	/**
	 * Characters Limit of the text.
	 *
	 * @param mixed  $text The text you want to limit.
	 * @param int    $limit The number of words to display.
	 * @param string $ellipsis The ellipsis at the end of the text.
	 * @return statement
	 */
	public static function limit_content_chr($text, $limit, $ellipsis = '...')
	{
		$length = $limit;
		if (strlen($text) < $length + 10) {
			return $text; // don't cut if too short.
		}
		$visible = substr($text, 0, $length);
		return $visible . $ellipsis;
	}

	/**
	 * Allowed tags function of the Plugin.
	 *
	 * @since 2.0.0
	 * @return array allowed tags
	 */
	public static function allowed_tags()
	{
		$allowed_tags           = wp_kses_allowed_html('tribe_events');
		$allowed_tags['iframe'] = array(
			'src'             => array(),
			'height'          => array(),
			'width'           => array(),
			'frameborder'     => array(),
			'allowfullscreen' => array(),
			'title'           => array(),
			'alt'             => array(),
		);

		$allowed_tags['style'] = array();

		return $allowed_tags;
	}

	/**
	 * Content function.
	 *
	 * @param array  $efpe_settings Read more efpe_settings.
	 * @param  mixed  $post post.
	 * @return content
	 */
	public static function efpe_content($options, $post, $efpe_settings)
	{
		$efpe_content_length_type      = isset($efpe_settings['content_length_type']) ? $efpe_settings['content_length_type'] : $options['content_length_type'];
		$event_content_length          = isset($efpe_settings['content_limit']) ? $efpe_settings['content_limit'] : $options['content_limit'];
		$efpe_content_characters_limit = isset($efpe_settings['content_characters_limit']) ? $efpe_settings['content_characters_limit'] : $options['content_characters_limit'];
		$event_content_ellipsis        = isset($efpe_settings['content_ellipsis']) ? $efpe_settings['content_ellipsis'] : $options['content_ellipsis'];
		$efpe_strip_tags               = isset($efpe_settings['strip_tags']) ? $efpe_settings['strip_tags'] : $options['strip_tags'];
		$efpe_allow_tag_name           = isset($efpe_settings['allow_tag_name']) ? $efpe_settings['allow_tag_name'] : $options['allow_tag_name'];
		$content_type     		  = isset($efpe_settings['content_type']) ? $efpe_settings['content_type'] : $options['content_type'];
		$allowed_tags                 = isset($efpe_settings['allow_tag_name']) ?  explode(',', $efpe_allow_tag_name) : array();
		$is_page_content = false;
		$is_page_content = apply_filters('efpe_strip_shortcode_in_page_content', $is_page_content);
		global $wp_embed;
		if ('excerpt' === $content_type) {
			$efpe_event_content = "<p>'" . get_the_excerpt($post) . "'</p>";
		} elseif ('full_content' === $content_type) {
			if ($is_page_content) {
				$event_content = apply_filters('efpe_the_content', strip_shortcodes($post->post_content));
			} else {
				$event_content = apply_filters('efpe_the_content', $post->post_content);
			}
			if ('allow_some' === $efpe_strip_tags) {
				$efpe_event_content = strip_tags($event_content, self::short_tag_to_html($allowed_tags));
			} elseif ('strip_all' === $efpe_strip_tags) {
				$efpe_event_content = wp_strip_all_tags($event_content);
			} else {
				$efpe_event_content = $event_content;
			}
		} else {
			if ($is_page_content) {
				$event_content = apply_filters('efpe_the_content', strip_shortcodes($post->post_content));
			} else {
				$event_content = apply_filters('efpe_the_content', $post->post_content);
			}
			if ('characters' === $efpe_content_length_type) {
				$_trimmed_content = ('strip_all' === $efpe_strip_tags) ? wp_html_excerpt($event_content, $efpe_content_characters_limit, $event_content_ellipsis) : self::limit_content_chr($event_content, $efpe_content_characters_limit, $event_content_ellipsis);
			} else {
				$_trimmed_content = self::efpe_limit_text($event_content, $event_content_length, $event_content_ellipsis);
			}
			if ('allow_some' === $efpe_strip_tags) {
				$efpe_event_content = strip_tags($_trimmed_content, self::short_tag_to_html($allowed_tags));
			} elseif ('strip_all' === $efpe_strip_tags) {
				$efpe_event_content = wp_strip_all_tags($_trimmed_content);
			} else {
				$efpe_event_content = $_trimmed_content;
			}
			$efpe_event_content = force_balance_tags($efpe_event_content);
		}
		$efpe_event_content = do_shortcode($wp_embed->autoembed($efpe_event_content));
		return $efpe_event_content;
	}

	/**
	 * Get the ID by the Image URL.
	 *
	 * @param mixed $url The image url.
	 * @param int   $post_id The image url.
	 * @return statement
	 */
	public static function efpe_image_id_by_url($url, $post_id = null)
	{
		global $wpdb;

		// If the URL is auto-generated thumbnail, remove the sizes and get the URL of the original image.
		$url       = preg_replace('/-\d+x\d+(?=\.(png|jp(e|g|eg)|gif|bmp|ico|webp|svg)$)/i', '', $url);
		$cache_key = 'efpe_content_img_url_to_id' . $post_id;
		$img_cache = wp_cache_get($cache_key);
		if (false === $img_cache) {
			$image = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid=%s;", $url));
			wp_cache_set($cache_key, $img_cache);
		}
		if (!empty($image)) {
			return $image[0];
		}
		return false;
	}
	/**
	 * Thumb alter text
	 *
	 * @param integer $slide_id The slide/post ID.
	 *
	 * @return string
	 */
	public static function efpe_thumb_alter_text($slide_id)
	{
		$image_id = get_post_thumbnail_id($slide_id);
		$alt_text = get_post_meta($image_id, '_wp_attachment_image_alt', true);
		return $alt_text;
	}

	/**
	 * Modify query params
	 *
	 * @param  array  $query_args query_args.
	 * @param  string $keyword keyword.
	 * @param  int    $author_id author id.
	 * @param  array  $custom_fields_array custom fields array.
	 * @param  string $orderby orderby.
	 * @param  string $order order.
	 * @param  array  $selected_term_list term_list.
	 * @param  int    $event_offset offset.
	 * @param  string $relation relation operator.
	 * @param  array  $post_in post in.
	 * @param  string $lang current lang.
	 * @return array
	 */
	public static function modify_query_params($query_args, $keyword, $author_id, $custom_fields_array, $orderby, $order, $selected_term_list, $event_offset, $relation, $post_in = array(), $lang = '')
	{
		if (!empty($keyword)) {
			$query_args['s'] = $keyword;
			$event_offset     = 0;
		}
		if ('all' !== $author_id & !empty($author_id)) {
			$query_args['author__in'] = $author_id;
			$event_offset              = 0;
		}
		if (!empty($lang)) {
			$query_args['lang'] = $lang;
		}
		$query_args['post__in'] = $post_in;
		if (!empty($custom_fields_array)) {
			$efpe_meta_query = array();
			foreach ($custom_fields_array as $_custom_field) {
				$c_field_key   = $_custom_field['custom_field_key'];
				$c_field_value = $_custom_field['custom_field_value'];
				if (strpos($c_field_value, ' ') !== false) {
					$c_field_value    = explode(' ', $c_field_value);
					$efpe_meta_query[] = array(
						'key'     => $c_field_key,
						'value'   => $c_field_value,
						'compare' => 'BETWEEN',
						'type'    => 'numeric',
					);
				} else {
					if (strpos($c_field_value, ',') !== false) {
						$c_field_value = explode(',', $c_field_value);
					}
					$efpe_meta_query[] = array(
						'key'     => $c_field_key,
						'compare' => 'IN',
						'value'   => $c_field_value,
					);
				}
			}
			if (count($efpe_meta_query) > 1) {
				$efpe_meta_query['relation'] = 'AND';
			}
			$query_args['meta_query'] = $efpe_meta_query;
		}

		if (!empty($orderby)) {
			$query_args['orderby'] = ('rand' === $orderby) ? 'rand(' . get_transient('efpe_rand') . ')' : $orderby;
		}
		if (!empty($order)) {
			$query_args['order'] = $order;
		}
		if (!empty($selected_term_list)) {
			if (count($selected_term_list) > 1) {
				$tax_settings['relation'] = $relation;
			}
			if (is_array($selected_term_list)) {
				foreach ($selected_term_list as $key => $tax_type) {
					$taxonomy = $tax_type['taxonomy'];
					$terms    = $tax_type['term_id'];
					if (strpos($terms, ',') !== false) {
						$terms = explode(',', $terms);
					}
					if ($taxonomy && $terms) {
						$tax_settings[] = array(
							'taxonomy'         => $taxonomy,
							'field'            => 'term_id',
							'terms'            => $terms,
							'operator'         => 'IN',
							'include_children' => false,
						);
					}
				}
				$query_args['tax_query'] = $tax_settings;
			}
			$event_offset = 0;
		}
		$query_args['offset'] = $event_offset;
		return $query_args;
	}

	/**
	 * Thumb Sized function
	 *
	 * @param array   $options Thumbnails options array.
	 * @param integer $slide_id The slide/post ID.
	 * @param  bool    $is_attachment type attachment.
	 *
	 * @return string
	 */
	public static function efpe_sized_thumb($options, $slide_id, $efpe_settings)
	{
		$thumb_id                  = '';
		$image                     = '';
		$efpe_thumb_src_replace     = isset($efpe_settings['thumb_src_replace']) ? $efpe_settings['thumb_src_replace'] : $options['thumb_src_replace'];
		$post_featured_thumb_found = isset($options['featured_thumb_found']) ? $options['featured_thumb_found'] : 'no_featured_img_found';
		$show_2x_image             = isset($efpe_settings['load_2x_image']) ? $efpe_settings['load_2x_image'] : false;
		$image_resize_2x_url       = '';
		if ('even_featured_img_found' === $post_featured_thumb_found && is_array($efpe_thumb_src_replace)) {
			$replace_thumb = self::efpe_thumb_replace($options, $slide_id, $efpe_settings);
			$thumb_id      = $replace_thumb['id'];
		} elseif (!has_post_thumbnail($slide_id) && 'no_featured_img_found' === $post_featured_thumb_found) {
			$replace_thumb = self::efpe_thumb_replace($options, $slide_id, $efpe_settings);
			$thumb_id      = $replace_thumb['id'];
		} else {
			if (has_post_thumbnail($slide_id)) {
				$thumb_id = get_post_thumbnail_id($slide_id);
			}
		}

		$placeholder_img = EVENTFUL_ELEMENTOR_PLUGIN_URL . 'src/Frontend/assets/img/placeholder.png';
		$placeholder_img = apply_filters('efpe_no_thumb_placeholder', $placeholder_img);
		if (empty($thumb_id) && !empty($placeholder_img)) {
			$thumb_id = attachment_url_to_postid($placeholder_img);
		}

		if (!empty($thumb_id)) {
			$image_sizes  = isset($efpe_settings['post_thumbnail_size']) ? $efpe_settings['post_thumbnail_size'] : $options['post_thumbnail_size'];

			$image_dimension  = isset($efpe_settings['post_thumbnail_custom_dimension']) ? $efpe_settings['post_thumbnail_custom_dimension'] : $options['post_thumbnail_custom_dimension'];
			$post_image_width  = isset($image_dimension['width']) ? $image_dimension['width'] : '';
			$post_image_height = isset($image_dimension['height']) ? $image_dimension['height'] : '';
			
			$thumb_full_src    = wp_get_attachment_image_src($thumb_id, 'full');
			$thumb_full_src    = is_array($thumb_full_src) ? $thumb_full_src : array('', '', '');
			$image_src         = wp_get_attachment_image_src($thumb_id, $image_sizes);
			$image_src         = is_array($image_src) ? $image_src : array('', '', '');
			if (('custom' === $image_sizes) && (!empty($post_image_width) && $thumb_full_src[1] >= $post_image_width) && (!empty($post_image_height) && $thumb_full_src[2] >= $post_image_height)) {
				$hard_crop = true;
				$image = EventfulForElementorImageResizer::efpe_resize($thumb_full_src[0], $post_image_width, $post_image_height, $hard_crop);
				if ($show_2x_image && ($thumb_full_src[1] >= ($post_image_width * 2)) && $thumb_full_src[2] >= ($post_image_height * 2)) {
					$image_resize_2x_url = EventfulForElementorImageResizer::efpe_resize($thumb_full_src[0], $post_image_width * 2, $post_image_height * 2, $hard_crop);
				} elseif ($show_2x_image && (($post_image_width * 2) === $thumb_full_src[1]) && ($post_image_height * 2) === $thumb_full_src[2]) {
					$image_resize_2x_url = $thumb_full_src[0];
				}
				$image_width  = $post_image_width;
				$image_height = $post_image_height;
			} else {
				$image        = !empty($image_src[0]) ? $image_src[0] : $placeholder_img;
				$image_width  = !empty($image_src[1]) ? $image_src[1] : 600;
				$image_height = !empty($image_src[2]) ? $image_src[2] : 400;
			}
		} else {
			$image        = $placeholder_img;
			$image_width  = 600;
			$image_height = 400;
		}

		$efpe_image_attr = array(
			'src'        => $image,
			'2x_src'     => $image_resize_2x_url,
			'width'      => $image_width,
			'height'     => $image_height,
			'video'      => !empty($replace_thumb['video']) ? $replace_thumb['video'] : '',
			'audio'      => !empty($replace_thumb['audio']) ? $replace_thumb['audio'] : '',
			'aria_label' => !empty($replace_thumb['aria_label']) ? $replace_thumb['aria_label'] : 'feature_image',
		);

		return $efpe_image_attr;
	}

	/**
	 * Thumb Sized function
	 *
	 * @param array   $options Thumbnails options array.
	 * @param integer $slide_id The slide/post ID.
	 *
	 * @return string
	 */
	public static function efpe_thumb_replace($options, $slide_id, $efpe_settings)
	{
		$thumb_src_replace = isset($efpe_settings['thumb_src_replace']) ? $efpe_settings['thumb_src_replace'] : $options['thumb_src_replace'];

		if (is_array($thumb_src_replace)) {
			$image_src    = in_array('image', $thumb_src_replace, true) ? true : false;
			$video_src    = in_array('video', $thumb_src_replace, true) ? true : false;
			$audio_src    = in_array('audio', $thumb_src_replace, true) ? true : false;
			$content_post = get_post($slide_id);
			$content      = $content_post->post_content;

			$test          = preg_match_all(
				'((https?|ftp|gopher|telnet|file|notes|ms-help):' .
					'((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)',
				$content,
				$matches,
				PREG_PATTERN_ORDER
			);
			$first_content = 'image';

			if (!empty($matches[0][0])) {
				if (strpos($matches[0][0], '.jpg') || strpos($matches[0][0], '.jpeg') || strpos($matches[0][0], '.gif') || strpos($matches[0][0], '.png') || strpos($matches[0][0], '.eps')) {
					$first_content = 'image';
				}
				if (strpos($matches[0][0], 'video') || strpos($matches[0][0], 'youtube') || strpos($matches[0][0], 'vimeo') || strpos($matches[0][0], '.mp4')) {
					$first_content = 'video';
				}
				if (strpos($matches[0][0], 'audio') || strpos($matches[0][0], 'soundcloud')) {
					$first_content = 'audio';
				}
			}
			$image_id = 'image' === $first_content ? self::efpe_get_img_from_post($options, $slide_id) : '';
			$is_video = 'video' === $first_content ? self::efpe_get_video_from_post($slide_id) : '';
			$is_audio = 'audio' === $first_content ? self::efpe_get_audios_from_post($slide_id) : '';

			if ($image_src && $video_src && $audio_src) {
				$thumb_id    = $image_id;
				$video_thumb = $is_video;
				$audio_thumb = $is_audio;
			}
			if ($image_src && $video_src) {
				$thumb_id    = $image_id;
				$video_thumb = $is_video;
			}
			if ($image_src && $audio_src) {
				$thumb_id    = $image_id;
				$audio_thumb = $is_audio;
			}
			if ($audio_src && $video_src) {
				$video_thumb = $is_video;
				$audio_thumb = $is_audio;
			}
			if ($image_src) {
				$thumb_id = self::efpe_get_img_from_post($options, $slide_id);
			}
			if ($video_src && (empty($matches[1][0]) || !$image_src)) {
				$video_thumb = self::efpe_get_video_from_post($slide_id);
			}
			if ($audio_src && empty($video_thumb) && (empty($matches[1][0]) || !$image_src)) {
				$audio_thumb = self::efpe_get_audios_from_post($slide_id);
			}
		}
		$efpe_thumbs_replace_src = array(
			'id'         => !empty($thumb_id) ? $thumb_id : '',
			'video'      => !empty($video_thumb) ? $video_thumb : '',
			'audio'      => !empty($audio_thumb) ? $audio_thumb : '',
			'aria_label' => !empty($first_content) ? $first_content : '',
		);
		return $efpe_thumbs_replace_src;
	}

	/**
	 * Get first image from post content
	 *
	 * @since 1.0
	 * @param array  $options Thumbnails options array.
	 * @param  number $slide_id Event id.
	 * @return mixed
	 */
	public static function efpe_get_img_from_post($options, $slide_id)
	{
		$efpe_thumb_src = isset($options['efpe_thumb_src']) ? $options['efpe_thumb_src'] : 'featured_image';
		$content_post  = get_post($slide_id);
		$content       = $content_post->post_content;
		$images        = preg_match_all('/<img[^>]* src=\"([^\"]*)\"[^>]*>/i', $content, $matches);
		if ($images) {
			$img_url  = 'last_img_content' === $efpe_thumb_src ? array_values(array_slice($matches[1], -1)) : $matches[1][0];
			$thumb_id = self::efpe_image_id_by_url($img_url, $slide_id);
		}
		if (!empty($thumb_id)) {
			return $thumb_id;
		}
	}

	/**
	 * Get first video from post content
	 *
	 * @since 1.0
	 * @param  number $slide_id Event id.
	 * @return mixed
	 */
	public static function efpe_get_video_from_post($slide_id)
	{

		$post    = get_post($slide_id);
		$content = do_shortcode(apply_filters('the_content', $post->post_content));
		$embeds  = apply_filters('efpe_get_post_video', get_media_embedded_in_content($content));

		if (empty($embeds)) {
			return '';
		}

		// check what is the first embed containg video tag, youtube or vimeo.
		foreach ($embeds as $embed) {
			if (strpos($embed, 'video') || strpos($embed, 'youtube') || strpos($embed, 'vimeo') || strpos($embed, '.mp4')) {
				return $embed;
			}
		}
	}

	/**
	 * Get audio files from post content
	 *
	 * @param  number $slide_id Event id.
	 * @return mixed          Iframe.
	 */
	public static function efpe_get_audios_from_post($slide_id)
	{
		// For audio post type - grab.
		$post    = get_post($slide_id);
		$content = do_shortcode(apply_filters('efpe_the_content', $post->post_content));
		$embeds  = apply_filters('efpe_get_post_audio', get_media_embedded_in_content($content));
		if (empty($embeds)) {
			return '';
		}

		// check what is the first embed containg video tag, youtube or vimeo.
		foreach ($embeds as $embed) {
			if (strpos($embed, 'audio') || strpos($embed, 'soundcloud')) {
				return $embed;
			}
		}
	}

	/**
	 * Process all the event fildes.
	 *
	 * @param object $event The selected event.
	 * @param array  $event_fildes_fields The selected event fildes to show.
	 * @param int    $visitor_count Number of visitor saw the event.
	 * @param string $fildes_separator The event fildes separator.
	 * @param string $is_table the table layout check.
	 * @return void
	 */
	public static function efpe_get_event_fildes($post, $options, $efpe_settings, $scode_id, $is_table)
	{
		$event_meta_separator        = isset($efpe_settings['event_meta_separator']) ? $efpe_settings['event_meta_separator'] : $options['event_meta_separator'];
		$meta_wrapper_start_tag = !$is_table ? apply_filters('efpe_event_fildes_wrapper_start', '<ul>') : '';
		$meta_wrapper_end_tag   = !$is_table ? apply_filters('efpe_event_fildes_wrapper_end', '</ul>') : '';
		echo wp_kses_post($meta_wrapper_start_tag);


		$custom_css = "
		  #efpe_wrapper-{$scode_id} .eventful__item .eventful__item--meta.event_meta ul li:not(:last-child):after {
			position: absolute;
			right: 0;
			padding-right: 0px; 
			content: '{$event_meta_separator}';
		  }
		";

		wp_add_inline_style('eventful-main', wp_kses_post($custom_css));

		$meta_categories     = isset($efpe_settings['meta_categories']) ? $efpe_settings['meta_categories'] : $options['meta_categories'];
		$categories_icon   = isset($efpe_settings['categories_icon']) ? $efpe_settings['categories_icon'] : $options['categories_icon'];
		$categories_icon_value = isset($categories_icon['value']) ? $categories_icon['value'] : $options['value'];
		$categories_meta_icon      = '<i class="elementor-icons-manager__tab__item__icon ' . $categories_icon_value . '"></i>';

		$venue_phone_icon = isset($options['venue_phone_icon']) ? $options['venue_phone_icon'] : [];
		$event_price_icon = isset($options['event_price_icon']) ? $options['event_price_icon'] : [];
		$event_venue_icon = isset($options['event_venue_icon']) ? $options['event_venue_icon'] : [];

		$event_meta_data        = isset($efpe_settings['event_meta_data']) ? $efpe_settings['event_meta_data'] : $options['event_meta_data'];
		$venue_settings        = isset($efpe_settings['venue_settings']) ? $efpe_settings['venue_settings'] : $options['venue_settings'];

		$event_venue_icon        = isset($efpe_settings['event_venue_icon']) ? $efpe_settings['event_venue_icon'] : $event_venue_icon;
		$event_venue_icon_value        = isset($event_venue_icon['value']) ? $event_venue_icon['value'] : '';
		$venue_icon_value      = '<i class="elementor-icons-manager__tab__item__icon ' . $event_venue_icon_value . '"></i>';

		$event_organizer_icon        = isset($efpe_settings['event_organizer_icon']) ? $efpe_settings['event_organizer_icon'] : $options['event_organizer_icon'];
		$event_organizer_icon_value        = isset($event_organizer_icon['value']) ? $event_organizer_icon['value'] : '';
		$organizer_icon      = '<i class="elementor-icons-manager__tab__item__icon ' . $event_organizer_icon_value . '"></i>';

		$event_price_icon        = isset($efpe_settings['event_price_icon']) ? $efpe_settings['event_price_icon'] : $event_price_icon;
		$event_price_icon_value        = isset($event_price_icon['value']) ? $event_price_icon['value'] : '';
		$price_icon      = '<i class="elementor-icons-manager__tab__item__icon ' . $event_price_icon_value . '"></i>';

		$event_date_icon        = isset($efpe_settings['event_date_icon']) ? $efpe_settings['event_date_icon'] : $options['event_date_icon'];
		$event_date_icon_value        = isset($event_date_icon['value']) ? $event_date_icon['value'] : '';
		$date_icon      = '<i class="elementor-icons-manager__tab__item__icon ' . $event_date_icon_value . '"></i>';

		$venue_phone_icon        = isset($efpe_settings['venue_phone_icon']) ? $efpe_settings['venue_phone_icon'] : $venue_phone_icon;
		$venue_map_link        = isset($efpe_settings['venue_map_link']) ? $efpe_settings['venue_map_link'] : $options['venue_map_link'];
		$event_fildes_date_format     = isset($efpe_settings['event_fildes_date_format']) ? $efpe_settings['event_fildes_date_format'] : $options['event_fildes_date_format'];
		$event_fildes_date_type   = isset($efpe_settings['event_fildes_date_type']) ? $efpe_settings['event_fildes_date_type'] : $options['event_fildes_date_type'];
		$efpe_custom_event_date_format   = isset($efpe_settings['efpe_custom_event_date_format']) ? $efpe_settings['efpe_custom_event_date_format'] : $options['efpe_custom_event_date_format'];

		$start_tag      = '<li  class="event_meta_address">';
		$end_tag        = '</li>';
		$meta_tag_start = apply_filters('efpe_event_fildes_html_tag_start', $start_tag);
		$meta_tag_end   = apply_filters('efpe_event_fildes_html_tag_end', $end_tag);
		$allowed_html   = array(
			'a'    => array(
				'href'  => array(),
				'title' => array(),
			),
			'i'    => array(
				'class' => array(),
				'id'    => array(),
			),
			'span' => array(
				'class' => array(),
				'id'    => array(),
			),
			'div'  => array(
				'class' => array(),
				'id'    => array(),
			),
		);
		$i = 0;
		foreach ($event_meta_data as $meta_data) {
			switch ($meta_data) {
				case 'taxonomy':
					$term = self::efpe_taxonomy_terms($meta_categories, $post->ID, $categories_meta_icon);
						if (!empty($term)) {
							echo wp_kses_post($meta_tag_start);
							echo wp_kses_post($term);
							echo wp_kses_post($meta_tag_end);
						}
					break;
				case 'venue':
					if (tribe_get_venue($post->ID, true)) {
						echo wp_kses_post($meta_tag_start);
						foreach ($venue_settings as $venue_setting) {
							switch ($venue_setting) {
								case 'address':
									if ('svg' === $event_venue_icon['library']) {
										$event_meta_venue_icon     =  '<img alt=' . esc_html__('Image', 'eventful-for-elementor') . ' src="' . esc_url($event_venue_icon_value["url"]) . '" width="16" height="16" >';
									} else {
										$event_meta_venue_icon     = !empty($venue_icon_value) ? $venue_icon_value : '<i class="elementor-icons-manager__tab__item__icon far fa-user"></i>';
									}

									echo wp_kses($event_meta_venue_icon, $allowed_html);

									if ($venue_map_link) {
										if (tribe_get_map_link($post->ID, true) || tribe_get_venue($post->ID, true)) {
					?>
											<a href="<?php echo esc_url(tribe_get_map_link($post->ID, true)) ?>"><?php echo esc_html(tribe_get_venue($post->ID, true));  ?>,</a>
							<?php
										}
									} else {
										if (tribe_get_venue($post->ID, true)) {
											echo '<span>' . esc_html(tribe_get_venue($post->ID, true)) . ',' . '</span>';
										}
									}
									break;
								case 'city':
									if (tribe_get_city($post->ID, true)) {
										echo '<span>' . esc_html(tribe_get_city($post->ID, true)) . ',' . '</span>';
									}

									break;
								case 'country':
									if (tribe_get_country($post->ID, true)) {
										echo '<span>' . esc_html(tribe_get_country($post->ID, true)) . ',' . '</span>';
									}
									break;
								case 'state':
									if (tribe_get_zip($post->ID, true)) {
										echo '<span>' . esc_html(tribe_get_zip($post->ID, true)) . ',' . '</span>';
									}
									break;
								case 'postal_code':
									if (tribe_get_stateprovince($post->ID, true)) {
										echo '<span>' . esc_html(tribe_get_stateprovince($post->ID, true)) . ',' . '</span>';
									}
									break;
								case 'phone':
									$phone = tribe_get_phone($post->ID, true);

									if ($phone) {
										echo '<span>';

										if ($venue_phone_icon) {
											echo '<i class="' . esc_attr($venue_phone_icon['value']) . '"></i>';
										}

										echo esc_html($phone) . ',' . '</span>';
									}
									break;
							}
						}
					}
					break;
				case 'organizer':
					if ('svg' === $event_organizer_icon['library']) {
						$date_meta_icon     =  '<img alt=' . esc_html__('Image', 'eventful-for-elementor') . ' src="' . esc_url($event_organizer_icon_value["url"]) . '" width="16" height="16" alt=' . esc_html__('Image', 'eventful-for-elementor') . '>';
					} else {
						$date_meta_icon     = !empty($organizer_icon) ? $organizer_icon : '<i class="elementor-icons-manager__tab__item__icon far fa-user"></i>';
					}

					if (tribe_get_organizer($post->ID, true)) {
						echo wp_kses_post($meta_tag_start);
						echo wp_kses($date_meta_icon, $allowed_html);
						if ($venue_map_link) {
							?>
							<a href="<?php echo esc_url(tribe_get_organizer_website_url($post->ID)); ?>"><?php echo esc_html(tribe_get_organizer($post->ID, true));  ?></a>
						<?php
						} else {
						?>
							<span><?php echo esc_html(tribe_get_organizer($post->ID, true)); ?></span>
						<?php
						}
						echo wp_kses_post($meta_tag_end);
					}
					break;
				case 'price':
					if ('svg' === $event_price_icon['library']) {
						$date_meta_icon     =  '<img alt=' . esc_html__('Image', 'eventful-for-elementor') . ' src="' . esc_url($event_price_icon_value["url"]) . '" width="16" height="16" >';
					} else {
						$date_meta_icon     = !empty($price_icon) ? $price_icon : '<i class="elementor-icons-manager__tab__item__icon far fa-user"></i>';
					}

					if (tribe_get_cost($post->ID)) {
						echo wp_kses_post($meta_tag_start);
						echo wp_kses($date_meta_icon, $allowed_html);
						if ($venue_map_link) {
						?>
							<span><?php echo esc_html(tribe_get_cost($post->ID)) ?></span>
						<?php
						} else {
						?>
							<span><?php echo esc_html(tribe_get_cost($post->ID)) ?></span>
					<?php
						}
						echo wp_kses_post($meta_tag_end);
					}
					break;
				case 'event_time':
					if ('svg' === $event_date_icon['library']) {
						$date_meta_icon     =  '<img alt=' . esc_html__('Image', 'eventful-for-elementor') . ' src="' . esc_url($event_date_icon_value["url"]) . '" width="16" height="16" >';
					} else {
						$date_meta_icon     = !empty($date_icon) ? $date_icon : '<i class="elementor-icons-manager__tab__item__icon far fa-user"></i>';
					}

					echo wp_kses_post($meta_tag_start);
					if ('start_date' === $event_fildes_date_type) {
						if ('custom' === $event_fildes_date_format) {
							$event_date = tribe_get_start_date($post->ID, false, $efpe_custom_event_date_format);
						} else {
							$event_date = tribe_get_start_date($post->ID, false, $event_fildes_date_format);
						}
					} elseif ('end_date' === $event_fildes_date_type) {
						if ('custom' === $event_fildes_date_format) {
							$event_date = tribe_get_end_date($post->ID, false, $efpe_custom_event_date_format);
						} else {
							$event_date = tribe_get_end_date($post->ID, false, $event_fildes_date_format);
						}
					} else {
						if ('custom' === $event_fildes_date_format) {
							$event_date = tribe_get_start_date($post->ID, true, $efpe_custom_event_date_format) . ' - ' . tribe_get_end_date($post->ID, true, $efpe_custom_event_date_format);
						} else {
							$event_date = tribe_get_start_date($post->ID, true, $event_fildes_date_format) . ' - ' . tribe_get_end_date($post->ID, true, $event_fildes_date_format);
						}
					}
					echo wp_kses($date_meta_icon, $allowed_html); ?>
					<time class="entry-date published updated">
						<?php echo wp_kses_post($event_date); ?></time>
<?php
					echo wp_kses_post($meta_tag_end);

					break;
			}
			++$i;
		}
		echo wp_kses_post($meta_wrapper_end_tag);
	}

	/**
	 * Process the taxonomy terms.
	 *
	 * @param array $taxonomy The taxonomy name to show terms from.
	 * @param mixed $id ids.
	 * @param mixed $meta_icon The meta icon html.
	 * @return statement
	 */
	public static function efpe_taxonomy_terms($taxonomy, $id, $meta_icon = null)
	{
		$terms = get_the_term_list($id, $taxonomy, '', ', ');
		if (!empty($terms) && !is_wp_error($terms)) {
			return $meta_icon . $terms;
		}
	}

	/**
	 * Show post thumb category.
	 *
	 * @param integer $post_id The post ID.
	 * @return statement.
	 */
	public static function efpe_post_thumb_taxonomy($taxonomy, $id, $meta_icon = null)
	{
		$terms = get_the_terms($id, $taxonomy);

		if (!empty($terms) && !is_wp_error($terms)) {
			$first_term = reset($terms); // Get the first term

			if ($first_term) {
				return '<a href="' . esc_url(get_tag_link($first_term->term_id)) . '">' . esc_html($first_term->name) . '</a>';
			}
		}
	}

	/**
	 * Maximum pages.
	 *
	 * @param int $total_post Number of total posts.
	 * @param int $event_per_page Events per page.
	 *
	 * @return void
	 */
	public static function efpe_max_pages($total_post, $event_per_page)
	{
		// Ensure both $total_post and $event_per_page are numeric values
		if (!is_numeric($total_post) || !is_numeric($event_per_page)) {
			return 0; // Return 0 or handle the error appropriately
		}

		// Convert to integers to ensure numeric division
		$total_post = (int) $total_post;
		$event_per_page = (int) $event_per_page;

		// Avoid division by zero
		if ($event_per_page === 0) {
			return 0; // Return 0 or handle the error appropriately
		}

		// Calculate and return the maximum number of pages
		return (int) ceil($total_post / $event_per_page);
	}


	/**
	 * Event per page.
	 *
	 * @param int $limit Event Limit.
	 * @param int $event_per_page post per page.
	 * @param int $page paged number.
	 *
	 * @return int
	 */
	public static function efpe_post_per_page($limit, $event_per_page, $page)
	{
		$limit               = (empty($limit) || '-1' === $limit) ? 10000000 : $limit;
		$offset              = (int) $event_per_page * ($page - 1);

		$final_post_per_page = !empty($event_per_page) ? $event_per_page : $limit;
		if (intval($event_per_page) > $limit - $offset) {
			$final_post_per_page = $limit - $offset;
		}

		return $final_post_per_page;
	}

	/**
	 * Pagination last page post
	 *
	 * @param [type] $limit total post limit.
	 * @param [type] $event_per_page post per page.
	 * @param [type] $total_page last post page.
	 *
	 * @return int.
	 */
	public static function efpe_last_page_post($limit, $event_per_page, $total_page)
	{
		// Ensure all parameters are numeric values
		if (!is_numeric($limit) || !is_numeric($event_per_page) || !is_numeric($total_page)) {
			return 0; // Return 0 or handle the error appropriately
		}

		// Convert to integers to ensure numeric calculations
		$limit = (int) $limit;
		$event_per_page = (int) $event_per_page;
		$total_page = (int) $total_page;

		// Avoid division by zero or negative values
		if ($event_per_page <= 0 || $total_page <= 0) {
			return 0; // Return 0 or handle the error appropriately
		}

		// Calculate the offset
		$offset = $event_per_page * ($total_page - 1);

		// Ensure the limit is greater than or equal to the offset
		$efpe_last_page_post = max(0, $limit - $offset);

		return $efpe_last_page_post;
	}


	/**
	 * Get view option from view ID
	 *
	 * @param string $efpe_gl_id ID of custom field.
	 *
	 * @return array
	 */
	public static function view_options($efpe_gl_id)
	{
		if (!$efpe_gl_id) {
			return;
		}
		$view_options = get_post_meta($efpe_gl_id, 'efpe_view_options', true);
		return $view_options;
	}

	/**
	 * Get value of a setting from global settings array
	 *
	 * @param string     $field        The full name of setting to get value.
	 * @param array      $array_to_get Array to get values of wanted setting.
	 * @param mixed|null $assign       The value to assign if setting is not found.
	 */
	public static function efpe_metabox_value($field, $array_to_get = null, $assign = null)
	{
		global $efpe_gl_id;
		if (empty($array_to_get)) {
			$array_to_get = self::view_options($efpe_gl_id);
		}
		return isset($array_to_get[$field]) ? $array_to_get[$field] : $assign;
	}

	/**
	 * Custom Template locator .
	 *
	 * @param  mixed $template_name template name .
	 * @param  mixed $template_path template path .
	 * @param  mixed $default_path default path .
	 * @return string
	 */
	public static function eventful_for_elementor_locate_template($template_name, $template_path = '', $default_path = '')
	{
		if (!$template_path) {
			$template_path = 'eventful-for-elementor';
		}

		if (!$default_path) {
			$default_path = EVENTFUL_ELEMENTOR_PLUGIN_PATH . '/src/Frontend/templates/';
		}
		$template = locate_template(trailingslashit($template_path) . $template_name);
		// Get default template.
		if (!$template) {
			$template = $default_path . $template_name;
		}
		// Return what we found.
		return $template;
	}
}
