<?php
/**
 * BricksExtras Query Loop Enhancements
 *
 * Extends Bricks query loop functionality with additional features.
 *
 * @package BricksExtras
 */

namespace BricksExtras;

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

if ( class_exists( 'BricksExtrasQueryLoop' ) ) {
	return;
}

/**
 * Class for extending Bricks query loop with custom controls and functionality.
 */
class BricksExtrasQueryLoop {

	/**
	 * Option prefix.
	 *
	 * @var string
	 */
	public static string $prefix = '';

	/**
	 * Initialize query loop extras.
	 *
	 * @param string $prefix Option prefix.
	 * @return void
	 */
	public function init( $prefix ) {

		self::$prefix = $prefix;

		add_action( 'init', array( $this, 'add_query_loop_extras_controls' ), 40 );
		add_filter( 'bricks/setup/control_options', array( $this, 'setup_query_loop_extras_controls' ) );
		add_filter( 'bricks/query/run', array( $this, 'run_query_loop_extras' ), 10, 2 );
		add_filter( 'bricks/query/loop_object', array( $this, 'extras_setup_post_data' ), 10, 3 );

		// Pagination filters for query loop (Bricks v2.2+).
		if ( method_exists( '\Bricks\Helpers', 'get_ajax_current_page' ) ) {
			add_filter( 'bricks/pagination/custom_logic', array( $this, 'pagination_custom_logic' ), 10, 3 );
			add_filter( 'bricks/pagination/current_page', array( $this, 'pagination_current_page' ), 10, 3 );
			add_filter( 'bricks/pagination/total_pages', array( $this, 'pagination_total_pages' ), 10, 3 );
		}

		// Add filter to display menu item IDs in WordPress admin.
		if ( is_admin() ) {
			add_action( 'wp_nav_menu_item_custom_fields', array( $this, 'display_menu_item_id' ), 10, 1 );
		}
	}

	/**
	 * Add query loop extras controls to elements.
	 *
	 * @return void
	 */
	public function add_query_loop_extras_controls() {

		$elements = array(
			'container',
			'block',
			'div',
			'xdynamictable',
		);

		foreach ( $elements as $element ) {
			add_filter( "bricks/elements/{$element}/controls", array( $this, 'query_loop_extras_controls' ), 40 );
		}
	}



