<?php
namespace PowerpackElements\Modules\Posts\Widgets;

use PowerpackElements\Base\Powerpack_Widget;
use PowerpackElements\Modules\Posts\Module;
use PowerpackElements\Modules\Posts\Traits\Posts_Query_Controls;
use PowerpackElements\Classes\PP_Posts_Query_Builder;

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

/**
 * Posts Grid Widget
 */
abstract class Posts_Base extends Powerpack_Widget {

	use Posts_Query_Controls;

	/**
	 * WP_Query
	 *
	 * @var $query
	 */
	protected $query         = null;
	protected $query_filters = null;

	protected $_has_template_content = false; // phpcs:ignore

	/**
	 * Retrieve posts grid widget icon.
	 *
	 * @access public
	 *
	 * @return string Widget icon.
	 */
	public function get_icon() {
		return 'eicon-posts-group power-pack-admin-icon';
	}

	protected function is_dynamic_content(): bool {
		return true;
	}

	/**
	 * Default query options, shared by query_posts() and query_posts_args().
	 *
	 * @since 3.0.1
	 * @access private
	 *
	 * @param array $overrides Options to override, e.g. [ 'paged' => true ].
	 *
	 * @return array Defaults.
	 */
	private function get_query_arg_defaults( $overrides = [] ) {
		return array_merge(
			[
				'filter'            => '',
				'taxonomy_filter'   => '',
				'search'            => '',
				'all_posts'         => false,
				'paged'             => false,
				'widget_type'       => 'posts',
				'old_code'          => false,
				'posts_count_var'   => '',
				'posts_count'       => 0,
				'posts_filter_keys' => [],
				'no_found_rows'     => false,
			],
			$overrides
		);
	}

	/**
	 * Normalise the query options into the names PP_Posts_Query_Builder uses.
	 *
	 * Accepts the named-options array that query_posts() and query_posts_args()
	 * now take, and still understands the legacy positional signature so the
	 * skins — and any third-party code — keep working.
	 *
	 * @since 3.0.1
	 * @access private
	 *
	 * @param array|string $args        Named options, or the first positional argument.
	 * @param array        $positional  The caller's func_get_args().
	 * @param array        $legacy_keys Option name for each positional slot. A null entry
	 *                                  marks a slot the legacy method ignored.
	 * @param array        $defaults    Option defaults for the calling method.
	 *
	 * @return array Normalised options.
	 */
	private function normalize_query_args( $args, $positional, $legacy_keys, $defaults ) {
		if ( ! is_array( $args ) ) {
			$named = [];

			foreach ( $positional as $index => $value ) {
				if ( ! empty( $legacy_keys[ $index ] ) ) {
					$named[ $legacy_keys[ $index ] ] = $value;
				}
			}

			$args = $named;
		}

		// Posts_Base called this 'taxonomy'; the builder calls it 'taxonomy_filter'.
		if ( isset( $args['taxonomy'] ) && ! isset( $args['taxonomy_filter'] ) ) {
			$args['taxonomy_filter'] = $args['taxonomy'];
		}

		$args = wp_parse_args( $args, $defaults );

		// The legacy signature spelled the booleans 'yes'/''.
		$args['all_posts'] = ( 'yes' === $args['all_posts'] || true === $args['all_posts'] );
		$args['old_code']  = ( 'yes' === $args['old_code'] || true === $args['old_code'] );
		$args['paged']     = ( 'yes' === $args['paged'] || true === $args['paged'] );

		return $args;
	}

	/**
	 * Get post query arguments.
	 *
	 * @access public
	 *
	 * @param array|string $args {
	 *     Query options. Named keys are passed straight through to
	 *     PP_Posts_Query_Builder::build(); see that method for the full list.
	 *
	 *     @type string $filter            Taxonomy term slug for runtime filtering.
	 *     @type string $taxonomy_filter   Taxonomy slug paired with $filter.
	 *     @type string $search            Search string.
	 *     @type bool   $all_posts         Leave posts_per_page at -1.
	 *     @type bool   $paged             Resolve the current page via get_paged().
	 *     @type string $widget_type       Used in the ppe_{widget_type}_query_args filter.
	 *     @type bool   $old_code          Legacy category/tag control names.
	 *     @type string $posts_count_var   Settings key holding posts-per-page.
	 *     @type int    $posts_count       Explicit posts-per-page override.
	 *     @type array  $posts_filter_keys Per-post-type include/exclude settings keys.
	 *     @type bool   $no_found_rows     Skip the found-rows count.
	 * }
	 * @return array WP_Query arguments.
	 */
	public function query_posts_args( $args = [] ) {
		$args = $this->normalize_query_args(
			$args,
			func_get_args(),
			[ 'filter', 'taxonomy_filter', 'search', 'all_posts', 'paged', 'widget_type', 'old_code', 'posts_count_var', 'posts_count' ],
			$this->get_query_arg_defaults()
		);

		$args['paged']                  = $args['paged'] ? $this->get_paged() : '';
		$args['related_fallback_query'] = $this->get_query();

		return PP_Posts_Query_Builder::build( $this->get_settings_for_display(), $args );
	}

