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

use PowerpackElements\Classes\PP_Posts_Helper;

use Elementor\Controls_Manager;

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

/**
 * Trait Posts_Query_Controls.
 *
 * Registers the shared "Query" section controls (post type, taxonomies,
 * authors, include/exclude, date, orderby, sticky, offset, query id, etc.)
 * used by posts-aware widgets. Consumed by Posts_Base today; available for
 * non-posts widgets that expose a "posts" data source.
 *
 * @since 2.13.0
 */
trait Posts_Query_Controls {

	/**
	 * Register the Query section controls on the using widget.
	 *
	 * Signature preserved from Posts_Base::register_query_section_controls()
	 * so existing callers continue to work unchanged.
	 *
	 * @since 2.13.0
	 *
	 * @param array  $condition         Elementor condition under which the section is shown.
	 * @param string $widget_type       Widget identifier used for filter hook namespacing.
	 * @param string $old_code          'yes' to preserve legacy category/tag control names.
	 * @param string $advanced_controls 'yes' to include the "Nothing Found" message controls.
	 * @param bool   $include_related   Whether to expose the "Related" post-type option and
	 *                                  its include/exclude/fallback controls. Default true.
	 * @param array  $posts_filter_keys Per-post-type overrides for the include/exclude posts
	 *                                  filter control ID. Example: [ 'post' => 'exclude_posts' ]
	 *                                  preserves a widget's legacy control name. Default [].
	 * @return void
	 */
	public function register_query_section_controls( $condition = [], $widget_type = 'posts', $old_code = '', $advanced_controls = 'no', $include_related = true, $posts_filter_keys = [] ) {
		$post_types = PP_Posts_Helper::get_post_types();

		/**
		 * Content Tab: Query
		 */
		$this->start_controls_section(
			'section_query',
			[
				'label'     => esc_html__( 'Query', 'powerpack' ),
				'condition' => $condition,
			]
		);

		$this->add_control(
			'query_type',
			[
				'label'   => esc_html__( 'Query Type', 'powerpack' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'custom',
				'options' => [
					'main'   => esc_html__( 'Main Query', 'powerpack' ),
					'custom' => esc_html__( 'Custom Query', 'powerpack' ),
				],
			]
		);

		$post_types = PP_Posts_Helper::get_post_types();

		if ( $include_related ) {
			$post_types['related'] = esc_html__( 'Related', 'powerpack' );
		}

		$this->add_control(
			'post_type',
			[
				'label'     => esc_html__( 'Post Type', 'powerpack' ),
				'type'      => Controls_Manager::SELECT,
				'options'   => $post_types,
				'default'   => 'post',
				'condition' => [
					'query_type' => 'custom',
				],
			]
		);

		foreach ( $post_types as $post_type_slug => $post_type_label ) {

			$taxonomy = PP_Posts_Helper::get_post_taxonomies( $post_type_slug );

			if ( ! empty( $taxonomy ) ) {

				foreach ( $taxonomy as $index => $tax ) {

					$terms = PP_Posts_Helper::get_tax_terms( $index );

					$tax_terms = [];

					if ( ! empty( $terms ) ) {

						foreach ( $terms as $term_index => $term_obj ) {

							$tax_terms[ $term_obj->term_id ] = $term_obj->name;
						}

						$tax_control_key = $index . '_' . $post_type_slug;

						if ( 'yes' === $old_code ) {
							if ( 'post' === $post_type_slug ) {
								if ( 'post_tag' === $index ) {
									$tax_control_key = 'tags';
								} elseif ( 'category' === $index ) {
									$tax_control_key = 'categories';
								}
							}
						}

						// Taxonomy filter type.
						$this->add_control(
							$index . '_' . $post_type_slug . '_filter_type',
							[
								/* translators: %s Label */
								'label'       => sprintf( esc_html__( '%s Filter Type', 'powerpack' ), $tax->label ),
								'type'        => Controls_Manager::SELECT,
								'default'     => 'IN',
								'label_block' => true,
								'options'     => [
									/* translators: %s label */
									'IN'     => sprintf( esc_html__( 'Include %s', 'powerpack' ), $tax->label ),
									/* translators: %s label */
									'NOT IN' => sprintf( esc_html__( 'Exclude %s', 'powerpack' ), $tax->label ),
								],
								'separator'   => 'before',
								'condition'   => [
									'query_type' => 'custom',
									'post_type'  => $post_type_slug,
								],
							]
						);

						$this->add_control(
							$tax_control_key,
							[
								'label'        => $tax->label,
								'type'         => 'pp-query',
								'post_type'    => $post_type_slug,
								'options'      => [],
								'label_block'  => true,
								'multiple'     => true,
								'query_type'   => 'terms',
								'object_type'  => $index,
								'include_type' => true,
								'condition'    => [
									'query_type' => 'custom',
									'post_type'  => $post_type_slug,
								],
							]
						);

					}
				}
			}
		}

		$this->add_control(
			'author_filter_type',
			[
				'label'       => esc_html__( 'Authors Filter Type', 'powerpack' ),
				'type'        => Controls_Manager::SELECT,
				'default'     => 'author__in',
				'label_block' => true,
				'separator'   => 'before',
				'options'     => [
					'author__in'     => esc_html__( 'Include Authors', 'powerpack' ),
					'author__not_in' => esc_html__( 'Exclude Authors', 'powerpack' ),
				],
				'condition'   => [
					'query_type' => 'custom',
					'post_type!' => 'related',
				],
			]
		);

		$this->add_control(
			'authors',
			[
				'label'       => esc_html__( 'Authors', 'powerpack' ),
				'type'        => 'pp-query',
				'label_block' => true,
				'multiple'    => true,
				'query_type'  => 'authors',
				'condition'   => [
					'query_type' => 'custom',
					'post_type!' => 'related',
				],
			]
		);

		foreach ( $post_types as $post_type_slug => $post_type_label ) {
			$this->add_control(
				$post_type_slug . '_filter_type',
				[
					/* translators: %s: post type label */
					'label'       => sprintf( esc_html__( '%s Filter Type', 'powerpack' ), $post_type_label ),
					'type'        => Controls_Manager::SELECT,
					'default'     => 'post__not_in',
					'label_block' => true,
					'separator'   => 'before',
					'options'     => [
						/* translators: %s: post type label */
						'post__in'     => sprintf( esc_html__( 'Include %s', 'powerpack' ), $post_type_label ),
						/* translators: %s: post type label */
						'post__not_in' => sprintf( esc_html__( 'Exclude %s', 'powerpack' ), $post_type_label ),
					],
					'condition'   => [
						'query_type' => 'custom',
						'post_type'  => $post_type_slug,
					],
				]
			);

			$posts_filter_control_id = isset( $posts_filter_keys[ $post_type_slug ] )
				? $posts_filter_keys[ $post_type_slug ]
				: $post_type_slug . '_filter';

			$this->add_control(
				$posts_filter_control_id,
				[
					/* translators: %s Label */
					'label'       => $post_type_label,
					'type'        => 'pp-query',
					'default'     => '',
					'multiple'    => true,
					'label_block' => true,
					'query_type'  => 'posts',
					'object_type' => $post_type_slug,
					'condition'   => [
						'query_type' => 'custom',
						'post_type'  => $post_type_slug,
					],
				]
			);
		}

		$taxonomy   = PP_Posts_Helper::get_post_taxonomies( $post_type_slug );
		$taxonomies = [];
		foreach ( $taxonomy as $index => $tax ) {
			$taxonomies[ $tax->name ] = $tax->label;
		}

		if ( $include_related ) {
			$this->start_controls_tabs(
				'tabs_related',
				[
					'condition' => [
						'query_type' => 'custom',
						'post_type'  => 'related',
					],
				]
			);

			$this->start_controls_tab(
				'tab_related_include',
				[
					'label'     => esc_html__( 'Include', 'powerpack' ),
					'condition' => [
						'query_type' => 'custom',
						'post_type'  => 'related',
					],
				]
			);

			$this->add_control(
				'related_include_by',
				[
					'label'       => esc_html__( 'Include By', 'powerpack' ),
					'type'        => Controls_Manager::SELECT2,
					'default'     => '',
					'label_block' => true,
					'multiple'    => true,
					'options'     => [
						'terms'   => esc_html__( 'Term', 'powerpack' ),
						'authors' => esc_html__( 'Author', 'powerpack' ),
					],
					'condition'   => [
						'query_type' => 'custom',
						'post_type'  => 'related',
					],
				]
			);

			$this->add_control(
				'related_filter_include',
				[
					'label'       => esc_html__( 'Term', 'powerpack' ),
					'type'        => Controls_Manager::SELECT2,
					'default'     => '',
					'label_block' => true,
					'multiple'    => true,
					'options'     => PP_Posts_Helper::get_taxonomies_options(),
					'condition'   => [
						'query_type'         => 'custom',
						'post_type'          => 'related',
						'related_include_by' => 'terms',
					],
				]
			);

			$this->end_controls_tab();

			$this->start_controls_tab(
				'tab_related_exclude',
				[
					'label'     => esc_html__( 'Exclude', 'powerpack' ),
					'condition' => [
						'query_type' => 'custom',
						'post_type'  => 'related',
					],
				]
			);

			$this->add_control(
				'related_exclude_by',
				[
					'label'       => esc_html__( 'Exclude By', 'powerpack' ),
					'type'        => Controls_Manager::SELECT2,
					'default'     => '',
					'label_block' => true,
					'multiple'    => true,
					'options'     => [
						'current_post' => esc_html__( 'Current Post', 'powerpack' ),
						'authors'      => esc_html__( 'Author', 'powerpack' ),
					],
					'condition'   => [
						'query_type' => 'custom',
						'post_type'  => 'related',
					],
				]
			);

			$this->end_controls_tab();
			$this->end_controls_tabs();

			$this->add_control(
				'related_fallback',
				[
					'label'       => esc_html__( 'Fallback', 'powerpack' ),
					'description' => esc_html__( 'Displayed if no relevant results are found.', 'powerpack' ),
					'type'        => Controls_Manager::SELECT,
					'options'     => [
						'none'   => esc_html__( 'None', 'powerpack' ),
						'recent' => esc_html__( 'Recent Posts', 'powerpack' ),
					],
					'default'     => 'none',
					'label_block' => false,
					'separator'   => 'before',
					'condition'   => [
						'query_type' => 'custom',
						'post_type'  => 'related',
					],
				]
			);
		}

		$this->add_control(
			'select_date',
			[
				'label'       => esc_html__( 'Date', 'powerpack' ),
				'type'        => Controls_Manager::SELECT,
				'options'     => [
					'anytime' => esc_html__( 'All', 'powerpack' ),
					'today'   => esc_html__( 'Past Day', 'powerpack' ),
					'week'    => esc_html__( 'Past Week', 'powerpack' ),
					'month'   => esc_html__( 'Past Month', 'powerpack' ),
					'quarter' => esc_html__( 'Past Quarter', 'powerpack' ),
					'year'    => esc_html__( 'Past Year', 'powerpack' ),
					'exact'   => esc_html__( 'Custom', 'powerpack' ),
				],
				'default'     => 'anytime',
				'label_block' => false,
				'multiple'    => false,
				'separator'   => 'before',
				'condition'   => [
					'query_type' => 'custom',
				],
			]
		);

		$this->add_control(
			'date_before',
			[
				'label'       => esc_html__( 'Before', 'powerpack' ),
				'description' => esc_html__( 'Setting a ‘Before’ date will show all the posts published until the chosen date (inclusive).', 'powerpack' ),
				'type'        => Controls_Manager::DATE_TIME,
				'label_block' => false,
				'multiple'    => false,
				'placeholder' => esc_html__( 'Choose', 'powerpack' ),
				'condition'   => [
					'query_type'  => 'custom',
					'select_date' => 'exact',
				],
			]
		);

		$this->add_control(
			'date_after',
			[
				'label'       => esc_html__( 'After', 'powerpack' ),
				'description' => esc_html__( 'Setting an ‘After’ date will show all the posts published since the chosen date (inclusive).', 'powerpack' ),
				'type'        => Controls_Manager::DATE_TIME,
				'label_block' => false,
				'multiple'    => false,
				'placeholder' => esc_html__( 'Choose', 'powerpack' ),
				'condition'   => [
					'query_type'  => 'custom',
					'select_date' => 'exact',
				],
			]
		);

		$this->add_control(
			'order',
			[
				'label'     => esc_html__( 'Order', 'powerpack' ),
				'type'      => Controls_Manager::SELECT,
				'options'   => [
					'DESC' => esc_html__( 'Descending', 'powerpack' ),
					'ASC'  => esc_html__( 'Ascending', 'powerpack' ),
				],
				'default'   => 'DESC',
				'separator' => 'before',
				'condition' => [
					'query_type' => 'custom',
				],
			]
		);

		$this->add_control(
			'orderby',
			[
				'label'     => esc_html__( 'Order By', 'powerpack' ),
				'type'      => Controls_Manager::SELECT,
				'options'   => [
					'date'          => esc_html__( 'Date', 'powerpack' ),
					'modified'      => esc_html__( 'Last Modified Date', 'powerpack' ),
					'rand'          => esc_html__( 'Random', 'powerpack' ),
					'comment_count' => esc_html__( 'Comment Count', 'powerpack' ),
					'title'         => esc_html__( 'Title', 'powerpack' ),
					'ID'            => esc_html__( 'Post ID', 'powerpack' ),
					'author'        => esc_html__( 'Post Author', 'powerpack' ),
					'menu_order'    => esc_html__( 'Menu Order', 'powerpack' ),
					'relevance'     => esc_html__( 'Relevance', 'powerpack' ),
				],
				'default'   => 'date',
				'condition' => [
					'query_type' => 'custom',
				],
			]
		);

		$this->add_control(
			'sticky_posts',
			[
				'label'        => esc_html__( 'Sticky Posts', 'powerpack' ),
				'type'         => Controls_Manager::SWITCHER,
				'default'      => '',
				'label_on'     => esc_html__( 'Yes', 'powerpack' ),
				'label_off'    => esc_html__( 'No', 'powerpack' ),
				'return_value' => 'yes',
				'separator'    => 'before',
				'condition'    => [
					'query_type' => 'custom',
				],
			]
		);

		$this->add_control(
			'all_sticky_posts',
			[
				'label'        => esc_html__( 'Show Only Sticky Posts', 'powerpack' ),
				'type'         => Controls_Manager::SWITCHER,
				'default'      => '',
				'label_on'     => esc_html__( 'Yes', 'powerpack' ),
				'label_off'    => esc_html__( 'No', 'powerpack' ),
				'return_value' => 'yes',
				'condition'    => [
					'query_type'   => 'custom',
					'sticky_posts' => 'yes',
				],
			]
		);

		$this->add_control(
			'offset',
			[
				'label'       => esc_html__( 'Offset', 'powerpack' ),
				'description' => esc_html__( 'Use this setting to skip this number of initial posts', 'powerpack' ),
				'type'        => Controls_Manager::NUMBER,
				'default'     => '',
				'min'         => 0,
				'condition'   => [
					'query_type' => 'custom',
					'post_type!' => 'related',
				],
			]
		);

		$this->add_control(
			'exclude_current',
			[
				'label'        => esc_html__( 'Exclude Current Post', 'powerpack' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'powerpack' ),
				'label_off'    => esc_html__( 'No', 'powerpack' ),
				'return_value' => 'yes',
				'default'      => '',
				'description'  => esc_html__( 'Enable this option to remove current post from the query.', 'powerpack' ),
				'condition'    => [
					'query_type' => 'custom',
				],
			]
		);

		$this->add_control(
			'avoid_duplicates',
			[
				'label'       => esc_html__( 'Avoid Duplicates', 'powerpack' ),
				'type'        => Controls_Manager::SWITCHER,
				'default'     => '',
				'description' => esc_html__( 'Set to Yes to avoid duplicate posts from showing up on the page. This only affects the frontend.', 'powerpack' ),
				'condition'   => [
					'query_type' => 'custom',
				],
			]
		);

		$this->add_control(
			'query_id',
			[
				'label'       => esc_html__( 'Query ID', 'powerpack' ),
				'description' => esc_html__( 'Give your Query a custom unique id to allow server side filtering', 'powerpack' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => '',
				'ai'          => [
					'active' => false,
				],
				'separator'   => 'before',
			]
		);

		if ( 'yes' === $advanced_controls ) {
			$this->add_control(
				'heading_nothing_found',
				[
					'label'     => esc_html__( 'If Nothing Found!', 'powerpack' ),
					'type'      => Controls_Manager::HEADING,
					'separator' => 'before',
				]
			);

			$this->add_control(
				'nothing_found_message',
				[
					'label'   => esc_html__( 'Nothing Found Message', 'powerpack' ),
					'type'    => Controls_Manager::TEXTAREA,
					'rows'    => 3,
					'default' => esc_html__( 'It seems we can\'t find what you\'re looking for.', 'powerpack' ),
				]
			);

			$this->add_control(
				'show_search_form',
				[
					'label'        => esc_html__( 'Show Search Form', 'powerpack' ),
					'type'         => Controls_Manager::SWITCHER,
					'label_on'     => esc_html__( 'Yes', 'powerpack' ),
					'label_off'    => esc_html__( 'No', 'powerpack' ),
					'return_value' => 'yes',
					'default'      => '',
				]
			);
		}

		$this->end_controls_section();
	}
}
