<?php

namespace Unlockafe_addons\Traits;

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

trait Utils
{


	/**
	 ********
	 * get_post return the array of post
	 * 
	 * @since 1.0.0
	 * @param string $post_type
	 * @return array
	 */
	public function get_posts(string $post_type = 'post')
	{

		/// post arguments
		$args = array(
			'post_type' => $post_type,
			'posts_per_page' => -1,
		);

		$posts_query = new \WP_Query($args);
		$posts       = [];

		if ($posts_query->have_posts()) {
			while ($posts_query->have_posts()) {
				$posts_query->the_post();
				// assign post to the $array
				$posts[get_the_ID()] = get_the_title();
			}
			wp_reset_postdata();
		}

		return $posts;
	}

	/**
	 ********
	 * get_categories return the array of Cat Taxonomy 
	 * 
	 * @since 1.0.0
	 * @return array
	 */
	public function get_categories()
	{
		$categories = get_categories();
		$cat        = [];
		foreach ($categories as $item) {
			$cat[$item->term_id] = $item->name;
		}

		return $cat;
	}

	/**
	 ********
	 * get_tags return the array of tag Taxonomy 
	 * 
	 * @since 1.0.0
	 * @return array
	 */
	public function get_tags()
	{
		$tags = get_tags();
		$tag  = [];
		foreach ($tags as $item) {
			$tag[$item->term_id] = $item->name;
		}

		return $tag;
	}

	/**
	 ********
	 * get_author return the array of authors
	 * 
	 * @since 1.0.0
	 * @return array
	 */
	public function get_author()
	{
		$authors = get_users();
		$author  = [];
		foreach ($authors as $item) {
			$author[$item->ID] = $item->user_nicename;
		}

		return $author;
	}

	/**
	 *  Return Allowd HTML function.
	 * 
	 * @since 1.0.0
	 * @return array
	 */
	public function allowed_tags()
	{

		$allowed_tags = [
			'a' => [
				'class' => [],
				'href' => [],
				'rel' => [],
				'title' => [],
				'target' => [],
			],
			'abbr' => [
				'title' => [],
			],
			'b' => [],
			'blockquote' => [
				'cite' => [],
			],
			'cite' => [
				'title' => [],
			],
			'code' => [],
			'del' => [
				'datetime' => [],
				'title' => [],
			],
			'dd' => [],
			'div' => [
				'class' => [],
				'title' => [],
				'style' => [],
			],
			'dl' => [],
			'dt' => [],
			'em' => [],
			'h1' => [],
			'h2' => [],
			'h3' => [],
			'h4' => [],
			'h5' => [],
			'h6' => [],
			'sub' => [],
			'i' => [
				'class' => [],
			],
			'img' => [
				'alt' => [],
				'class' => [],
				'height' => [],
				'src' => [],
				'width' => [],
			],
			'li' => [
				'class' => [],
			],
			'ol' => [
				'class' => [],
			],
			'p' => [
				'class' => [],
			],
			'q' => [
				'cite' => [],
				'title' => [],
			],
			'span' => [
				'class' => [],
				'title' => [],
				'style' => [],
			],
			'iframe' => [
				'width' => [],
				'height' => [],
				'scrolling' => [],
				'frameborder' => [],
				'allow' => [],
				'src' => [],
			],
			'strike' => [],
			'br' => [],
			'strong' => [],
			'ul' => [
				'class' => [],
			],
		];


		return $allowed_tags;
	}