	/**
	 * pre_get_posts_query_filter
	 *
	 * @param  mixed $wp_query
	 */
	public function pre_get_posts_query_filter( $wp_query ) {
		$settings = $this->get_settings_for_display();

		$query_id = $settings['query_id'];
		/**
		 * Query args.
		 *
		 * It allows developers to alter individual posts widget queries.
		 *
		 * The dynamic portion of the hook name '$query_id', refers to the Query ID.
		 *
		 * @since 1.4.11.3
		 *
		 * @param \WP_Query     $wp_query
		 */
		do_action_deprecated( "pp_query_{$query_id}", [ $wp_query ], '2.3.7', "powerpack/query/{$query_id}" );
		do_action( "powerpack/query/{$query_id}", $wp_query, $this );

	}

	/**
	 * Run the widget's post query.
	 *
	 * Builds the arguments, applies the query_id hook around the WP_Query, and
	 * registers the results with the avoid-duplicates list. The query itself is
	 * run through PP_Posts_Query_Builder::run(), which handles the offset.
	 *
	 * @access public
	 *
	 * @param array|string $args Query options; see query_posts_args(). Pagination is
	 *                           resolved by default, so 'paged' rarely needs setting.
	 *
	 * @return void
	 */
	public function query_posts( $args = [] ) {
		$args = $this->normalize_query_args(
			$args,
			func_get_args(),
			// Slots 4 and 5 are null because this method has always ignored the
			// positional $all_posts and $paged_args and forced its own values.
			[ 'filter', 'taxonomy_filter', 'search', null, null, 'widget_type', 'old_code', 'posts_count_var', 'posts_count' ],
			$this->get_query_arg_defaults( [ 'paged' => true ] )
		);

		$settings = $this->get_settings_for_display();
		$query_id = $settings['query_id'];

		if ( ! empty( $query_id ) ) {
			add_action( 'pre_get_posts', array( $this, 'pre_get_posts_query_filter' ) );
		}
		$query_args = $this->query_posts_args( $args );

		$this->query = PP_Posts_Query_Builder::run( $query_args );

		remove_action( 'pre_get_posts', array( $this, 'pre_get_posts_query_filter' ) );

		Module::add_to_avoid_list( wp_list_pluck( $this->query->posts, 'ID' ) );
	}

	public function query_filters_posts( $filter = '', $taxonomy = '', $search = '' ) {
		$settings = $this->get_settings();
		$query_id = $settings['query_id'];

		if ( ! empty( $query_id ) ) {
			add_action( 'pre_get_posts', array( $this, 'pre_get_posts_query_filter' ) );
		}
		$query_filter_args   = $this->query_posts_args( [
			'filter'          => $filter,
			'taxonomy_filter' => $taxonomy,
			'search'          => $search,
			'all_posts'       => true,
			'paged'           => true,
		] );
		$this->query_filters = PP_Posts_Query_Builder::run( $query_filter_args );
		remove_action( 'pre_get_posts', array( $this, 'pre_get_posts_query_filter' ) );
	}

	/**
	 * Render current query.
	 *
	 * @since 1.7.0
	 * @access protected
	 */
	public function get_query() {

		return $this->query;
	}

	/**
	 * Render current query.
	 *
	 * @since 1.7.0
	 * @access protected
	 */
	public function get_query_filters() {

		return $this->query_filters;
	}

