<?php
defined( 'ABSPATH' ) || exit;

/**
 * Checks if shortcode has load more.
 */
function vcex_shortcode_has_loadmore( $atts, $vcex_query ) {
	$check = false;
	if ( vcex_validate_att_boolean( 'pagination_loadmore', $atts ) && ! empty( $vcex_query->max_num_pages ) ) {
		$check = true;
	}
	return $check;
}

/**
 * Check if we are currently loading new posts.
 */
function vcex_doing_loadmore() {
	if ( wp_doing_ajax() && isset( $_REQUEST['action'] ) && 'vcex_loadmore_ajax_render' == $_REQUEST['action'] ) {
		return true;
	}
	return false;
}

/**
 * Load More Scripts.
 */
function vcex_loadmore_scripts() {
	$dependencies = array(
		'jquery',
		'imagesloaded'
	);

	if ( defined( 'WPEX_THEME_JS_HANDLE' ) ) {
		$dependencies[] = WPEX_THEME_JS_HANDLE;
	}

	if ( apply_filters( 'vcex_loadmore_enqueue_mediaelement', false ) ) {
		wp_enqueue_style( 'wp-mediaelement' );
		wp_enqueue_script( 'wp-mediaelement' );
	}

	// Enqueue load more script.
	wp_enqueue_script(
		'vcex-loadmore',
		vcex_asset_url( 'js/vcex-loadmore.min.js' ),
		$dependencies,
		TTC_VERSION,
		true
	);

	// Localize load more script.
	wp_localize_script(
		'vcex-loadmore',
		'vcex_loadmore_params',
		array(
			'ajax_url' => set_url_scheme( admin_url( 'admin-ajax.php' ) ),
		)
	);
}

/**
 * Load More Button.
 */