	/**
	 * Summary of get_hero_posts_query
	 * 
	 * This will return an Query object based on peramiter
	 * 
	 * @param mixed $settings
	 * @param int $page
	 * @param string $post_type
	 * @return \WP_Query
	 */
	public function get_posts_query($settings, int $page = 1, string $post_type = 'post'): \WP_Query
	{
		// Query posts without using tax_query
		$args = [
			'posts_per_page' => $settings['post_per_page'] ?? 10,
			'order'          => 'DESC',
			'post_status'    => 'publish',
			'post_type'      => $post_type,
			'paged'          => $page,
		];
	
		// Add ordering if post_source is set
		if (!empty($settings['post_source'])) {
			$args['orderby'] = $settings['post_source'];
		}
	
		// Add specific posts to include, if set
		if (!empty($settings['include_post'])) {
			$args['post__in'] = $settings['include_post'];
		}
	
		// Add specific authors to include, if set
		if (!empty($settings['post_author'])) {
			$args['author__in'] = $settings['post_author'];
		}
	
		$the_query = new \WP_Query($args);
	
		// Now, programmatically filter posts by taxonomies
		if (!empty($settings['post_category']) || !empty($settings['post_tag'])) {
			$filtered_posts = [];
	
			while ($the_query->have_posts()) {
				$the_query->the_post();
				$post_id = get_the_ID();
	
				// Check if the post has the required categories or tags
				$has_required_taxonomies = true;
	
				if (!empty($settings['post_category'])) {
					$has_required_taxonomies = has_term($settings['post_category'], 'category', $post_id);
				}
	
				if ($has_required_taxonomies && !empty($settings['post_tag'])) {
					$has_required_taxonomies = has_term($settings['post_tag'], 'post_tag', $post_id);
				}
	
				if ($has_required_taxonomies) {
					$filtered_posts[] = $post_id;
				}
			}
	
			// Reset the post data after the loop
			wp_reset_postdata();
	
			// Return a new WP_Query object with the filtered post IDs
			$filtered_args = [
				'post__in' => $filtered_posts,
				'posts_per_page' => $settings['post_per_page'],
			];
	
			return new \WP_Query($filtered_args);
		}
	
		return $the_query;
	}

	public function unlockafe_combine_widgets($widgets, $db_widgets)
	{
		return array_replace_recursive($widgets, $db_widgets);
	}
	protected function filter_widgets()
	{
		// minimise array
		$new_widgets = [];
		$to_unset    = ['css', 'js'];

		// creating new array
		foreach ($this->registered_widgets as $k => $v) {
			$v['id'] = $k;

			if (isset($v['type']) && ! empty($v['type'])) {
				$v['type'] = $v['type'] == 'pro' ? true : false;
			}
			$new_widgets[] = array_diff_key($v, array_flip($to_unset));
		}
		$this->new_widgets = $new_widgets;
		return $new_widgets;
	}

	/**
	 * Summary of get_skin
	 * 
	 * Locate the templates of widget
	 * 
	 * @param mixed $path
	 * @param mixed $args
	 * @return void
	 */
	public function get_skin($path, $args = [])
	{
		$real_path = UNLOCKAFE_INCLUDE_PATH . 'Skins/' . $path . '.php';
		if (file_exists($real_path)) {
			include $real_path;
		}
	}

	/**
	 * Get image size from settings
	 * 
	 * @since 1.0.0
	 * @param array $settings
	 * @param string $key
	 * @return string|array
	 */
	public function tp_get_img_size($settings = null, $key = '')
	{
		if (empty($settings) || empty($key)) {
			return 'full';
		}

		$img_size = $settings[$key . '_size'] ?? 'full';

		if ('custom' !== $img_size) {
			$image_size = $img_size;
		} else {
			require_once ELEMENTOR_PATH . 'includes/libraries/bfi-thumb/bfi-thumb.php';
			$image_dimention = $settings[$key . '_custom_dimension'] ?? [];
			$image_size = [
				0 => null,
				1 => null,
				'bfi_thumb' => true,
				'crop' => true,
			];
			$has_custom_size = false;
			if (!empty($image_dimention['width'])) {
				$has_custom_size = true;
				$image_size[0] = $image_dimention['width'];
			}

			if (!empty($image_dimention['height'])) {
				$has_custom_size = true;
				$image_size[1] = $image_dimention['height'];
			}

			if (!$has_custom_size) {
				$image_size = 'full';
			}
		}

		return $image_size;
	}

	/**
	 * Render link attributes for button
	 * 
	 * @since 1.0.0
	 * @param string $control_id
	 * @param string $control_name
	 * @param array $settings
	 * @return void
	 */
	protected function tp_link_attributes_render($control_id = null, $control_name = 'tp-btn', $settings = null)
	{
		if (empty($control_id) || empty($settings)) {
			return;
		}

		if ('2' == ($settings['tp_' . $control_id . '_link_type'] ?? '1')) {
			$this->add_render_attribute('tp-button-arg' . $control_id . '', 'href', get_permalink($settings['tp_' . $control_id . '_page_link'] ?? ''));
			$this->add_render_attribute('tp-button-arg' . $control_id . '', 'target', '_self');
			$this->add_render_attribute('tp-button-arg' . $control_id . '', 'rel', 'nofollow');
			$this->add_render_attribute('tp-button-arg' . $control_id . '', 'class', '' . $control_name . ' tp-el-btn');
		} else {
			if (!empty($settings['tp_' . $control_id . '_link']['url'])) {
				$this->add_link_attributes('tp-button-arg' . $control_id . '', $settings['tp_' . $control_id . '_link']);
				$this->add_render_attribute('tp-button-arg' . $control_id . '', 'class', '' . $control_name . ' tp-el-btn');
			}
		}
	}