	/**
	 * Add query loop extras controls to elements.
	 *
	 * @param array $controls Existing element controls.
	 * @return array Modified controls array.
	 */
	public function query_loop_extras_controls( $controls ) {

		$new_controls = array();

		$taxonomies = \Bricks\Setup::$control_options['taxonomies'];
		unset( $taxonomies['Wp_template_part'] );

			$extras_query_options = array(
				'adjacent' => esc_html__( 'Adjacent Posts', 'bricksextras' ),
				'gallery'  => esc_html__( 'Gallery', 'bricksextras' ),
				'related'  => esc_html__( 'Related Posts', 'bricksextras' ),
				'wpmenu'   => esc_html__( 'WP Menu', 'bricksextras' ),
			);

			if ( get_option( self::$prefix . 'favorite' ) ) {
				$extras_query_options['favorite'] = 'Favorites';
			}

			$new_controls['extrasQuery'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Query type', 'bricks' ),
				'type'        => 'select',
				'inline'      => true,
				'options'     => $extras_query_options,
				'placeholder' => esc_html__( 'Select option', 'bricks' ),
				'required'    => array(
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
				'rerender'    => true,
				'multiple'    => false,
			);

			/* adjacentPost */

			$new_controls['adjacentPost'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Adjacent Post', 'bricksextras' ),
				'type'        => 'select',
				'inline'      => true,
				'options'     => array(
					'prev' => esc_html__( 'Previous', 'bricks' ),
					'next' => esc_html__( 'Next', 'bricks' ),
				),
				'placeholder' => esc_html__( 'Previous', 'bricks' ),
				'required'    => array(
					array( 'extrasQuery', '=', 'adjacent' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
				'rerender'    => true,
				'multiple'    => false,
			);

			$new_controls['adjacentPostSameTerm'] = array(
				'tab'      => 'content',
				'label'    => esc_html__( 'Post should be in the same taxonomy term', 'bricksextras' ),
				'type'     => 'checkbox',
				'rerender' => true,
				'required' => array(
					array( 'extrasQuery', '=', 'adjacent' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['adjacentTaxonomy'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Taxonomy', 'bricks' ),
				'type'        => 'select',
				'options'     => $taxonomies,
				'multiple'    => false,
				'description' => esc_html__( 'Taxonomy adjacent posts must have in common.', 'bricksextras' ),
				'placeholder' => array(
					'category',
				),
				'required'    => array(
					array( 'extrasQuery', '=', 'adjacent' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
					array( 'adjacentPostSameTerm', '=', true ),
				),
			);

			$new_controls['adjacentPostExcludedTerms'] = array(
				'tab'      => 'content',
				'label'    => esc_html__( 'Excluded Term IDs', 'bricksextras' ),
				'type'     => 'text',
				'required' => array(
					array( 'extrasQuery', '=', 'adjacent' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
					array( 'adjacentPostSameTerm', '=', true ),
				),
			);

			$new_controls['adjacentPostCount'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Number of posts', 'bricks' ),
				'type'        => 'number',
				'min'         => 1,
				'max'         => 10,
				'placeholder' => 1,
				'small'       => true,
				'required'    => array(
					array( 'extrasQuery', '=', 'adjacent' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['adjacentPostOrderby'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Adjacent Post Order', 'bricksextras' ),
				'type'        => 'select',
				'options'     => array(
					'date'       => esc_html__( 'Published date', 'bricks' ),
					'modified'   => esc_html__( 'Modified date', 'bricks' ),
					'menu_order' => esc_html__( 'Menu order', 'bricks' ),
					'ID'         => esc_html__( 'ID', 'bricks' ),
					'title'      => esc_html__( 'Title', 'bricks' ),
				),
				'inline'      => true,
				'placeholder' => esc_html__( 'Published date', 'bricks' ),
				'required'    => array(
					array( 'extrasQuery', '=', 'adjacent' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['adjacentPostOrder'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Order', 'bricks' ),
				'type'        => 'select',
				'options'     => array(
					'ASC'  => esc_html__( 'Ascending', 'bricks' ),
					'DESC' => esc_html__( 'Descending', 'bricks' ),
				),
				'inline'      => true,
				'placeholder' => esc_html__( 'Ascending', 'bricks' ),
				'required'    => array(
					array( 'extrasQuery', '=', 'adjacent' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'adjacentPostCount', '!=', array( 1, '' ) ),
					array( 'hasLoop', '!=', false ),
				),
			);

			/* related posts */

			$post_type_options        = bricks_is_builder() ? \Bricks\Helpers::get_registered_post_types() : array();
			$post_type_options['any'] = esc_html__( 'Any', 'bricks' );

			$new_controls['post_type'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Post type', 'bricks' ),
				'type'        => 'select',
				'options'     => $post_type_options,
				'clearable'   => true,
				'inline'      => true,
				'searchable'  => true,
				'placeholder' => esc_html__( 'Default', 'bricks' ),
				'required'    => array(
					array( 'extrasQuery', '=', array( 'related', 'favorite' ) ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['count'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Max. related posts', 'bricks' ),
				'type'        => 'number',
				'min'         => 1,
				'max'         => 4,
				'placeholder' => 3,
				'required'    => array(
					array( 'extrasQuery', '=', 'related' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['order'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Order', 'bricks' ),
				'type'        => 'select',
				'options'     => array(
					'ASC'  => esc_html__( 'Ascending', 'bricks' ),
					'DESC' => esc_html__( 'Descending', 'bricks' ),
				),
				'inline'      => true,
				'placeholder' => esc_html__( 'Descending', 'bricks' ),
				'required'    => array(
					array( 'extrasQuery', '=', 'related' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['orderby'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Order by', 'bricks' ),
				'type'        => 'select',
				'options'     => \Bricks\Setup::$control_options['queryOrderBy'],
				'inline'      => true,
				'placeholder' => esc_html__( 'Random', 'bricks' ),
				'required'    => array(
					array( 'extrasQuery', '=', 'related' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['taxonomies'] = array(
				'tab'      => 'content',
				'label'    => esc_html__( 'Common taxonomies', 'bricks' ),
				'type'     => 'select',
				'options'  => $taxonomies,
				'multiple' => true,
				'default'  => array(
					'category',
					'post_tag',
				),
				'required' => array(
					array( 'extrasQuery', '=', 'related' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			/* wpmenu */

			$nav_menus = array();

			if ( bricks_is_builder() ) {
				foreach ( wp_get_nav_menus() as $menu ) {
					$nav_menus[ $menu->term_id ] = $menu->name;
				}
			}

			$new_controls['menuSource'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Source', 'bricks' ),
				'type'        => 'select',
				'options'     => array(
					'dropdown' => esc_html__( 'Select option', 'bricks' ),
					'dynamic'  => esc_html__( 'Dynamic data', 'bricks' ),
				),
				'inline'      => true,
				'clearable'   => false,
				'placeholder' => esc_html__( 'Select option', 'bricks' ),
				'required'    => array(
					array( 'extrasQuery', '=', 'wpmenu' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['x_menu_id'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Menu name, menu slug or menu ID', 'bricksextras' ),
				'type'        => 'text',
				'description' => sprintf( '<a href="' . admin_url( 'nav-menus.php' ) . '" target="_blank">' . esc_html__( 'Manage my menus in WordPress.', 'bricks' ) . '</a>' ),
				'required'    => array(
					array( 'extrasQuery', '=', 'wpmenu' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'menuSource', '=', 'dynamic' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['menu'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Select Menu..', 'bricksextras' ),
				'type'        => 'select',
				'options'     => $nav_menus,
				'placeholder' => esc_html__( 'Select nav menu', 'bricks' ),
				'description' => sprintf( '<a href="' . admin_url( 'nav-menus.php' ) . '" target="_blank">' . esc_html__( 'Manage my menus in WordPress.', 'bricks' ) . '</a>' ),
				'required'    => array(
					array( 'extrasQuery', '=', 'wpmenu' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'menuSource', '!=', 'dynamic' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['x_menu_filter_type'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Menu Items Filter', 'bricksextras' ),
				'type'        => 'select',
				'options'     => array(
					'all'      => esc_html__( 'All Items', 'bricksextras' ),
					'top'      => esc_html__( 'Top Level Items Only', 'bricksextras' ),
					'children' => esc_html__( 'Child Items of Parent', 'bricksextras' ),
				),
				'inline'      => true,
				'placeholder' => esc_html__( 'All Items', 'bricksextras' ),
				'required'    => array(
					array( 'extrasQuery', '=', 'wpmenu' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['x_menu_parent_id'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Parent Menu Item ID', 'bricksextras' ),
				'type'        => 'text',
				'inline'      => true,
				'description' => sprintf(
					/* translators: %s: placeholder for menu item ID */
					esc_html__( 'Use %s for current menu ID if inside menu query.', 'bricksextras' ),
					'{x_menu_item_id}'
				),
				'required'    => array(
					array( 'extrasQuery', '=', 'wpmenu' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'x_menu_filter_type', '=', 'children' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			/* favorites */

			$new_controls['x_favorites_orderby'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Order by', 'bricks' ),
				'type'        => 'select',
				'inline'      => true,
				'options'     => array(
					'post__in'       => esc_html__( 'As added to list', 'bricks' ),
					'none'           => esc_html__( 'None', 'bricks' ),
					'ID'             => esc_html__( 'ID', 'bricks' ),
					'author'         => esc_html__( 'Author', 'bricks' ),
					'title'          => esc_html__( 'Title', 'bricks' ),
					'date'           => esc_html__( 'Published date', 'bricks' ),
					'modified'       => esc_html__( 'Modified date', 'bricks' ),
					'rand'           => esc_html__( 'Random', 'bricks' ),
					'meta_value'     => esc_html__( 'Meta value', 'bricks' ),
					'meta_value_num' => esc_html__( 'Meta numeric value', 'bricks' ),
				),
				'placeholder' => esc_html__( 'Added to list', 'bricksextras' ),
				'required'    => array(
					array( 'extrasQuery', '=', 'favorite' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['x_favorites_meta_key'] = array(
				'type'           => 'text',
				'label'          => esc_html__( 'Meta Key', 'bricks' ),
				'hasDynamicData' => false,
				'inline'         => true,
				'required'       => array(
					array( 'extrasQuery', '=', 'favorite' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
					array( 'x_favorites_orderby', '=', array( 'meta_value', 'meta_value_num' ) ),
				),
			);

			$new_controls['x_favorites_order'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Order', 'bricks' ),
				'type'        => 'select',
				'inline'      => true,
				'options'     => array(
					'ASC'  => esc_html__( 'Ascending', 'bricks' ),
					'DESC' => esc_html__( 'Descending', 'bricks' ),
				),
				'placeholder' => esc_html__( 'Ascending', 'bricks' ),
				'required'    => array(
					array( 'extrasQuery', '=', 'favorite' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['x_newList_separator'] = array(
				'tab'      => 'content',
				'type'     => 'separator',
				'required' => array(
					array( 'extrasQuery', '=', 'favorite' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['newList'] = array(
				'tab'      => 'content',
				'type'     => 'checkbox',
				'label'    => esc_html__( 'Custom list', 'bricksextras' ),
				'required' => array(
					array( 'extrasQuery', '=', 'favorite' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['listSlug'] = array(
				'tab'      => 'content',
				'label'    => esc_html__( 'List Indentifier', 'bricksextras' ),
				'type'     => 'text',
				'inline'   => true,
				'required' => array(
					array( 'extrasQuery', '=', 'favorite' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
					array( 'newList', '=', true ),
				),
			);

			/* gallery */

			$new_controls['x_gallery_data'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Gallery', 'bricks' ),
				'type'        => 'text',
				'inline'      => true,
				'placeholder' => esc_html__( 'Dynamic Data', 'bricks' ),
				'required'    => array(
					array( 'extrasQuery', '=', 'gallery' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['x_gallery_orderby'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Order by', 'bricks' ),
				'type'        => 'select',
				'inline'      => true,
				'options'     => array(
					'post__in' => esc_html__( 'Default', 'bricks' ),
					'date'     => esc_html__( 'Published date', 'bricks' ),
					'modified' => esc_html__( 'Modified date', 'bricks' ),
					'ID'       => esc_html__( 'ID', 'bricks' ),
					'author'   => esc_html__( 'Author', 'bricks' ),
					'title'    => esc_html__( 'Title', 'bricks' ),
					'rand'     => esc_html__( 'Random', 'bricks' ),
				),
				'placeholder' => esc_html__( 'Default', 'bricks' ),
				'required'    => array(
					array( 'extrasQuery', '=', 'gallery' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['x_gallery_order'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Order', 'bricks' ),
				'type'        => 'select',
				'inline'      => true,
				'options'     => array(
					'ASC'  => esc_html__( 'Ascending', 'bricks' ),
					'DESC' => esc_html__( 'Descending', 'bricks' ),
				),
				'placeholder' => esc_html__( 'Ascending', 'bricks' ),
				'required'    => array(
					array( 'extrasQuery', '=', 'gallery' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
					array( 'x_gallery_orderby', '!=', array( 'post__in', '' ) ),
				),
			);

			$new_controls['x_gallery_offset'] = array(
				'tab'         => 'content',
				'label'       => esc_html__( 'Offset', 'bricks' ),
				'type'        => 'number',
				'units'       => false,
				'inline'      => true,
				'placeholder' => '0',
				'required'    => array(
					array( 'extrasQuery', '=', 'gallery' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			$new_controls['x_gallery_max'] = array(
				'tab'      => 'content',
				'label'    => esc_html__( 'Maximum', 'bricks' ) . ' (' . esc_html__( 'Images', 'bricks' ) . ')',
				'type'     => 'number',
				'units'    => false,
				'inline'   => true,
				'required' => array(
					array( 'extrasQuery', '=', 'gallery' ),
					array( 'query.objectType', '=', 'queryLoopExtras' ),
					array( 'hasLoop', '!=', false ),
				),
			);

			if ( method_exists( '\Bricks\Helpers', 'get_ajax_current_page' ) ) {
				$new_controls['x_gallery_per_page'] = array(
					'tab'         => 'content',
					'label'       => esc_html__( 'Items per page', 'bricks' ),
					'type'        => 'number',
					'units'       => false,
					'inline'      => true,
					'placeholder' => '',
					'required'    => array(
						array( 'extrasQuery', '=', 'gallery' ),
						array( 'query.objectType', '=', 'queryLoopExtras' ),
						array( 'hasLoop', '!=', false ),
					),
				);
			}

			$query_key_index = absint( array_search( 'query', array_keys( $controls ), true ) );
			$new_controls    = array_slice( $controls, 0, $query_key_index + 1, true ) + $new_controls + array_slice( $controls, $query_key_index + 1, null, true );

			return $new_controls;
	}

	/**
	 * Setup query loop extras controls.
	 *
	 * @param array $control_options Control options.
	 * @return array Modified control options.
	 */
	public function setup_query_loop_extras_controls( $control_options ) {

		$control_options['queryTypes']['queryLoopExtras'] = esc_html__( 'Extras', 'bricksextras' );
		return $control_options;
	}

	/**
	 * Run query loop extras functionality.
	 *
	 * @param array  $results   Query results.
	 * @param object $query_obj Query object.
	 * @return array Modified query results.
	 */
	public function run_query_loop_extras( $results, $query_obj ) {

		if ( 'queryLoopExtras' !== $query_obj->object_type ) {
			return $results;
		}

		$settings = $query_obj->settings;

		if ( ! $settings['hasLoop'] ) {
			return array();
		}

		$extras_query = isset( $settings['extrasQuery'] ) ? $settings['extrasQuery'] : false;

		if ( 'adjacent' === $extras_query ) {

			/* adjacent posts */

			$adjacent_post           = isset( $settings['adjacentPost'] ) ? $settings['adjacentPost'] : 'prev';
			$adjacent_post_same_term = isset( $settings['adjacentPostSameTerm'] );
			$excluded_terms          = isset( $settings['adjacentPostExcludedTerms'] ) ? $settings['adjacentPostExcludedTerms'] : '';
			$adjacent_taxonomy       = isset( $settings['adjacentTaxonomy'] ) ? $settings['adjacentTaxonomy'] : 'category';
			$adjacent_post_count     = isset( $settings['adjacentPostCount'] ) ? intval( $settings['adjacentPostCount'] ) : 1;
			$adjacent_post_orderby   = isset( $settings['adjacentPostOrderby'] ) ? $settings['adjacentPostOrderby'] : 'date';
			$adjacent_post_order     = isset( $settings['adjacentPostOrder'] ) ? $settings['adjacentPostOrder'] : 'ASC';

			// Only use WordPress's built-in functions when count=1 AND orderby=date.
			// For all other cases (including menu_order), use our custom function.
			if ( $adjacent_post_count <= 1 && 'date' === $adjacent_post_orderby ) {
				// For a single adjacent post with date ordering, WordPress's built-in functions work well.
				if ( 'prev' === $adjacent_post && ! empty( get_previous_post( $adjacent_post_same_term, $excluded_terms, $adjacent_taxonomy ) ) ) {
					return array( get_previous_post( $adjacent_post_same_term, $excluded_terms, $adjacent_taxonomy ) );
				}

				if ( 'next' === $adjacent_post && ! empty( get_next_post( $adjacent_post_same_term, $excluded_terms, $adjacent_taxonomy ) ) ) {
					return array( get_next_post( $adjacent_post_same_term, $excluded_terms, $adjacent_taxonomy ) );
				}
			}

			// For all other cases (multiple posts or non-date ordering), use our custom query.
			return $this->get_multiple_adjacent_posts(
				$adjacent_post,
				$adjacent_post_count,
				$adjacent_post_same_term,
				$excluded_terms,
				$adjacent_taxonomy,
				$adjacent_post_orderby,
				$adjacent_post_order
			);

		} elseif ( 'related' === $extras_query ) {

			/* related posts */

			global $post;

			$post_id = isset( $post ) && $post ? $post->ID : get_the_ID();

			if ( ! $post_id ) {
				$post_id = 0;
			}

			$args = array(
				'posts_per_page' => isset( $settings['count'] ) ? intval( $settings['count'] ) : 3,
				'post__not_in'   => array( $post_id ),
				'no_found_rows'  => true, // No pagination.
				'orderby'        => isset( $settings['orderby'] ) ? $settings['orderby'] : 'rand',
				'order'          => isset( $settings['order'] ) ? $settings['order'] : 'DESC',
			);

			if ( ! empty( $settings['post_type'] ) ) {
				$args['post_type'] = $settings['post_type'];
			}

			$taxonomies = ! empty( $settings['taxonomies'] ) ? $settings['taxonomies'] : array();

			foreach ( $taxonomies as $taxonomy ) {
				$terms_ids = wp_get_post_terms(
					$post_id,
					$taxonomy,
					array( 'fields' => 'ids' )
				);

				if ( ! empty( $terms_ids ) ) {
					$args['tax_query'][] = array(
						'taxonomy' => $taxonomy,
						'field'    => 'term_id',
						'terms'    => $terms_ids,
					);
				}
			}

			if ( count( $taxonomies ) > 1 && isset( $args['tax_query'] ) ) {
				$args['tax_query']['relation'] = 'OR';
			}

			$args['post_status'] = 'publish';

			$posts_query = new \WP_Query( $args );

			return $posts_query->posts;

		} elseif ( 'wpmenu' === $extras_query ) {

			$menu_source = isset( $settings['menuSource'] ) ? $settings['menuSource'] : 'dropdown';
			$menu        = isset( $settings['menu'] ) ? intval( $settings['menu'] ) : false;
			$menu_id     = isset( $settings['x_menu_id'] ) ? bricks_render_dynamic_data( $settings['x_menu_id'] ) : false;

			$final_menu_id = 'dropdown' === $menu_source ? $menu : $menu_id;

			return ! $final_menu_id ? array() : $this->x_nav_menu_query( $query_obj, $final_menu_id, $settings );

		} elseif ( 'favorite' === $extras_query ) {

			$post_type = ! empty( $settings['post_type'] ) ? $settings['post_type'] : 'post';

			$favorites_order_by = isset( $settings['x_favorites_orderby'] ) ? $settings['x_favorites_orderby'] : 'post__in';
			$favorites_order    = isset( $settings['x_favorites_order'] ) ? $settings['x_favorites_order'] : 'ASC';

			$args = array(
				'post_type'      => $post_type,
				'post_status'    => array( 'publish', 'inherit' ),
				'posts_per_page' => -1,
				'orderby'        => $favorites_order_by,
				'order'          => $favorites_order,
				'cache_results'  => false,
				'meta_key'       => isset( $settings['x_favorites_meta_key'] ) ? $settings['x_favorites_meta_key'] : '',
			);

			if ( 'attachment' === $post_type ) {
				$args['post_mime_type'] = 'image';
				$args['post_status']    = 'inherit';
			}

			$list_slug = ! empty( $settings['listSlug'] ) ? $settings['listSlug'] : false;

			if ( (bool) $list_slug && isset( $settings['newList'] ) ) {

				$list_slug = strtolower( $list_slug );                     // Convert to lowercase.
				$list_slug = preg_replace( '/\s+/', '_', $list_slug );      // Replace spaces with underscores.
				$suffix    = preg_replace( '/[^a-z0-9_]/', '', $list_slug );    // Remove characters that are not letters, numbers, or underscores.

				if ( 'any' === $post_type ) {
					$post_type = 'custom';
				}

				$post__in = Helpers::get_favorite_ids_array( $post_type . '__' . $suffix );
			} else {
				$post__in = Helpers::get_favorite_ids_array( $post_type );
			}

			$post__in_value = is_array( $post__in ) && ! empty( $post__in ) ? $post__in : array( 0 );

			if ( 'post__in' === $favorites_order_by && 'DESC' === $favorites_order ) {
				$post__in_value = array_reverse( $post__in_value );
			}

			$args['post__in'] = $post__in_value;

			$posts_query = new \WP_Query( $args );

			$key = 'x_favorite_ids';

			// Add in_favorites_loop flag for posts in favorites loop, for 'in favorites loop' condition.
			foreach ( $posts_query->posts as $key => $favorite_post ) {
				$posts_query->posts[ $key ]->in_favorites_loop = true;
			}

			return is_array( $posts_query->posts ) ? $posts_query->posts : array();

		} elseif ( 'gallery' === $extras_query ) {

			$gallery_data = ! empty( $settings['x_gallery_data'] ) ? $settings['x_gallery_data'] : false;

			if ( ! $gallery_data ) {
				return array();
			}

			$post_id = isset( \Bricks\Database::$page_data['preview_or_post_id'] ) && isset( $settings['x_gallery_per_page'] ) ? \Bricks\Database::$page_data['preview_or_post_id'] : get_the_ID();

			$gallery_images = \Bricks\Integrations\Dynamic_Data\Providers::render_tag( $gallery_data, $post_id, 'image' );

			$x_gallery_orderby  = isset( $settings['x_gallery_orderby'] ) ? $settings['x_gallery_orderby'] : 'post__in';
			$x_gallery_order    = isset( $settings['x_gallery_order'] ) ? $settings['x_gallery_order'] : 'ASC';
			$x_gallery_offset   = isset( $settings['x_gallery_offset'] ) ? intval( $settings['x_gallery_offset'] ) : 0;
			$x_gallery_max      = isset( $settings['x_gallery_max'] ) ? intval( $settings['x_gallery_max'] ) : 999;
			$x_gallery_per_page = isset( $settings['x_gallery_per_page'] ) ? intval( $settings['x_gallery_per_page'] ) : 0;

			if ( ! is_array( $gallery_images ) || empty( $gallery_images ) ) {
				$post__in = array( 0 );
			} else {
				$post__in = $gallery_images;
			}

			// Check if pagination is available (Bricks v2.2+).
			if ( method_exists( '\Bricks\Helpers', 'get_ajax_current_page' ) && isset( $settings['x_gallery_per_page'] ) && $x_gallery_per_page > 0 ) {

				// For other orderby values, let WP_Query handle the ordering.
				if ( 'post__in' === $x_gallery_orderby ) {
					// Apply offset and maximum to the array before pagination (only for default order).
					if ( is_array( $post__in ) && array( 0 ) !== $post__in ) {
						// Apply offset first.
						if ( 0 < $x_gallery_offset ) {
							$post__in = array_slice( $post__in, $x_gallery_offset );
						}

						// Apply maximum limit.
						if ( $x_gallery_max > 0 && $x_gallery_max < 999 ) {
							$post__in = array_slice( $post__in, 0, $x_gallery_max );
						}
					}

					global $bricksextras_gallery_total_images;
					$bricksextras_gallery_total_images = count( $post__in );

					$current_page = 1;
					if ( \Bricks\Helpers::get_ajax_current_page() ) {
						$current_page = \Bricks\Helpers::get_ajax_current_page();
					} elseif ( get_query_var( 'page' ) ) {
						$current_page = get_query_var( 'page' );
					} elseif ( get_query_var( 'paged' ) ) {
						$current_page = get_query_var( 'paged' );
					}

					$pagination_offset = ( $current_page - 1 ) * $x_gallery_per_page;

					$args = array(
						'post_type'      => 'attachment',
						'post_status'    => 'inherit',
						'posts_per_page' => $x_gallery_per_page,
						'post__in'       => $post__in,
						'orderby'        => $x_gallery_orderby,
						'order'          => $x_gallery_order,
						// For other orderby values, apply offset and max through WP_Query.
						'offset'         => $pagination_offset,
					);
				} else {

					// First, get total count for pagination by querying with max limit.
					$count_args  = array(
						'post_type'      => 'attachment',
						'post_status'    => 'inherit',
						'posts_per_page' => $x_gallery_max,
						'post__in'       => $post__in,
						'orderby'        => $x_gallery_orderby,
						'order'          => $x_gallery_order,
						'offset'         => $x_gallery_offset,
						'fields'         => 'ids',
					);
					$count_query = new \WP_Query( $count_args );

					global $bricksextras_gallery_total_images;
					$bricksextras_gallery_total_images = $count_query->post_count;

					$current_page = 1;
					if ( \Bricks\Helpers::get_ajax_current_page() ) {
						$current_page = \Bricks\Helpers::get_ajax_current_page();
					} elseif ( get_query_var( 'page' ) ) {
						$current_page = get_query_var( 'page' );
					} elseif ( get_query_var( 'paged' ) ) {
						$current_page = get_query_var( 'paged' );
					}

					// Calculate combined offset: gallery offset + pagination offset.
					$pagination_offset = ( $current_page - 1 ) * $x_gallery_per_page;
					$combined_offset   = $x_gallery_offset + $pagination_offset;

					// Calculate how many images we can fetch.
					$remaining_images = $bricksextras_gallery_total_images - $pagination_offset;
					$actual_per_page  = min( $x_gallery_per_page, max( 0, $remaining_images ) );

					$args = array(
						'post_type'      => 'attachment',
						'post_status'    => 'inherit',
						'posts_per_page' => $actual_per_page,
						'post__in'       => $post__in,
						'orderby'        => $x_gallery_orderby,
						'order'          => $x_gallery_order,
						'offset'         => $combined_offset,
					);
				}
			} else {
				// OLD LOGIC: Use WP_Query offset directly (for older Bricks versions or when no pagination).

				$args = array(
					'post_type'      => 'attachment',
					'post_status'    => 'inherit',
					'posts_per_page' => $x_gallery_max,
					'post__in'       => $post__in,
					'orderby'        => $x_gallery_orderby,
					'order'          => $x_gallery_order,
					'offset'         => $x_gallery_offset,
				);
			}

			$posts_query = new \WP_Query( $args );

			return is_array( $posts_query->posts ) ? $posts_query->posts : array();

		} else {
			return array();
		}
	}

	/**
	 * Setup post data for extras query loop.
	 *
	 * @param mixed  $loop_object Loop object.
	 * @param int    $loop_key Loop key.
	 * @param object $query_obj Query object.
	 * @return mixed Modified loop object.
	 */
	public function extras_setup_post_data( $loop_object, $loop_key, $query_obj ) {

		if ( 'queryLoopExtras' !== $query_obj->object_type ) {
			return $loop_object;
		}

		// Handle menu items.
		if ( isset( $query_obj->query_vars['extrasQuery'] ) && 'wpmenu' === $query_obj->query_vars['extrasQuery'] ) {
			global $bricksextras_current_menu_item;
			$bricksextras_current_menu_item = $loop_object;
			return $loop_object;
		}

		// Handle regular posts.
		global $post;
		$post = get_post( $loop_object );
		setup_postdata( $post );

		return $loop_object;
	}

	/**
	 * Query navigation menu items.
	 *
	 * @param object $query_obj Query object.
	 * @param int    $menu_id Menu ID.
	 * @param array  $settings Settings.
	 * @return array Menu items.
	 */
	private function x_nav_menu_query( $query_obj, $menu_id, $settings ) {
		$menu_items = wp_get_nav_menu_items( $menu_id );

		$menu_filter_type = isset( $settings['x_menu_filter_type'] ) ? $settings['x_menu_filter_type'] : 'all';
		$menu_parent_id   = isset( $settings['x_menu_parent_id'] ) ? bricks_render_dynamic_data( $settings['x_menu_parent_id'] ) : '';

		if ( 'top' === $menu_filter_type ) {
			$menu_items = array_filter(
				$menu_items,
				function ( $item ) {
					return empty( $item->menu_item_parent ) || '0' === $item->menu_item_parent;
				}
			);
		} elseif ( 'children' === $menu_filter_type && ! empty( $menu_parent_id ) ) {
			$menu_items = array_filter(
				$menu_items,
				function ( $item ) use ( $menu_parent_id ) {
					// Convert both to strings for comparison.
					return (string) $item->menu_item_parent === (string) $menu_parent_id;
				}
			);
		}

		return $menu_items ? $menu_items : array();
	}


	/**
	 * Display menu item ID in WordPress admin menu screen.
	 *
	 * @param int $item_id Menu item ID.
	 * @return void
	 */
	public function display_menu_item_id( $item_id ) {
		echo '<p style="font-size:12px;color:#888;">Menu Item ID: ' . intval( $item_id ) . '</p>';
	}

	/**
	 * Enable custom pagination logic for queryLoopExtras (gallery).
	 * Bricks v2.2 filter.
	 *
	 * @param bool   $custom_logic Whether to use custom pagination logic.
	 * @param array  $query_settings Query settings.
	 * @param object $element Element object.
	 * @return bool
	 */
	public function pagination_custom_logic( $custom_logic, $query_settings, $element ) {
		$query_object_type = $query_settings['query']['objectType'] ?? false;
		$extras_query      = $query_settings['extrasQuery'] ?? false;

		if ( 'queryLoopExtras' !== $query_object_type ) {
			return $custom_logic;
		}

		// Enable pagination for gallery.
		if ( 'gallery' === $extras_query ) {
			return true;
		}

		return $custom_logic;
	}

	/**
	 * Get current page for queryLoopExtras pagination (gallery).
	 * Bricks v2.2 filter.
	 *
	 * @param int    $current_page Current page number.
	 * @param array  $query_settings Query settings.
	 * @param object $element Element object.
	 * @return int
	 */
	public function pagination_current_page( $current_page, $query_settings, $element ) {
		$query_object_type = $query_settings['query']['objectType'] ?? false;
		$extras_query      = $query_settings['extrasQuery'] ?? false;

		if ( 'queryLoopExtras' !== $query_object_type ) {
			return $current_page;
		}

		// Handle pagination for gallery.
		if ( 'gallery' !== $extras_query ) {
			return $current_page;
		}

		if ( method_exists( '\Bricks\Helpers', 'get_ajax_current_page' ) && \Bricks\Helpers::get_ajax_current_page() ) {
			$current_page = \Bricks\Helpers::get_ajax_current_page();
		} elseif ( get_query_var( 'page' ) ) {
			$current_page = get_query_var( 'page' );
		} elseif ( get_query_var( 'paged' ) ) {
			$current_page = get_query_var( 'paged' );
		} else {
			$current_page = 1;
		}

		return $current_page;
	}

	/**
	 * Calculate total pages for queryLoopExtras pagination (gallery).
	 * Bricks v2.2 filter.
	 *
	 * @param int    $total_pages Total number of pages.
	 * @param array  $query_settings Query settings.
	 * @param object $element Element object.
	 * @return int
	 */
	public function pagination_total_pages( $total_pages, $query_settings, $element ) {
		$query_object_type = $query_settings['query']['objectType'] ?? false;
		$extras_query      = $query_settings['extrasQuery'] ?? false;

		if ( 'queryLoopExtras' !== $query_object_type ) {
			return $total_pages;
		}

		// Handle gallery pagination.
		if ( 'gallery' === $extras_query ) {
			global $bricksextras_gallery_total_images;

			if ( ! $bricksextras_gallery_total_images ) {
				return $total_pages;
			}

			// Use x_gallery_per_page for pagination calculation.
			$x_gallery_per_page = isset( $query_settings['x_gallery_per_page'] ) ? intval( $query_settings['x_gallery_per_page'] ) : 0;

			// If no per_page is set, return 1 page (show all).
			if ( $x_gallery_per_page <= 0 ) {
				return 1;
			}

			// Total images already has offset and max applied in the query.
			return (int) ceil( $bricksextras_gallery_total_images / $x_gallery_per_page );
		}

		return $total_pages;
	}

	/**
	 * Get multiple adjacent posts using WP_Query.
	 *
	 * @param string $direction Direction to get posts ('prev' or 'next').
	 * @param int    $count Number of posts to retrieve.
	 * @param bool   $in_same_term Whether to get posts from the same taxonomy term.
	 * @param string $excluded_terms Comma-separated list of term IDs to exclude.
	 * @param string $taxonomy Taxonomy to use for same term filtering.
	 * @param string $orderby Field to order posts by.
	 * @param string $order Sort order (ASC or DESC).
	 * @return array Array of post objects.
	 */
	private function get_multiple_adjacent_posts( $direction = 'prev', $count = 3, $in_same_term = false, $excluded_terms = '', $taxonomy = 'category', $orderby = 'date', $order = 'ASC' ) {
		global $post;

		if ( empty( $post ) ) {
			return array();
		}

		$current_post_id   = $post->ID;
		$current_post_type = $post->post_type;
		$db_orderby_field  = $this->get_db_field_name( $orderby );

		// For date/modified/ID, use WordPress built-in functions for single posts.
		if ( $count <= 1 && ( 'date' === $orderby || 'modified' === $orderby || 'ID' === $orderby ) ) {
			if ( 'prev' === $direction ) {
				$adjacent_post = get_previous_post( $in_same_term, $excluded_terms, $taxonomy );
			} else {
				$adjacent_post = get_next_post( $in_same_term, $excluded_terms, $taxonomy );
			}

			if ( $adjacent_post ) {
				$adjacent_post->in_adjacent_posts_loop = true;
				$adjacent_post->adjacent_direction     = $direction;
				return array( $adjacent_post );
			}
			return array();
		}

		// For all other cases, use single WP_Query to get all posts at once.
		$current_post_value = $this->get_post_orderby_value( $current_post_id, $orderby );
		if ( null === $current_post_value ) {
			return array();
		}

		// Build query args.
		$query_args = array(
			'post_type'      => $current_post_type,
			'post_status'    => 'publish',
			'posts_per_page' => $count,
			'post__not_in'   => array( $current_post_id ),
			'orderby'        => $orderby,
			'order'          => ( 'prev' === $direction ) ? 'DESC' : 'ASC',
		);

		// Handle taxonomy filtering.
		if ( $in_same_term && taxonomy_exists( $taxonomy ) && is_object_in_taxonomy( $current_post_type, $taxonomy ) ) {
			$term_ids = wp_get_object_terms( $current_post_id, $taxonomy, array( 'fields' => 'ids' ) );

			if ( ! empty( $term_ids ) && ! is_wp_error( $term_ids ) ) {
				// Remove excluded terms.
				if ( ! empty( $excluded_terms ) ) {
					if ( ! is_array( $excluded_terms ) ) {
						$excluded_terms = explode( ',', $excluded_terms );
					}
					$excluded_terms = array_map( 'intval', $excluded_terms );
					$term_ids       = array_diff( $term_ids, $excluded_terms );
				}

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

		// Add comparison for the ordering field.
		$this->add_first_post_comparison( $query_args, $orderby, $current_post_value, $direction );

		// Add temporary filter for custom field comparisons if needed.
		$filter_callback = null;
		if ( isset( $query_args['_adjacent_comparison'] ) ) {
			$comparison_data = $query_args['_adjacent_comparison'];
			$filter_callback = function ( $where ) use ( $comparison_data ) {
				global $wpdb;

				$field   = $comparison_data['field'];
				$compare = $comparison_data['compare'];
				$value   = $comparison_data['value'];

				if ( 'post_title' === $field ) {
					if ( '<' === $compare ) {
						$where .= $wpdb->prepare( ' AND ' . $wpdb->posts . '.post_title < %s', $value );
					} elseif ( '>' === $compare ) {
						$where .= $wpdb->prepare( ' AND ' . $wpdb->posts . '.post_title > %s', $value );
					} elseif ( '<=' === $compare ) {
						$where .= $wpdb->prepare( ' AND ' . $wpdb->posts . '.post_title <= %s', $value );
					} elseif ( '>=' === $compare ) {
						$where .= $wpdb->prepare( ' AND ' . $wpdb->posts . '.post_title >= %s', $value );
					}
				} elseif ( 'menu_order' === $field ) {
					if ( '<' === $compare ) {
						$where .= $wpdb->prepare( ' AND ' . $wpdb->posts . '.menu_order < %d', $value );
					} elseif ( '>' === $compare ) {
						$where .= $wpdb->prepare( ' AND ' . $wpdb->posts . '.menu_order > %d', $value );
					} elseif ( '<=' === $compare ) {
						$where .= $wpdb->prepare( ' AND ' . $wpdb->posts . '.menu_order <= %d', $value );
					} elseif ( '>=' === $compare ) {
						$where .= $wpdb->prepare( ' AND ' . $wpdb->posts . '.menu_order >= %d', $value );
					}
				} elseif ( 'ID' === $field ) {
					if ( '<' === $compare ) {
						$where .= $wpdb->prepare( ' AND ' . $wpdb->posts . '.ID < %d', $value );
					} elseif ( '>' === $compare ) {
						$where .= $wpdb->prepare( ' AND ' . $wpdb->posts . '.ID > %d', $value );
					} elseif ( '<=' === $compare ) {
						$where .= $wpdb->prepare( ' AND ' . $wpdb->posts . '.ID <= %d', $value );
					} elseif ( '>=' === $compare ) {
						$where .= $wpdb->prepare( ' AND ' . $wpdb->posts . '.ID >= %d', $value );
					}
				}

				return $where;
			};
			add_filter( 'posts_where', $filter_callback );
			unset( $query_args['_adjacent_comparison'] );
		}

		// Execute query.
		$query = new \WP_Query( $query_args );
		$posts = $query->get_posts();

		// Remove temporary filter.
		if ( $filter_callback ) {
			remove_filter( 'posts_where', $filter_callback );
		}

		wp_reset_postdata();

		// Apply final sorting according to user's preference.
		if ( ! empty( $posts ) ) {
			usort(
				$posts,
				function ( $a, $b ) use ( $db_orderby_field, $order ) {
					$result = $a->$db_orderby_field <=> $b->$db_orderby_field;
					return 'DESC' === $order ? -$result : $result;
				}
			);

			// Add flags to each post.
			foreach ( $posts as $key => $post_obj ) {
				$posts[ $key ]->in_adjacent_posts_loop = true;
				$posts[ $key ]->adjacent_direction     = $direction;
			}
		}

		return $posts;
	}


	/**
	 * Get the orderby value for a specific post.
	 *
	 * @param int    $post_id Post ID.
	 * @param string $orderby Orderby field.
	 * @return mixed Post orderby value or null if not found.
	 */
	private function get_post_orderby_value( $post_id, $orderby ) {
		$post_obj = get_post( $post_id );
		if ( ! $post_obj ) {
			return null;
		}

		switch ( $orderby ) {
			case 'date':
				return $post_obj->post_date;
			case 'modified':
				return $post_obj->post_modified;
			case 'title':
				return $post_obj->post_title;
			case 'menu_order':
				return $post_obj->menu_order;
			case 'ID':
				return $post_obj->ID;
			default:
				return $post_obj->post_date;
		}
	}

	/**
	 * Add comparison for first adjacent post (uses < or > operators).
	 *
	 * @param array  $query_args Query arguments array (passed by reference).
	 * @param string $orderby Orderby field.
	 * @param mixed  $current_value Current post's orderby value.
	 * @param string $direction Direction ('prev' or 'next').
	 */
	private function add_first_post_comparison( &$query_args, $orderby, $current_value, $direction ) {
		$compare = ( 'prev' === $direction ) ? '<' : '>';

		switch ( $orderby ) {
			case 'date':
				$query_args['date_query'] = array(
					array(
						'before' => ( 'prev' === $direction ) ? $current_value : null,
						'after'  => ( 'next' === $direction ) ? $current_value : null,
					),
				);
				break;

			case 'modified':
				$query_args['date_query'] = array(
					array(
						'column' => 'post_modified',
						'before' => ( 'prev' === $direction ) ? $current_value : null,
						'after'  => ( 'next' === $direction ) ? $current_value : null,
					),
				);
				break;

			case 'title':
			case 'menu_order':
			case 'ID':
				// For these fields, we'll use a posts_where filter.
				$field                              = $this->get_db_field_name( $orderby );
				$query_args['_adjacent_comparison'] = array(
					'field'   => $field,
					'value'   => $current_value,
					'compare' => $compare,
				);
				break;
		}
	}


	/**
	 * Get database field name for orderby value.
	 *
	 * @param string $orderby Orderby field.
	 * @return string Database field name.
	 */
	private function get_db_field_name( $orderby ) {
		switch ( $orderby ) {
			case 'date':
				return 'post_date';
			case 'modified':
				return 'post_modified';
			case 'title':
				return 'post_title';
			case 'menu_order':
				return 'menu_order';
			case 'ID':
				return 'ID';
			default:
				return 'post_date';
		}
	}
}
