<?php
/**
 * Pre-Order products list table.
 *
 * @package  YITH\PreOrder\Admin
 */

if ( ! defined( 'ABSPATH' ) || ! defined( 'YITH_WCPO_VERSION' ) ) {
	exit;
}

require_once ABSPATH . 'wp-admin/includes/class-wp-posts-list-table.php';

/**
 * YITH_Pre_Order_Products_List Class.
 */
class YITH_Pre_Order_Products_List extends WP_Posts_List_Table {

	/**
	 * The post type.
	 *
	 * @var string
	 */
	protected $post_type = '';

	/**
	 * The number of posts per page for the list table.
	 *
	 * @var string
	 */
	public $posts_per_page = 30;

	/**
	 * Whether the post is in trash or not.
	 *
	 * @var bool
	 */
	private $is_trash;

	/**
	 * Construct
	 *
	 * @param array  $args      An associative array of arguments.
	 * @param string $post_type The post type.
	 */
	public function __construct( $args, $post_type ) {
		parent::__construct( $args );
		$this->post_type = $post_type;
		add_action( 'pre_get_posts', array( $this, 'alter_products_query' ) );
	}

	/**
	 * Add the 'meta_key' and 'meta_value' for identifying pre-order products.
	 *
	 * @param WP_Query $query The WP_Query instance (passed by reference).
	 */
	public function alter_products_query( $query ) {
		if ( $query->is_main_query() ) {
			$query->set( 'meta_key', array( '_ywpo_preorder', '_ywpo_has_variations' ) );
			$query->set( 'meta_value', 'yes' );
		}
	}

	/**
	 * Prepares the list of items for displaying.
	 */
	public function prepare_items() {
		global $mode, $avail_post_stati, $wp_query, $per_page;

		if ( ! empty( $_REQUEST['mode'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$mode = 'excerpt' === $_REQUEST['mode'] ? 'excerpt' : 'list'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.WP.GlobalVariablesOverride.Prohibited
			set_user_setting( 'posts_list_mode', $mode );
		} else {
			$mode = get_user_setting( 'posts_list_mode', 'list' ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
		}
		$post_type = $this->post_type;

		// Is going to call wp().
		$avail_post_stati = wp_edit_posts_query( array( 'post_type' => $post_type ) ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited

		$this->set_hierarchical_display( is_post_type_hierarchical( $post_type ) && 'menu_order title' === $wp_query->query['orderby'] );

		$per_page = $this->get_items_per_page( 'edit_' . $post_type . '_per_page' ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
		if ( empty( $per_page ) ) {
			$per_page = $this->posts_per_page; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
		}

		/** This filter is based on the "edit_posts_per_page" filter, documented in wp-admin/includes/post.php */
		$per_page = apply_filters( 'ywpo_products_list_edit_posts_per_page', $per_page, $post_type ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited

		if ( $this->hierarchical_display ) {
			$total_items = $wp_query->post_count;
		} elseif ( $wp_query->found_posts || $this->get_pagenum() === 1 ) {
			$total_items = $wp_query->found_posts;
		} else {
			$post_counts = (array) wp_count_posts( $post_type, 'readable' );

			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			if ( isset( $_REQUEST['post_status'] ) && in_array( $_REQUEST['post_status'], $avail_post_stati, true ) ) {
				$total_items = $post_counts[ $_REQUEST['post_status'] ]; // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
			} elseif ( isset( $_REQUEST['show_sticky'] ) && $_REQUEST['show_sticky'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
				$total_items = $this->sticky_posts_count;
			} elseif ( isset( $_GET['author'] ) && get_current_user_id() === $_GET['author'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				$total_items = $this->user_posts_count;
			} else {
				$total_items = array_sum( $post_counts );

				// Subtract post types that are not included in the admin all list.
				foreach ( get_post_stati( array( 'show_in_admin_all_list' => false ) ) as $state ) {
					$total_items -= $post_counts[ $state ];
				}
			}
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$this->is_trash = isset( $_REQUEST['post_status'] ) && 'trash' === $_REQUEST['post_status'];

		$this->set_pagination_args(
			array(
				'total_items' => $total_items,
				'per_page'    => $per_page,
			)
		);
	}

	/**
	 * Gets a list of CSS classes for the WP_List_Table table tag.
	 *
	 * @return array
	 */
	protected function get_table_classes() {
		global $mode;

		$mode_class = esc_attr( 'table-view-' . $mode );

		return array( 'widefat', 'fixed', 'striped', $mode_class, is_post_type_hierarchical( $this->screen->post_type ) ? 'pages' : 'posts', 'yith-plugin-fw__classic-table' );
	}

	/**
	 * Gets a list of sortable columns.
	 *
	 * @return array
	 */
	protected function get_sortable_columns() {
		return array(
			'name' => array( 'name', false ),
		);
	}

	/**
	 * Retrieves the list of bulk actions available for this table.
	 *
	 * @return array
	 */
	protected function get_bulk_actions() {
		$actions = array();

		$actions['trash']                 = __( 'Move to Trash' );
		$actions['ywpo-remove-pre-order'] = __( 'Remove the pre-order status' );

		return $actions;
	}

	/**
	 * Generates the table navigation above or below the table
	 *
	 * @param string $which Tablenav location.
	 */
	protected function display_tablenav( $which ) {
		if ( 'top' === $which ) {
			wp_nonce_field( 'bulk-' . $this->_args['plural'] );
		}
		?>
		<div class="tablenav <?php echo esc_attr( $which ); ?>">

			<?php if ( $this->has_items() ) : ?>
				<div class="alignleft actions bulkactions">
					<?php $this->bulk_actions( $which ); ?>
				</div>
				<?php
			endif;
			$this->extra_tablenav( $which );
			$this->pagination( $which );
			?>

			<br class="clear" />
		</div>
		<?php
	}

}