	/**
	 * Kses function for allowed HTML
	 * 
	 * @since 1.0.0
	 * @param string $raw
	 * @return string
	 */
	public function tp_kses($raw)
	{
		return wp_kses($raw, $this->allowed_tags());
	}

	/**
	 * Get all types of posts
	 * 
	 * @since 1.0.0
	 * @param string $post_type
	 * @return array
	 */
	public function tp_get_all_types_post($post_type = 'page')
	{
		return $this->get_posts($post_type);
	}

	/**
	 * Get allowed HTML description
	 * 
	 * @since 1.0.0
	 * @param string $level
	 * @return string
	 */
	public function tp_get_allowed_html_desc($level = 'basic')
	{
		if (!in_array($level, ['basic', 'intermediate', 'advance'])) {
			$level = 'basic';
		}

		$tags_str = '<' . implode('>,<', array_keys($this->tp_get_allowed_html_tags($level))) . '>';
		return sprintf(__('This input field has support for the following HTML tags: %1$s', 'unlock-addons-for-elementor'), '<code>' . esc_html($tags_str) . '</code>');
	}

	/**
	 * Get allowed HTML tags
	 * 
	 * @since 1.0.0
	 * @param string $level
	 * @return array
	 */
	public function tp_get_allowed_html_tags($level = 'basic')
	{
		$allowed_html = [
			'b' => [],
			'i' => [
				'class' => [],
			],
			'u' => [],
			'em' => [],
			'br' => [],
			'abbr' => [
				'title' => [],
			],
			'span' => [
				'class' => [],
			],
			'strong' => [],
		];

		if ($level === 'intermediate') {
			$allowed_html['a'] = [
				'href' => [],
				'title' => [],
				'class' => [],
				'id' => [],
				'target' => [],
			];
		}

		if ($level === 'advance') {
			$allowed_html['ul'] = [
				'class' => [],
				'id' => [],
			];
			$allowed_html['ol'] = [
				'class' => [],
				'id' => [],
			];
			$allowed_html['li'] = [
				'class' => [],
				'id' => [],
			];
			$allowed_html['a'] = [
				'href' => [],
				'title' => [],
				'class' => [],
				'id' => [],
				'target' => [],
			];
		}

		return $allowed_html;
	}

