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

class EcafeHelper {

	private static $instance;

	public static function instanceFetch() {
		if ( ! isset( self::$instance ) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

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

	/**
	 * Get Number
	 */
	public static function getNumbers( $start = 0, $end = 10, $none = '' ) {
		$options = array();
		if ( ! empty( $none ) ) {
			$options[0] = esc_html__( 'None', 'essential-classy-addons-for-elementor' );
		}
		for ( $start;$start <= $end;$start++ ) {
				$options[ $start ] = $start;
		}
		return $options;
	}

	/**
	 * Get Template
	 */
	public static function getTemplates() {
		$EleTemplates = Elementor\Plugin::instance()->templates_manager->get_source( 'local' )->get_items();
		$types        = array();

		if ( empty( $EleTemplates ) ) {
			$options = array( '0' => esc_html__( 'No Templates Found.', 'essential-classy-addons-for-elementor' ) );
		} else {
			$options = array( '0' => esc_html__( 'Select Template', 'essential-classy-addons-for-elementor' ) );

			foreach ( $EleTemplates as $template ) {
				$options[ $template['template_id'] ] = $template['title'] . ' (' . $template['type'] . ')';
				$types[ $template['template_id'] ]   = $template['type'];
			}
		}

		return $options;
	}

	/**
	 * Get option
	 */
	public static function ecafeGetOption( $optionsType, $field ) {
		$ecafewidgetsPage = get_option( 'ecafe_widgets' );
		$postTypeOptions  = get_option( 'post_type_options' );
		$values           = '';
		if ( $optionsType == 'general' ) {
			if ( isset( $ecafewidgetsPage[ $field ] ) && ! empty( $ecafewidgetsPage[ $field ] ) ) {
				$values = $ecafewidgetsPage[ $field ];
			}
		}
		if ( $optionsType == 'post_type' ) {
			if ( isset( $postTypeOptions[ $field ] ) && ! empty( $postTypeOptions[ $field ] ) ) {
				$values = $postTypeOptions[ $field ];
			}
		}
		return $values;
	}

	/*html tag validate*/
	public static function html_tag_check_and_verify() {
		return array(
			'h1',
			'h2',
			'h3',
			'h4',
			'h5',
			'h6',
			'div',
			'a',
			'span',
			'p',
			'main',
			'nav',
			'section',
			'header',
			'footer',
			'article',
			'aside',
		);
	}

	public static function check_and_validate_html_tag( $chk_tag ) {
		return in_array( strtolower( $chk_tag ), self::html_tag_check_and_verify() ) ? $chk_tag : 'div';
	}

	/*get Style Loop List*/
	public static function getStyleLoop( $max = 5, $none = '', $loop = '' ) {
		$style = array();
		if ( $none == 'yes' ) {
			$style['none'] = esc_html__( 'None', 'essential-classy-addons-for-elementor' );
		}
		for ( $i = 1;$i <= $max;$i++ ) {
			$style[ 'style-' . $i ] = esc_html__( 'Style ', 'essential-classy-addons-for-elementor' ) . $i;
		}
		if ( $loop == 'yes' ) {
			$style['custom-template'] = esc_html__( 'Custom Template', 'essential-classy-addons-for-elementor' );
		}

		return $style;
	}

	public static function getListLayout() {
		return array(
			'grid'    => esc_html__( 'Grid', 'essential-classy-addons-for-elementor' ),
			'masonry' => esc_html__( 'Masonry', 'essential-classy-addons-for-elementor' ),
		);
	}

	public static function getResponsiveColumn() {
		return array(
			'100'       => esc_html__( '1', 'essential-classy-addons-for-elementor' ),
			'50'        => esc_html__( '2', 'essential-classy-addons-for-elementor' ),
			'33.3333'   => esc_html__( '3', 'essential-classy-addons-for-elementor' ),
			'25'        => esc_html__( '4', 'essential-classy-addons-for-elementor' ),
			'20'        => esc_html__( '5', 'essential-classy-addons-for-elementor' ),
			'16.666667' => esc_html__( '6', 'essential-classy-addons-for-elementor' ),
		);
	}

	public static function getHtmlTag( $linktag = '' ) {
		$tag = array(
			'h1'   => esc_html__( 'H1', 'essential-classy-addons-for-elementor' ),
			'h2'   => esc_html__( 'H2', 'essential-classy-addons-for-elementor' ),
			'h3'   => esc_html__( 'H3', 'essential-classy-addons-for-elementor' ),
			'h4'   => esc_html__( 'H4', 'essential-classy-addons-for-elementor' ),
			'h5'   => esc_html__( 'H5', 'essential-classy-addons-for-elementor' ),
			'h6'   => esc_html__( 'H6', 'essential-classy-addons-for-elementor' ),
			'span' => esc_html__( 'Span', 'essential-classy-addons-for-elementor' ),
			'p'    => esc_html__( 'P', 'essential-classy-addons-for-elementor' ),
			'div'  => esc_html__( 'Div', 'essential-classy-addons-for-elementor' ),
		);
		if ( ! empty( $linktag ) ) {
			$tag['a'] = esc_html__( 'a', 'essential-classy-addons-for-elementor' );
		}
		return $tag;
	}

	/* get Post Tyles List*/
	public static function getPostTypes() {
		$options   = array();
		$postTypes = get_post_types(
			array(
				'public'  => true,
				'show_ui' => true,
			),
			'objects'
		);

		$exclude = array( 'attachment', 'elementor_library' );

		foreach ( $postTypes  as $postType ) {

			if ( true === in_array( $postType->name, $exclude ) ) {
				continue;
			}

			$options[ $postType->name ] = $postType->label;
		}

		return $options;
	}

	/* get Taxonomy List*/
	public static function getTaxonomiesList() {
		$options  = array();
		$output   = 'objects'; // or names
		$operator = 'and'; // 'and' or 'or'

		$taxonomies = get_taxonomies(
			array(
				'public'  => true,
				'show_ui' => true,
			),
			$output,
			$operator
		);
		if ( $taxonomies ) {
			foreach ( $taxonomies  as $taxonomy ) {
				$options[ $taxonomy->name ] = $taxonomy->label;
			}
			return $options;
		}
	}

	/* Get Post Categories */
	public static function getTermsList( $taxonomy = 'category', $key = 'term_id' ) {
		$options = array();
		$terms   = get_terms(
			array(
				'taxonomy'   => $taxonomy,
				'hide_empty' => true,
			)
		);

		if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
			foreach ( $terms as $term ) {
				$options[ $term->{$key} ] = $term->name;
			}
		}

		return $options;
	}

	/*
	Get all Authors*/
	// public static function getAuthorsList() {
		// $users = get_users([
			// 'capability' => 'authors',
			// 'has_published_posts' => true,
			// 'fields' => [
				// 'ID',
				// 'display_name',
			// ],
		// ]);

		// if (!empty($users)) {
			// return wp_list_pluck($users, 'display_name', 'ID');
		// }

		// return [];
	// }

	public static function getOrderByArray() {
		$options = array(
			'none'          => esc_html__( 'None', 'essential-classy-addons-for-elementor' ),
			'menu_order'    => esc_html__( 'Default', 'essential-classy-addons-for-elementor' ),
			'ID'            => esc_html__( 'ID', 'essential-classy-addons-for-elementor' ),
			'author'        => esc_html__( 'Author', 'essential-classy-addons-for-elementor' ),
			'title'         => esc_html__( 'Title', 'essential-classy-addons-for-elementor' ),
			'name'          => esc_html__( 'Name (slug)', 'essential-classy-addons-for-elementor' ),
			'date'          => esc_html__( 'Date', 'essential-classy-addons-for-elementor' ),
			'modified'      => esc_html__( 'Modified', 'essential-classy-addons-for-elementor' ),
			'rand'          => esc_html__( 'Random', 'essential-classy-addons-for-elementor' ),
			'parent'        => esc_html__( 'Parent Id', 'essential-classy-addons-for-elementor' ),
			'comment_count' => esc_html__( 'Comment Count', 'essential-classy-addons-for-elementor' ),
		);
		ksort( $options );
		return $options;
	}

	public static function getOrderArray() {
		return array(
			'ASC'  => esc_html__( 'Ascending', 'essential-classy-addons-for-elementor' ),
			'DESC' => esc_html__( 'Descending', 'essential-classy-addons-for-elementor' ),
		);
	}

	public static function getLoadingOptions() {
		return array(
			'none'       => esc_html__( 'Select Options', 'essential-classy-addons-for-elementor' ),
			'pagination' => esc_html__( 'Pagination', 'essential-classy-addons-for-elementor' ),
			'load_more'  => esc_html__( 'Load More', 'essential-classy-addons-for-elementor' ),
			'lazy_load'  => esc_html__( 'Lazy Load', 'essential-classy-addons-for-elementor' ),
		);
	}

	public static function getQueryArgs( $settings = array(), $onLoad = false ) {

		$include_posts = ( $settings['postsInclude'] ) ? explode( ',', $settings['postsInclude'] ) : array();
		$exclude_posts = ( $settings['postsExclude'] ) ? explode( ',', $settings['postsExclude'] ) : array();

		if ( is_single() ) {
			$exclude_posts = array( get_the_ID() );
		}
		$query_args = array(
			'post_type'           => $settings['selectPostType'],
			'post_status'         => 'publish',
			'posts_per_page'      => ! empty( $onLoad ) ? $settings['loadMorePost'] : $settings['numberOfPosts'],
			'orderby'             => $settings['postsOrderBy'],
			'order'               => $settings['postsOrder'],
			'offset'              => ! empty( $onLoad ) ? $settings['offset'] : $settings['postsOffset'],
			'post__in'            => $include_posts,
			'post__not_in'        => $exclude_posts,
			'ignore_sticky_posts' => true,
		);

		$query_args['tax_query'] = array();

		if ( is_archive() ) {
			if ( is_category() ) {
				$query_args['tax_query'][] = array(
					'taxonomy' => 'category',
					'field'    => 'term_id',
					'terms'    => get_queried_object_id(),
				);
			} elseif ( is_tag() ) {
				$query_args['tax_query'][] = array(
					'taxonomy' => 'post_tag',
					'field'    => 'term_id',
					'terms'    => get_queried_object_id(),
				);
			} elseif ( is_tax() ) {
				$queried_object            = get_queried_object();
				$query_args['tax_query'][] = array(
					'taxonomy' => $queried_object->taxonomy,
					'field'    => 'term_id',
					'terms'    => $queried_object->term_id,
				);
			}
		} else {
			$setting_key = '';
			if ( $settings['selectPostType'] != 'post' ) {
				$setting_key = ! empty( $settings['taxonomyInclude'] ) ? explode( ',', $settings['taxonomyInclude'] ) : array();
			} elseif ( $settings['selectTaxonomy'] == 'category' ) {
				$setting_key = ! empty( $settings['postCategory'] ) ? $settings['postCategory'] : array();
			} elseif ( $settings['selectTaxonomy'] == 'post_tag' ) {
				$setting_key = ! empty( $settings['postTags'] ) ? $settings['postTags'] : array();
			}

			if ( ! empty( $setting_key ) ) {
				$query_args['tax_query'][] = array(
					'taxonomy' => $settings['selectTaxonomy'],
					'field'    => 'term_id',
					'terms'    => $setting_key,
				);
			}
		}

		if ( ! empty( $query_args['tax_query'] ) ) {
			$query_args['tax_query']['relation'] = 'AND';
		}

		return $query_args;
	}

	public static function getPostExcerpt( $limit ) {
		if ( method_exists( 'WPBMap', 'addAllMappedShortcodes' ) ) {
			WPBMap::addAllMappedShortcodes();
		}
			global $post;
			$excerpt = explode( ' ', get_the_excerpt(), $limit );
		if ( count( $excerpt ) >= $limit ) {
			array_pop( $excerpt );
			$excerpt = implode( ' ', $excerpt ) . '...';
		} else {
			$excerpt = implode( ' ', $excerpt );
		}
			$excerpt = preg_replace( '`[[^]]*]`', '', $excerpt );

		return $excerpt;
	}


	/*
	 * Post Pagination
	 */
	public static function post_pagination( $pages = '', $range = 4, $next = 'Next', $prev = 'Prev' ) {
		$showitems = ( $range * 2 ) + 1;

		global $paged;  // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
		if ( empty( $paged ) ) {
			$paged = 1;
		}

		if ( $pages == '' ) {
			global $wp_query;
			$pages = $wp_query->max_num_pages;
			if ( ! $pages ) {
				$pages = 1;
			}
		}

		if ( 1 != $pages ) {
			$paginate = '<div class="eca-paginate">';

			if ( $paged > 1 ) {
				$paginate .= "<a class='prev' href='" . get_pagenum_link( $paged - 1 ) . "'>" . esc_html( $prev ) . '</a>';
			}
			if ( get_previous_posts_link() ) {
				get_previous_posts_link( 'Prev' );
			}
			for ( $i = 1; $i <= $pages; $i++ ) {
				if ( 1 != $pages && ( ! ( $i >= $paged + $range + 1 || $i <= $paged - $range - 1 ) || $pages <= $showitems ) ) {
					$paginate .= ( $paged == $i ) ? '<span class="current">' . esc_html( $i ) . '</span>' : "<a href='" . get_pagenum_link( $i ) . "' class=\"inactive\">" . esc_html( $i ) . '</a>';
				}
			}
			if ( get_next_posts_link() ) {
				get_next_posts_link( 'Next', 1 );
			}
			if ( $paged < $pages ) {
				$paginate .= "<a class='next' href='" . get_pagenum_link( $paged + 1 ) . "'>" . esc_html( $next ) . '</a>';
			}
			$paginate .= "</div>\n";
			return $paginate;
		}
	}

	public static function ecGetAcfFields( $type = 'text' ) {
		$acfGet = array();
		if ( class_exists( 'ACF' ) ) {
			if ( function_exists( 'acf_get_field_groups' ) ) {
				$acfField = acf_get_field_groups();
			} else {
				$acfField = apply_filters( 'acf/get_field_groups', array() );
			}

			foreach ( $acfField as $fieldGroup ) {
				$key         = $fieldGroup['key'];
				$title       = $fieldGroup['title'];
				$ecAcfFields = array();
				if ( function_exists( 'acf_get_fields' ) ) {
					if ( isset( $fieldGroup['ID'] ) && ! empty( $fieldGroup['ID'] ) ) {
						$fields = acf_get_fields( $fieldGroup['ID'] );
					} else {
						$fields = acf_get_fields( $fieldGroup );
					}
				} else {
					$fields = apply_filters( 'acf/field_group/get_fields', array(), $fieldGroup['id'] );
				}

				foreach ( $fields as $acfField ) {
					if ( ! empty( $acfField['name'] ) && $acfField['type'] === $type ) {
						$ecAcfFields[ $acfField['name'] ] = $acfField['label'];
					}
				}
				$acfGet[] = array(
					'label'   => $title,
					'options' => $ecAcfFields,
				);
			}
		}
		return $acfGet;
	}

	public static function ecGetJetEngineFields( $type = 'text' ) {
		$jetEngineGet = array();
		if ( class_exists( 'Jet_Engine' ) ) {
			$ecJetRaw = jet_engine()->meta_boxes->data->raw;
			foreach ( $ecJetRaw as $field_group ) {
				$ecJetEngineGroup = array();
				foreach ( $field_group['meta_fields'] as $field ) {
					if ( ! empty( $field['name'] ) && $field['type'] == $type ) {
						$ecJetEngineGroup[ $field['name'] ] = $field['title'];
					}
				}
				if ( ! empty( $ecJetEngineGroup ) ) {
					$jetEngineGet[] = array(
						'label'   => $field_group['args']['name'],
						'options' => $ecJetEngineGroup,
					);
				}
			}
		}
		return $jetEngineGet;
	}

	public static function ecGetMetaBoxFields( $type = 'text' ) {
		$metaBoxGet = array();
		if ( class_exists( 'RWMB_Field' ) ) {
			$mbRegistry = (array) rwmb_get_registry( 'meta_box' )->all();
			foreach ( $mbRegistry as $metaField ) {
				$ecMetaFields = array();
				$metaBox      = (array) $metaField;
				$metaTitle    = $metaBox['meta_box']['title'];
				$metaField    = $metaBox['meta_box']['fields'];

				foreach ( $metaField as $field ) {
					if ( ! empty( $field['name'] ) && $field['type'] == $type ) {
						$ecMetaFields[ $field['id'] ] = $field['name'];
					}
				}
				$metaBoxGet[] = array(
					'label'   => $metaTitle,
					'options' => $ecMetaFields,
				);
			}
		}

		return $metaBoxGet;
	}

	public static function ecGetPodsFields( $type = 'text' ) {
		$podsGet = array();
		if ( class_exists( 'PodsInit' ) ) {
			$podsLoad = pods_api()->load_pods(
				array(
					'table_info' => true,
					'fields'     => true,
				)
			);
			if ( ! empty( $podsLoad ) ) {
				foreach ( $podsLoad as $group ) {
					$ecPodsField = array();
					if ( ! empty( $group['fields'] ) ) {
						foreach ( $group['fields'] as $field ) {
							if ( ! empty( $field['name'] ) && $field['type'] == $type ) {
								$ecPodsField[ $field['name'] ] = $field['label'];
							}
						}
					}

					if ( ! empty( $ecPodsField ) ) {
						$podsGet[] = array(
							'label'   => $group['label'],
							'options' => $ecPodsField,
						);
					}
				}
			}
		}
		return $podsGet;
	}

	public static function ecGetToolsetFields( $type = 'textfield' ) {
		$toolsetGet = array();
		if ( defined( 'WPCF_VERSION' ) ) {
			$groups = wpcf_admin_fields_get_groups();
			foreach ( $groups as $group ) {
				$ecToolsetField = array();
				if ( $group['slug'] !== 'toolset-woocommerce-fields' ) {
					$fields    = wpcf_admin_fields_get_fields_by_group( $group['id'] );
					$tooltitle = $group['name'];
					foreach ( $fields as $key => $value ) {
						if ( ! empty( $value['name'] ) && $value['type'] == $type ) {
							$ecToolsetField[ $value['id'] ] = $value['name'];
						}
					}
				}
				if ( ! empty( $ecToolsetField ) ) {
					$toolsetGet[] = array(
						'label'   => $tooltitle,
						'options' => $ecToolsetField,
					);
				}
			}
		}
		return $toolsetGet;
	}
}

EcafeHelper::instanceFetch();

function postsListingLoadMore() {
	ob_start();
	$settings = ( ! empty( $_POST['settings'] ) ) ? wp_unslash( $_POST['settings'] ) : '';
	$settings = json_decode( str_replace( '\"', '"', $settings ) );

	$selectTaxonomy         = isset( $settings->selectTaxonomy ) ? sanitize_text_field( wp_unslash( $settings->selectTaxonomy ) ) : '';
	$style                  = isset( $settings->style ) ? sanitize_text_field( wp_unslash( $settings->style ) ) : '';
	$showTitle              = isset( $settings->showTitle ) ? wp_unslash( $settings->showTitle ) : '';
	$titleTag               = isset( $settings->titleTag ) ? wp_unslash( $settings->titleTag ) : '';
	$titleLength            = isset( $settings->titleLength ) ? wp_unslash( $settings->titleLength ) : '';
	$showImage              = isset( $settings->showImage ) ? wp_unslash( $settings->showImage ) : '';
	$imageSize              = isset( $settings->imageSize ) ? wp_unslash( $settings->imageSize ) : '';
	$showExcerpt            = isset( $settings->showExcerpt ) ? wp_unslash( $settings->showExcerpt ) : '';
	$postExcerptLength      = isset( $settings->postExcerptLength ) ? wp_unslash( $settings->postExcerptLength ) : '';
	$showPostMeta           = isset( $settings->showPostMeta ) ? wp_unslash( $settings->showPostMeta ) : '';
	$postMetaStyle          = isset( $settings->postMetaStyle ) ? wp_unslash( $settings->postMetaStyle ) : '';
	$postDateMeta           = isset( $settings->postDateMeta ) ? wp_unslash( $settings->postDateMeta ) : '';
	$postUserMeta           = isset( $settings->postUserMeta ) ? wp_unslash( $settings->postUserMeta ) : '';
	$prefixTextPostUserMeta = isset( $settings->prefixTextPostUserMeta ) ? wp_unslash( $settings->prefixTextPostUserMeta ) : '';
	$filterPost             = isset( $settings->filterPost ) ? wp_unslash( $settings->filterPost ) : '';
	$readMoreButton         = isset( $settings->readMoreButton ) ? wp_unslash( $settings->readMoreButton ) : '';
	$buttonHoverEffectH     = ( isset( $settings->buttonHoverEffectH ) && $settings->buttonHoverEffectH == 'yes' ) ? wp_unslash( 'eca-button-hover-effect ' . $settings->buttonEffectPosH ) : '';
	$readButtonText         = isset( $settings->readButtonText ) ? sanitize_text_field( wp_unslash( $settings->readButtonText ) ) : '';
	$templateid             = isset( $settings->templateid ) ? wp_unslash( $settings->templateid ) : '';
	$selectPostType         = isset( $settings->selectPostType ) ? sanitize_text_field( wp_unslash( $settings->selectPostType ) ) : '';
	$loadMorePost           = ( isset( $settings->loadMorePost ) && intval( $settings->loadMorePost ) ) ? wp_unslash( $settings->loadMorePost ) : '';
	$postCategory           = isset( $settings->postCategory ) ? wp_unslash( $settings->postCategory ) : '';
	$offset                 = ( isset( $settings->offset ) && intval( $settings->offset ) ) ? wp_unslash( $settings->offset ) : '';
	$postsOrderBy           = isset( $settings->postsOrderBy ) ? sanitize_text_field( wp_unslash( $settings->postsOrderBy ) ) : '';
	$postsOrder             = isset( $settings->postsOrder ) ? sanitize_text_field( wp_unslash( $settings->postsOrder ) ) : '';

	$itemClass = '';
	$args      = \EcafeHelper::getQueryArgs( (array) $settings, true );

	$query = new WP_Query( $args );

	if ( $query->have_posts() ) {
		while ( $query->have_posts() ) {
			$query->the_post();
			include ECAFE_PATH . 'element/ajax-load/posts-listing.php';
		}
	}

	wp_reset_postdata();
	exit;
	ob_end_clean();
}
add_action( 'wp_ajax_eca_load_more_posts', 'postsListingLoadMore' );
add_action( 'wp_ajax_nopriv_eca_load_more_posts', 'postsListingLoadMore' );