	/**
	 * Returns the paged number for the query.
	 *
	 * @since 1.7.0
	 * @return int
	 */
	public function get_paged() {
		$settings = $this->get_settings_for_display();

		global $wp_the_query, $paged;

		if ( isset( $settings['_skin'] ) ) {
			$skin_id         = $settings['_skin'];
			$pagination_ajax = ( 'yes' === $settings[ $skin_id . '_show_filters' ] || 'yes' === $settings[ $skin_id . '_show_ajax_search_form' ] ) ? 'yes' : $settings[ $skin_id . '_pagination_ajax' ];
			$pagination_type = $settings[ $skin_id . '_pagination_type' ];
		} else {
			$pagination_ajax = '';
			$pagination_type = '';
		}

		if ( isset( $_POST['ajax_for'] ) && 'timeline' === sanitize_key( wp_unslash( $_POST['ajax_for'] ) ) ) {
			$pagination_ajax = ( 'yes' === $settings['pagination_ajax'] ) ? $settings['pagination_ajax'] : '';
			$pagination_type = $settings['pagination_type'];
		}

		if ( 'yes' === $pagination_ajax || 'load_more' === $pagination_type || 'infinite' === $pagination_type ) {
			if ( isset( $_POST['nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'pp-posts-widget-nonce' ) ) {
				if ( isset( $_POST['page_number'] ) && '' !== $_POST['page_number'] ) {
					return absint( wp_unslash( $_POST['page_number'] ) );
				}
			}

			// Check the 'paged' query var.
			$paged_qv = $wp_the_query->get( 'paged' );

			if ( is_numeric( $paged_qv ) ) {
				return $paged_qv;
			}

			// Check the 'page' query var.
			$page_qv = $wp_the_query->get( 'page' );

			if ( is_numeric( $page_qv ) ) {
				return $page_qv;
			}

			// Check the $paged global?
			if ( is_numeric( $paged ) ) {
				return $paged;
			}

			return 0;
		} else {
			return max( 1, get_query_var( 'paged' ), get_query_var( 'page' ) );
		}
	}

	public function get_posts_nav_link( $page_limit = null ) {
		if ( ! $page_limit ) {
			$page_limit = $this->query->max_num_pages;
		}

		$return = array();

		$paged = $this->get_paged();

		$link_template     = '<a class="page-numbers %s" href="%s">%s</a>';
		$disabled_template = '<span class="page-numbers %s">%s</span>';

		if ( $paged > 1 ) {
			$next_page = intval( $paged ) - 1;
			if ( $next_page < 1 ) {
				$next_page = 1;
			}

			$return['prev'] = sprintf( $link_template, 'prev', $this->get_wp_link_page( $next_page ), $this->get_settings( 'pagination_prev_label' ) );
		} else {
			$return['prev'] = sprintf( $disabled_template, 'prev', $this->get_settings( 'pagination_prev_label' ) );
		}

		$next_page = intval( $paged ) + 1;

		if ( $next_page <= $page_limit ) {
			$return['next'] = sprintf( $link_template, 'next', $this->get_wp_link_page( $next_page ), $this->get_settings( 'pagination_next_label' ) );
		} else {
			$return['next'] = sprintf( $disabled_template, 'next', $this->get_settings( 'pagination_next_label' ) );
		}

		return $return;
	}

	private function get_wp_link_page( $i ) {
		if ( ! is_singular() || is_front_page() ) {
			return get_pagenum_link( $i );
		}

		// Based on wp-includes/post-template.php:957 `_wp_link_page`.
		global $wp_rewrite;
		$post       = get_post();
		$query_args = array();
		$url        = get_permalink();

		if ( $i > 1 ) {
			if ( '' === get_option( 'permalink_structure' ) || in_array( $post->post_status, array( 'draft', 'pending' ), true ) ) {
				$url = add_query_arg( 'page', $i, $url );
			} elseif ( get_option( 'show_on_front' ) === 'page' && (int) get_option( 'page_on_front' ) === $post->ID ) {
				$url = trailingslashit( $url ) . user_trailingslashit( "$wp_rewrite->pagination_base/" . $i, 'single_paged' );
			} else {
				$url = trailingslashit( $url ) . user_trailingslashit( $i, 'single_paged' );
			}
		}

		if ( is_preview() ) {
			if ( ( 'draft' !== $post->post_status ) && isset( $_GET['preview_id'], $_GET['preview_nonce'] ) ) { //phpcs:ignore
				$query_args['preview_id']    = wp_unslash( $_GET['preview_id'] ); //phpcs:ignore
				$query_args['preview_nonce'] = wp_unslash( $_GET['preview_nonce'] ); //phpcs:ignore
			}

			$url = get_preview_post_link( $post, $query_args, $url );
		}

		return $url;
	}

	/**
	 * Truncate the current post's excerpt to a word limit.
	 *
	 * Strips shortcode-style brackets and appends an ellipsis when truncated.
	 * An empty string is returned when $limit is 0.
	 *
	 * @since 3.0.0
	 *
	 * @param int $limit Maximum number of words.
	 *
	 * @return string Truncated post excerpt.
	 */
	protected function get_custom_post_excerpt( $limit ) {
		$limit = absint( $limit );

		if ( 0 === $limit ) {
			return '';
		}

		$excerpt = explode( ' ', get_the_excerpt(), $limit + 1 );

		if ( count( $excerpt ) > $limit ) {
			array_pop( $excerpt );
			$excerpt = implode( ' ', $excerpt ) . '...';
		} else {
			$excerpt = implode( ' ', $excerpt );
		}

		$excerpt = preg_replace( '/\[[^\]]*\]/', '', $excerpt );

		return $excerpt;
	}
}