	/**
	 * Render single icon HTML
	 * 
	 * @since 1.0.0
	 * @param array $settings
	 * @param string $key
	 * @param string $class
	 * @return void
	 */
	public function tp_render_signle_icon_html($settings = null, $key = 'icon', $class = '')
	{
		if (empty($settings)) {
			return;
		}

		$common_icon_class = 'tp-' . $key . '-icon ' . $class;
		$common_image_class = 'tp-' . $key . '-image-icon ' . $class;
		$common_svg_class = 'tp-' . $key . '-svg-icon ' . $class;

		$icon_type = $settings['tp_' . $key . '_icon_type'] ?? 'icon';

		if ($icon_type == 'icon') {
			if (!empty($settings['tp_' . $key . '_icon'])) {
				$icon_settings = $settings['tp_' . $key . '_icon'];
				
				// Check if icon value exists
				$icon_value = isset($icon_settings['value']) ? $icon_settings['value'] : '';
				
				// Check for invalid icon names that might cause warnings
				$invalid_icons = ['bag-shopping', 'fa-bag-shopping'];
				$is_invalid = false;
				
				if (!empty($icon_value) && is_string($icon_value)) {
					foreach ($invalid_icons as $invalid) {
						if (strpos($icon_value, $invalid) !== false) {
							$is_invalid = true;
							break;
						}
					}
				}
				
				echo '<span class="' . esc_attr($common_icon_class) . '">';
				
				// If invalid icon, use fallback for cart icons
				if ($is_invalid && strpos($key, 'cart') !== false) {
					echo '<i class="fas fa-shopping-cart" aria-hidden="true"></i>';
				} elseif (empty($icon_value) && strpos($key, 'cart') !== false) {
					// If icon value is empty but it's a cart icon, use fallback
					echo '<i class="fas fa-shopping-cart" aria-hidden="true"></i>';
				} elseif (!empty($icon_value)) {
					// Valid icon, render normally
					\Elementor\Icons_Manager::render_icon($icon_settings, ['aria-hidden' => 'true']);
				} else {
					// Icon value is empty, try to render anyway (Elementor might handle it)
					\Elementor\Icons_Manager::render_icon($icon_settings, ['aria-hidden' => 'true']);
				}
				
				echo '</span>';
			} elseif (strpos($key, 'cart') !== false) {
				// If icon settings are empty but it's a cart icon, show fallback
				echo '<span class="' . esc_attr($common_icon_class) . '">';
				echo '<i class="fas fa-shopping-cart" aria-hidden="true"></i>';
				echo '</span>';
			}
		} elseif ($icon_type == 'image') {
			echo '<span class="' . esc_attr($common_image_class) . '">';
			if (!empty($settings['tp_' . $key . '_image']['url'])) {
				$image_id = attachment_url_to_postid($settings['tp_' . $key . '_image']['url']);
				$alt = $image_id ? get_post_meta($image_id, '_wp_attachment_image_alt', true) : '';
				echo '<img src="' . esc_url($settings['tp_' . $key . '_image']['url']) . '" alt="' . esc_attr($alt) . '">';
			}
			echo '</span>';
		} else {
			echo '<span class="' . esc_attr($common_svg_class) . '">';
			if (!empty($settings['tp_' . $key . '_icon_svg'])) {
				echo wp_kses_post($settings['tp_' . $key . '_icon_svg']);
			}
			echo '</span>';
		}
	}

	/**
	 * Get orderby options for post queries
	 * 
	 * @since 1.0.0
	 * @return array
	 */
	public function tp_get_orderby_options()
	{
		return [
			'ID' => 'Post ID',
			'author' => 'Post Author',
			'title' => 'Title',
			'date' => 'Date',
			'modified' => 'Last Modified Date',
			'parent' => 'Parent Id',
			'rand' => 'Random',
			'comment_count' => 'Comment Count',
			'menu_order' => 'Menu Order',
		];
	}

	/**
	 * Get categories for a taxonomy
	 * 
	 * @since 1.0.0
	 * @param string $category Taxonomy name
	 * @return array
	 */
	public function tp_get_categories($category = 'category')
	{
		$categories = get_categories([
			'taxonomy' => $category,
			'orderby' => 'name',
			'order' => 'ASC',
		]);
		$cat_list = [];
		foreach ($categories as $cat) {
			$cat_list[$cat->slug] = $cat->name;
		}
		return $cat_list;
	}

	/**
	 * Build query arguments for post queries
	 * 
	 * @since 1.0.0
	 * @param string $post_type Post type
	 * @param string $taxonomy Taxonomy name
	 * @param array|null $settings Widget settings
	 * @return array
	 */
	public function tp_query_args($post_type = 'post', $taxonomy = 'category', $settings = null)
	{
		$posts_per_page = !empty($settings['posts_per_page']) ? $settings['posts_per_page'] : -1;
		$order = !empty($settings['order']) ? $settings['order'] : 'DESC';
		$order_by = !empty($settings['orderby']) ? $settings['orderby'] : 'date';

		$cat_list = !empty($settings['category']) ? $settings['category'] : [];
		$cat_exclude = !empty($settings['exclude_category']) ? $settings['exclude_category'] : [];
		$cat_include = !empty($settings['category']) ? $settings['category'] : [];

		$post_exclude = !empty($settings['post__not_in']) ? $settings['post__not_in'] : [];
		$post_include = !empty($settings['post__in']) ? $settings['post__in'] : [];
		$ignore_sticky_posts = (!empty($settings['ignore_sticky_posts']) && 'yes' == $settings['ignore_sticky_posts']) ? true : false;

		if (get_query_var('paged')) {
			$paged = get_query_var('paged');
		} else if (get_query_var('page')) {
			$paged = get_query_var('page');
		} else {
			$paged = 1;
		}

		$offset_value = (!empty($settings['offset'])) ? $settings['offset'] : '0';
		$off = (!empty($offset_value)) ? $offset_value : 0;
		$offset = $off + (($paged - 1) * $posts_per_page);

		$args = [
			'post_type' => $post_type,
			'post_status' => 'publish',
			'order' => $order,
			'offset' => $offset,
			'orderby' => $order_by,
			'posts_per_page' => $posts_per_page,
			'post__not_in' => $post_exclude,
			'post__in' => $post_include,
			'ignore_sticky_posts' => $ignore_sticky_posts
		];

		if (!empty($cat_include) && !empty($cat_exclude)) {
			$args['tax_query'] = [
				'relation' => 'AND',
				[
					'taxonomy' => $taxonomy,
					'field' => 'slug',
					'terms' => $cat_include,
					'operator' => 'IN',
				],
				[
					'taxonomy' => $taxonomy,
					'field' => 'slug',
					'terms' => $cat_exclude,
					'operator' => 'NOT IN',
				],
			];
		} elseif (!empty($cat_list) || !empty($cat_exclude)) {
			$args['tax_query'] = [
				[
					'taxonomy' => $taxonomy,
					'field' => 'slug',
					'terms' => !empty($cat_exclude) ? $cat_exclude : $cat_list,
					'operator' => !empty($cat_exclude) ? 'NOT IN' : 'IN',
				],
			];
		}

		return $args;
	}

