<?php

/**
 * Flo Guten Helper.
 *
 * @package FBG
 */

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

if (!class_exists('Flo_Guten_Blocks_Helper')) {
	/**
	 * Class Flo_Guten_Helper.
	 */
	final class Flo_Guten_Blocks_Helper
	{
		/**
		 * Member Variable
		 *
		 * @since 0.0.1
		 * @var instance
		 */
		private static $instance;

		/**
		 *  Initiator
		 *
		 * @since 0.0.1
		 */
		public static function get_instance()
		{
			if (!isset(self::$instance)) {
				self::$instance = new self();
			}
			return self::$instance;
		}

		/**
		 * Constructor
		 */
		public function __construct()
		{
		}

		public static function flo_comment_reply_text($attr, $link)
		{
			$link = str_replace('Reply', $attr['replayLabel'], $link);
			return $link;
		}
		/**
		 * Get size information for all currently-registered image sizes.
		 *
		 * @global $_wp_additional_image_sizes
		 * @uses   get_intermediate_image_sizes()
		 * @link   https://codex.wordpress.org/Function_Reference/get_intermediate_image_sizes
		 * @since  1.9.0
		 * @return array $sizes Data for all currently-registered image sizes.
		 */
		public static function get_image_sizes()
		{
			global $_wp_additional_image_sizes;

			$sizes = get_intermediate_image_sizes();
			$image_sizes = [];

			$image_sizes[] = [
				'value' => 'full',
				'label' => esc_html__('Full', 'flo-gutenberg-blocks'),
			];

			foreach ($sizes as $size) {
				if (
					in_array(
						$size,
						['thumbnail', 'medium', 'medium_large', 'large'],
						TRUE
					)
				) {
					$image_sizes[] = [
						'value' => $size,
						'label' => ucwords(
							trim(str_replace(['-', '_'], [' ', ' '], $size))
						),
					];
				} else {
					$image_sizes[] = [
						'value' => $size,
						'label' => sprintf(
							'%1$s (%2$sx%3$s)',
							ucwords(trim(str_replace(['-', '_'], [' ', ' '], $size))),
							$_wp_additional_image_sizes[$size]['width'],
							$_wp_additional_image_sizes[$size]['height']
						),
					];
				}
			}

			return $image_sizes;
		}

		/**
		 * Get Post Types.
		 *
		 * @since 1.11.0
		 * @access public
		 */
		public static function get_post_types()
		{
			$post_types = get_post_types(
				[
					'public' => TRUE,
					'show_in_rest' => TRUE,
				],
				'objects'
			);

			$options = [];

			foreach ($post_types as $post_type) {
				if ('product' === $post_type->name) {
					continue;
				}

				if ('attachment' === $post_type->name) {
					continue;
				}

				$options[] = [
					'value' => $post_type->name,
					'label' => $post_type->label,
				];
			}

			return $options;
		}

		/**
		 * Get all taxonomies.
		 *
		 * @since 1.11.0
		 * @access public
		 */
		public static function get_related_taxonomy()
		{
			$post_types = self::get_post_types();

			$return_array = [];

			foreach ($post_types as $key => $value) {
				$post_type = $value['value'];

				$taxonomies = get_object_taxonomies($post_type, 'objects');
				$data = [];

				foreach ($taxonomies as $tax_slug => $tax) {
					if (!$tax->public || !$tax->show_ui || !$tax->show_in_rest) {
						continue;
					}

					$data[$tax_slug] = $tax;

					$terms = get_terms($tax_slug, ['hide_empty' => FALSE]);

					$related_tax = [];

					if (!empty($terms)) {
						foreach ($terms as $t_index => $t_obj) {
							$related_tax[] = [
								'id' => $t_obj->term_id,
								'name' => $t_obj->name,
							];
						}

						$return_array[$post_type]['terms'][$tax_slug] = $related_tax;
					}
				}

				$return_array[$post_type]['taxonomy'] = $data;
			}
			return $return_array;
		}

		/**
		 * Returns Query.
		 *
		 * @param array  $attributes The block attributes.
		 */
		public static function get_query($attributes)
		{
			$query_args = [
				'posts_per_page' => isset($attributes['postsToShow'])
					? $attributes['postsToShow']
					: 6,
				'post_status' => 'publish',
				'post_type' => isset($attributes['postType'])
					? $attributes['postType']
					: 'post',
				'ignore_sticky_posts' => 1,
				'paged' => 1,
			];

			if ($attributes['excludeCurrentPost']) {
				$query_args['post__not_in'] = [get_the_ID()];
			}

			if (
				isset($attributes['categories']) &&
				'' !== $attributes['categories']
			) {
				$query_args['tax_query'][] = [
					'taxonomy' => isset($attributes['taxonomyType'])
						? $attributes['taxonomyType']
						: 'category',
					'field' => 'id',
					'terms' => $attributes['categories'],
					'operator' => 'IN',
				];
			}

			if (
				isset($attributes['postPagination']) &&
				TRUE === $attributes['postPagination']
			) {
				if (get_query_var('paged')) {
					$paged = get_query_var('paged');
				} elseif (get_query_var('page')) {
					$paged = get_query_var('page');
				} else {
					$paged = 1;
				}
				$query_args['posts_per_page'] = $attributes['postsToShow'];
				$query_args['paged'] = $paged;
			}

			return new WP_Query($query_args);
		}
		/**
		 * Returns default image.
		 *
		 * @param array  $attributes The block attributes.
		 */
		public static function get_default_post_image()
		{
			return FGB_URL . '/assets/images/no-image.jpg';
		}

		public static function get_post_pagination($attributes)
		{
			extract($attributes);

			$pagination_str = '';
			if ($displayPagination  || is_archive() || (is_home() && is_front_page()) || is_home()) {
				$attr = [
					'prev_next' => FALSE,
				];
				$pagination_str =
					'<div class="flo-block flo-block-post-pagination" style="
					--pagination-elements-color: ' .
					Flo_Guten_Blocks_Helper::get_style_color($paginationElementsColor) .
					';
					--pagination-background-color: ' .
					Flo_Guten_Blocks_Helper::get_style_color($paginationBackgroundColor) .
					';
					--pagination-line-color: ' .
					Flo_Guten_Blocks_Helper::get_style_color($paginationLineColor) .
					Flo_Guten_Blocks_Helper::get_style_for_typography(
						'pagination-arrows',
						$paginationArrowsTypography
					) .
					Flo_Guten_Blocks_Helper::get_style_for_typography(
						'pagination-numbers',
						$paginationNumbersTypography
					) .
					'
					">';

				$pagination_str .=
					'<div class="flo-block-post-pagination__arrows flo-block-post-pagination__arrows--prev" data-font="' .
					Flo_Guten_Blocks_Helper::getDataFontForTypography(
						$paginationArrowsTypography
					) .
					'">' .
					get_previous_posts_link(
						'<i class="gbp-icon-arrow-small-left-1"></i> <span>' .
							$previousLinkLabel .
							'</span>'
					) .
					'</div>';
				if ($paginationDisplayNumbers) {
					$pagination_str .=
						'<div class="flo-block-post-pagination__numbers" data-font="' .
						Flo_Guten_Blocks_Helper::getDataFontForTypography(
							$paginationNumbersTypography
						) .
						'">' .
						paginate_links($attr) .
						'</div>';
				}
				$pagination_str .=
					'<div class="flo-block-post-pagination__arrows flo-block-post-pagination__arrows--next" data-font="' .
					Flo_Guten_Blocks_Helper::getDataFontForTypography(
						$paginationArrowsTypography
					) .
					'">' .
					get_next_posts_link(
						'<span>' .
							$nextLinkLabel .
							'</span> <i class="gbp-icon-arrow-small-right-1"></i>'
					) .
					'</div>';
				$pagination_str .= '</div>';
			}
			return $pagination_str;
		}

		public static function get_style_color($color)
		{
			$colorStr =
				isset($color['theme']) && $color['theme'] != ''
				? 'var(--' . str_replace('/', '--', $color['theme']) . ')'
				: $color['custom'];

			return $colorStr;
		}

		public static function get_post_query($attributes)
		{
			extract($attributes);

			if (is_numeric(get_query_var('paged'))) {
				$page = get_query_var('paged');
			} elseif (is_numeric(get_query_var('page'))) {
				// fix for home page pagination
				$page = get_query_var('page');
			} else {
				$page = 1;
			}

			$args = [
				'post_type' => $postType,
				'posts_per_page' => $postsToShow,
				'paged' => $page,
			];


			if (!empty($categories)) {
				$args['tax_query'] = [
					[
						'taxonomy' => $taxonomyType,
						'field' => 'term_id',
						'terms' => $categories,
					],
				];
			}
			if (!empty($_GET['tax']) && !empty($_GET['categ'])) {
				$taxonomy = $_GET['tax'];
				$term_slug = $_GET['categ'];
				$taxonomies = get_object_taxonomies($postType, 'objects');
				//				print_r($taxonomies);
				//				exit;
				if (array_key_exists($taxonomy, $taxonomies)) {
					$args['tax_query'] = [
						[
							'taxonomy' => $taxonomy,
							'field' => 'slug',
							'terms' => $term_slug,
						],
					];
				}
			}
			return new WP_Query($args);
		}

		public static function get_default_typography_attributes(
			$theme_default = ''
		) {
			return [
				'type' => 'theme',
				'theme' => $theme_default,
				'fontFamily' => 'Open Sans',
				'fontWeight' => 'regular',
				'fontSubset' => 'latin',
				'fontSize' => 16,
				'lineHeight' => 1,
				'letterSpacing' => 0,
			];
		}

		/*create a similar method than the above, but extended*/
		public static function get_default_typography_attributes_extended(
			$default = []
		) {
			return shortcode_atts(
				[
					'type' => 'theme',
					'theme' => '',
					'fontFamily' => 'Open Sans',
					'fontWeight' => 'regular',
					'fontSubset' => 'latin',
					'fontSize' => 16,
					'lineHeight' => 1,
					'letterSpacing' => 0,
				],
				$default
			);
		}

		public static function load_google_fonts($typographies)
		{
			foreach ($typographies as $typography) {
				//print_r($typography);
				if (
					(isset($typography['type']) && $typography['type'] == 'custom') ||
					!self::is_flex_builder_enabled()
				) {
					$url =
						'https://fonts.googleapis.com/css?family=' .
						$typography['fontFamily'] .
						':' .
						$typography['fontWeight'];
					if (!empty($typography['fontSubset'])) {
						$url .= '&subset=' . $typography['fontSubset'];
					}
					wp_enqueue_style('google-fonts-' . md5($url), $url, FALSE);
				}
			}
		}

		public static function get_style_for_typography($prefix, $typography)
		{
			$style = '';

			if (
				(isset($typography['type']) && $typography['type'] == 'custom') ||
				!self::is_flex_builder_enabled()
			) {
				//	var_dump($typography['fontWeight']);
				if ($typography['fontWeight'] != '') {
					if (strpos($typography['fontWeight'], 'italic') !== FALSE) {
						$style .= '--' . $prefix . '-font-style : italic;';
						$style .=
							'--' .
							$prefix .
							'-font-weight : ' .
							str_replace('italic', '', $typography['fontWeight']) .
							';';
					} else {
						$style .= '--' . $prefix . '-font-style : normal;';
						$style .=
							'--' .
							$prefix .
							'-font-weight : ' .
							$typography['fontWeight'] .
							';';
					}
				}

				$style .=
					'--' . $prefix . '-font-family : ' . $typography['fontFamily'] . ';';
				$style .=
					'--' . $prefix . '-line-height : ' . $typography['lineHeight'] . ';';
				$style .=
					'--' .
					$prefix .
					'-font-size : ' .
					Flo_Guten_Blocks_Helper::get_em_by_value($typography['fontSize']) .
					';';
				$style .=
					'--' .
					$prefix .
					'-letter-spacing : ' .
					$typography['letterSpacing'] .
					'em;';
			}
			return $style;
		}
		public static function getDataFontForTypography($typography)
		{
			return self::is_flex_builder_enabled() && $typography['type'] == 'theme'
				? $typography['theme']
				: '';
		}
		public static function get_em_by_value($value)
		{
			return $value / 16 . 'em';
		}
		public static function get_additional_class($attributes = [])
		{
			$additional_classes = [];

			if (isset($attributes['hideOnDesktop']) && $attributes['hideOnDesktop']) {
				$additional_classes[] = 'flo-block--hide-on-desktop';
			}
			if (isset($attributes['hideOnMobile']) && $attributes['hideOnMobile']) {
				$additional_classes[] = 'flo-block--hide-on-mobile';
			}

			return implode(' ', $additional_classes);
		}
		public static function get_not_found_message()
		{
			return '
			<h1>Not Found.</h1>
			<br>
			<h3>We couldn\'t find what you were looking for.</h3>
			<br>
			<a href="' .
				site_url() .
				'"> Check out Our Home Page </a>
			';
		}
		public static function is_flex_builder_enabled()
		{
			return class_exists('Flo_Flex_Builder') ? TRUE : FALSE;
		}

		/**
		 * ONLY for PRONTO theme
		 * Check if there are Gallery posts with _post_image_gallery
		 * This is used by the Gallery block in order to show or hide the Images Source option
		 *
		 * @return array
		 */
		public static function get_galleries_with_meta_images()
		{
			$gallery_ids = [];
			$current_theme = wp_get_theme();

			// this should return true only for Pronto theme by flothemes.
			if (!wp_doing_ajax() && $current_theme->get('Author') == 'Flothemes' && strpos($current_theme->get('Name'), 'Pronto') != -1) {

				// We will use a custom SQL query: using inner Join on meta table and retrieve the meta data in the same query.
				// we are doing that to optimize the number of SQL queries
				global $wpdb;
				$posts_table = "{$wpdb->prefix}posts";
				$post_meta_table = "{$wpdb->prefix}postmeta";

				$sql = " 	SELECT p.ID, p.post_title, m.meta_value as meta
									FROM `$posts_table` as p
									INNER JOIN `$post_meta_table` as m
										ON p.ID = m.post_id
											AND m.meta_key = '_post_image_gallery'
									WHERE p.post_type = 'gallery'
									Order by	p.post_date desc	";

				$results = $wpdb->get_results($sql, ARRAY_A);

				if (is_array($results) && sizeof($results)) {
					foreach ($results as $post) {
						$gallery_ids[] = ['label' => $post['post_title'], 'value' => (int)$post['ID'], 'meta' => maybe_unserialize($post['meta'])];
					}
				}
			}

			return $gallery_ids;
		}

		/**
		 * Returns Current Archives Page Title
		 * @param string $title_placeholder
		 *
		 * @return string
		 */
		public static function get_archives_title($title_placeholder)
		{
			global $wp_query;

			$tax = $wp_query->get_queried_object();

			if ($tax) { // only if we are on a taxonomy page
				$tax_name = $tax->taxonomy;
				$taxit = get_taxonomy($tax_name);
				$tax_label = $taxit->labels->singular_name;
				$archives_title = str_replace('%Term_Title%', single_term_title('', FALSE), $title_placeholder);
				$archives_title = str_replace('%Taxonomy%', $tax_label, $archives_title);

				return $archives_title;
			} else {
				return get_the_archive_title();
			}
		}

		/**
		 * get the listing category taking into account the GET paramater if available
		 * @param array $post_terms
		 * @return object|null
		 */
		public static function getListingCategory($post_id, $taxonomyType)
		{
			// category
			//
			// gallery-category
			// gallery-tag

			$post_terms = wp_get_post_terms($post_id, $taxonomyType);

			if (isset($_GET['tax']) && isset($_GET['categ'])) {
				$term_slug = $_GET['categ'];
			} elseif (is_category()) {
				$term = get_queried_object();
				$term_slug = $term->slug;
			} elseif (is_tag()) {
				$term = get_queried_object();
				$term_slug = $term->slug;
			}

			if (isset($term_slug) && is_array($post_terms) && sizeof($post_terms)) {
				foreach ($post_terms as $term) {
					if ($term->slug === $term_slug) {
						return $term;
					}
				}
			}


			if (is_array($post_terms) && isset($post_terms[0])) {
				return $post_terms[0];
			}

			return NULL;
		}
	}
}