function vcex_get_loadmore_button( $shortcode_tag, $atts, $query, $infinite_scroll = false ) {
	$page         = get_query_var( 'paged' ) ?: 1;
	$max_pages    = $query->max_num_pages;
	$vc_is_inline = vcex_vc_is_inline();

	// No need for load more if we already reached the last page.
	if ( $page >= $max_pages || ( $infinite_scroll && $vc_is_inline ) ) {
		return;
	}

	// Remove useless attributes.
	unset( $atts['wrap_css'] );
	unset( $atts['show_categories_tax'] );

	if ( ! in_array( $shortcode_tag, array( 'vcex_post_type_archive', 'vcex_post_type_grid', 'vcex_recent_news' ) ) ) {
		unset( $atts['post_type'] );
		unset( $atts['taxonomy'] );
	}

	// Add query vars for auto_query.
	if ( vcex_validate_att_boolean( 'auto_query', $atts ) ) {
		$atts['query_vars'] = wp_json_encode( $query->query_vars );
	}

	// Define load more text.
	$loadmore_text = esc_html__( 'Load More', 'total-theme-core' );
	$loading_text  = esc_html__( 'Loading&hellip;', 'total-theme-core' );
	$failed_text   = esc_html__( 'Failed to load posts.', 'total-theme-core' );

	if ( is_callable( array( 'TotalTheme\Pagination\Load_More', 'get_more_text' ) ) ) {
		$loadmore_text = TotalTheme\Pagination\Load_More::get_more_text();
	}

	if ( is_callable( array( 'TotalTheme\Pagination\Load_More', 'get_loading_text' ) ) ) {
		$loading_text = TotalTheme\Pagination\Load_More::get_loading_text();
	}

	if ( is_callable( array( 'TotalTheme\Pagination\Load_More', 'get_failed_text' ) ) ) {
		$failed_text = TotalTheme\Pagination\Load_More::get_failed_text();
	}

	// Create array of load more settings to be added to the button data.
	$settings = array(
		'class'           => 'vcex-loadmore-button theme-button',
		'text'            => $loadmore_text,
		'loading_text'    => $loading_text,
		'failed_text'     => $failed_text,
		'infinite_scroll' => $infinite_scroll,
	);

	if ( is_callable( array( 'TotalTheme\Pagination\Load_More', 'get_loader_svg_html' ) ) ) {
		$settings['svg'] = TotalTheme\Pagination\Load_More::get_loader_svg_html();
	} else {
		$settings['gif'] = includes_url( 'images/spinner-2x.gif' );
	}

	// old filter - @todo deprecate.
	$settings = (array) apply_filters( 'vcex_get_loadmore_button_settings', $settings, $shortcode_tag, $atts );

	/**
	 * Filters the vcex load more button settings.
	 *
	 * @param array $settings
	 * @param string $shortcode_tag
	 * @param array $shortcode_attributes
	 */
	$settings = (array) apply_filters( 'vcex_loadmore_button_settings', $settings, $shortcode_tag, $atts );

	// Check if infinite scroll is enabled.
	$has_infinite_scroll = wp_validate_boolean( $settings['infinite_scroll'] ?? false );

	if ( $vc_is_inline && $has_infinite_scroll  ) {
		return;
	}

	// Load more classes.
	$loadmore_classes = array(
		'vcex-loadmore',
		'wpex-clear',
		'wpex-text-center',
	);

	if ( 'wpex_post_cards' == $shortcode_tag ) {
		$loadmore_classes[] = 'wpex-mt-30';
	} else {
		$loadmore_classes[] = 'wpex-mt-10';
	}

	if ( $has_infinite_scroll ) {
		$loadmore_classes[] = 'vcex-loadmore--infinite-scroll wpex-invisible';
	}

	/**
	 * Filters the vcex load more button class.
	 *
	 * @param array $classes
	 * @param string $shortcode_tag
	 * @param array $shortcode_attributes
	 */
	$loadmore_classes = (array) apply_filters( 'vcex_loadmore_class', $loadmore_classes, $shortcode_tag, $atts );

	// Return load more button.
	$button = '<div class="' . esc_attr( implode( ' ', $loadmore_classes ) ) . '">';

		$button_class = $settings['class'] ?? '';

		if ( $has_infinite_scroll ) {
			if ( is_string( $button_class ) ) {
				$button_class .= ' wpex-h-1px';
			} else {
				$button_class[] = 'wpex-h-1px';
			}
		}

		$btn_attr = array(
			'href'                  => '#',
			'class'                 => esc_attr( $button_class ),
			'data-infinite-scroll'  => (int) $has_infinite_scroll,
			'data-page'             => esc_attr( $page ),
			'data-max-pages'        => esc_attr( $max_pages ),
			'data-text'             => esc_attr( $settings['text'] ),
			'data-loading-text'     => esc_attr( $settings['loading_text'] ),
			'data-failed-text'      => esc_attr( $settings['failed_text'] ),
			'data-nonce'            => esc_attr( wp_create_nonce( 'vcex-ajax-pagination-nonce' ) ),
			'data-shortcode-tag'    => esc_attr( $shortcode_tag ),
			'data-shortcode-params' => esc_attr( wp_json_encode( $atts, false ) ), // changed from htmlspecialchars to esc_attr in v 5.0
		);

		$button .= '<a';
			foreach ( $btn_attr as $name => $value_escaped ) {
	            $button .= ' ' . $name . '="' .  $value_escaped . '"';
	        }
		$button .= '>';

			$button_text_allowed_tags = array(
				'img'  => array(
					'src' => array(),
					'alt' => array(),
				),
				'span' => array(
					'class' => array(),
				),
			);

			/**
			 * Filters the allowed tags for the vcex load more button text.
			 *
			 * @param array $allowed_tags
			 */
			$button_text_allowed_tags = apply_filters( 'vcex_loadmore_button_text_allowed_tags', $button_text_allowed_tags );

			$button .= '<span class="vcex-txt">' . wp_kses( $settings['text'], $button_text_allowed_tags ) . '</span>';

		$button .= '</a>';

		// Spinner.
		if ( $has_infinite_scroll ) {
			$spinner_class = 'vcex-spinner wpex-invisible wpex-opacity-0';
		} else {
			$spinner_class = 'vcex-spinner wpex-hidden';
		}
		if ( ! empty( $settings['gif'] ) ) {
			$button .= '<img src="' . esc_url( $settings['gif'] ) . '" class="' . $spinner_class . ' wpex-opacity-40" alt="' . esc_attr( $settings['loading_text'] ) . '" height="20" width="20">';
		} elseif ( ! empty( $settings['svg'] ) ) {
			$button .= '<div class="' . $spinner_class . '">' . $settings['svg'] . '</div>';
		}

	$button .= '</div>';

	return $button;
}

/**
 *  Load More AJAX.
 */
function vcex_loadmore_ajax_render() {
	check_ajax_referer( 'vcex-ajax-pagination-nonce', 'nonce' );

	if ( empty( $_POST['shortcodeParams'] ) ) {
		wp_die();
	}

	$allowed_shortcodes = array(
		'vcex_blog_grid',
		'vcex_image_grid',
		'vcex_portfolio_grid',
		'vcex_post_type_archive',
		'vcex_post_type_grid',
		'vcex_recent_news',
		'vcex_staff_grid',
		'vcex_testimonials_grid',
		'wpex_post_cards',
	);

	if ( empty( $_POST[ 'shortcodeTag' ] ) || ! in_array( $_POST['shortcodeTag'], $allowed_shortcodes ) ) {
		wp_die();
	}

	if ( class_exists( 'WPBMap' ) ) {
		WPBMap::addAllMappedShortcodes(); // fix for WPBakery not working in ajax
	}

	$tag    = wp_strip_all_tags( $_POST['shortcodeTag'] );
	$params = (array) $_POST[ 'shortcodeParams' ];

	$data = wp_send_json_success( vcex_do_shortcode_function( $tag, $params ) );

	wp_send_json_success( $data );

	wp_die();
}
add_action( 'wp_ajax_vcex_loadmore_ajax_render', 'vcex_loadmore_ajax_render' );
add_action( 'wp_ajax_nopriv_vcex_loadmore_ajax_render', 'vcex_loadmore_ajax_render' );