	/**
	 * Get repeater links attributes
	 * 
	 * @since 1.0.0
	 * @param array $item Settings item
	 * @param string|null $control_id Control ID
	 * @return array
	 */
	public function tp_get_repeater_links_attr($item, $control_id = null)
	{
		if ('2' == $item['tp_' . $control_id . '_link_type']) {
			$link = get_permalink($item['tp_' . $control_id . '_page_link']);
			$target = '_self';
			$rel = 'nofollow';
		} else {
			$link = !empty($item['tp_' . $control_id . '_link']['url']) ? $item['tp_' . $control_id . '_link']['url'] : '';
			$target = !empty($item['tp_' . $control_id . '_link']['is_external']) ? '_blank' : '';
			$rel = !empty($item['tp_' . $control_id . '_link']['nofollow']) ? 'nofollow' : '';
		}

		return [
			'link' => $link,
			'target' => $target,
			'rel' => $rel
		];
	}

	/**
	 * Get image with size
	 * 
	 * @since 1.0.0
	 * @param array|null $settings Widget settings
	 * @param string $key Image key
	 * @param string $size Image size key
	 * @param bool $has_size_settings Whether size settings exist
	 * @return array
	 */
	public function tp_get_img($settings = null, $key = '', $size = 'full', $has_size_settings = true)
	{
		$img_size = $has_size_settings ? $settings[$size . "_size"] : 'full';
		$tp_image = '';
		$tp_image_alt = '';

		if (!empty($settings[$key]['url'])) {
			$tp_image = !empty($settings[$key]['id']) ? wp_get_attachment_image_url($settings[$key]['id'], $img_size) : $settings[$key]['url'];
			$tp_image_alt = get_post_meta($settings[$key]["id"], "_wp_attachment_image_alt", true);
		}

		return [
			$key => $tp_image,
			$key . '_alt' => $tp_image_alt
		];
	}

	/**
	 * Implode HTML attributes
	 * 
	 * @since 1.0.0
	 * @param array $raw_attributes Raw attributes array
	 * @return string
	 */
	public function tp_implode_html_attributes($raw_attributes)
	{
		$attributes = array();
		foreach ($raw_attributes as $name => $value) {
			if (!empty($value)) {
				$attributes[] = esc_attr($name) . '="' . esc_attr($value) . '"';
			}
		}
		return implode(' ', $attributes);
	}

	/**
	 * Get all pages
	 * 
	 * @since 1.0.0
	 * @return array
	 */
	public function tp_get_all_pages()
	{
		$page_list = get_posts(
			array(
				'post_type' => 'page',
				'orderby' => 'date',
				'order' => 'DESC',
				'posts_per_page' => 50,
			)
		);

		$pages = array();

		if (!empty($page_list) && !is_wp_error($page_list)) {
			foreach ($page_list as $page) {
				$pages[$page->ID] = $page->post_title;
			}
		}

		return $pages;
	}
}