<?php
/**
 * Ecre_Orders_Filter class for handling custom WooCommerce order filters.
 *
 * This class adds a custom filter to the WooCommerce orders admin interface
 * allowing filtering orders based on referral status.
 *
 * @package ECRE\Admin
 * @since   1.0.0
 */

namespace ECRE\Admin;

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

if ( ! class_exists( 'Ecre_Orders_Filter' ) ) {
	/**
	 * The Ecre_Orders_Filter class
	 *
	 * Handles referral order filtering in WooCommerce orders admin.
	 *
	 * @since 1.0.0
	 */
	class Ecre_Orders_Filter {

		/**
		 * Meta key used for referral user identification.
		 *
		 * @var string
		 */
		private $referral_meta_key = '_referral_user_id';

		/**
		 * Constructor.
		 *
		 * Initializes the class and hooks it to WooCommerce actions.
		 */
		public function __construct() {
			// For HPOS support (Custom Order Tables).
			add_action( 'woocommerce_order_list_table_restrict_manage_orders', array( $this, 'ecre_custom_referral_order_filter' ), 25, 2 );
			// For legacy CPT orders.
			add_action( 'restrict_manage_posts', array( $this, 'ecre_custom_referral_order_filter' ), 25, 2 );
			// Filter handlers for both order types.
			add_filter( 'woocommerce_orders_table_query_clauses', array( $this, 'ecre_filter_orders_by_referral_status' ), 25 );
			add_action( 'pre_get_posts', array( $this, 'ecre_filter_orders_by_referral_status_legacy' ) );
		}

		/**
		 * Adds a referral filter dropdown to the WooCommerce Orders admin page.
		 *
		 * @param string $post_type The post type being filtered.
		 * @param string $which     The location of the filter (top/bottom).
		 * @return void
		 */
		public function ecre_custom_referral_order_filter( $post_type, $which ) {
			// Only add filter for shop_order post type.
			if ( 'shop_order' !== $post_type ) {
				return;
			}

			// Get the filter value safely.
			$selected = filter_input( INPUT_GET, 'filter_is_referral' );

			// Output the filter dropdown.
			?>
			<select name="filter_is_referral">
				<option value=""><?php esc_html_e( 'Filter by Referral', 'echo-rewards' ); ?></option>
				<option value="yes" <?php selected( $selected, 'yes' ); ?>><?php esc_html_e( 'Referral Orders', 'echo-rewards' ); ?></option>
				<option value="no" <?php selected( $selected, 'no' ); ?>><?php esc_html_e( 'Non-Referral Orders', 'echo-rewards' ); ?></option>
			</select>
			<?php
		}

		/**
		 * Filters WooCommerce orders based on referral status.
		 * Used for HPOS (Custom Order Tables).
		 *
		 * @param array $clauses SQL query clauses.
		 * @return array Modified query clauses.
		 */
		public function ecre_filter_orders_by_referral_status( $clauses ) {
			global $wpdb;

			// Get the filter value safely.
			$is_referral = filter_input( INPUT_GET, 'filter_is_referral' );

			// Skip if no filter is set.
			if ( empty( $is_referral ) ) {
				return $clauses;
			}

			// Apply the filter based on the selection.
			if ( 'yes' === $is_referral ) {
				// Make sure join clause exists.
				if ( ! isset( $clauses['join'] ) ) {
					$clauses['join'] = '';
				}

				// Add join for referral orders.
				$clauses['join'] .= $wpdb->prepare(
					" INNER JOIN {$wpdb->prefix}postmeta AS postmeta_referral 
					ON {$wpdb->prefix}wc_orders.id = postmeta_referral.post_id 
					AND postmeta_referral.meta_key = %s",
					$this->referral_meta_key
				);
			} elseif ( 'no' === $is_referral ) {
				// Make sure where clause exists.
				if ( ! isset( $clauses['where'] ) ) {
					$clauses['where'] = '';
				}

				// Add where clause for non-referral orders.
				$clauses['where'] .= $wpdb->prepare(
					" AND {$wpdb->prefix}wc_orders.id NOT IN (
						SELECT post_id FROM {$wpdb->prefix}postmeta WHERE meta_key = %s
					)",
					$this->referral_meta_key
				);
			}

			return $clauses;
		}

		/**
		 * Filters WooCommerce orders (CPT-based orders) based on referral status.
		 * Used for legacy orders system.
		 *
		 * @param \WP_Query $query The query object.
		 * @return void
		 */
		public function ecre_filter_orders_by_referral_status_legacy( $query ) {
			// Only process in admin area.
			if ( ! is_admin() ) {
				return;
			}

			// Check if we're on the shop orders page.
			global $pagenow;
			if ( 'edit.php' !== $pagenow || 'shop_order' !== $query->get( 'post_type' ) ) {
				return;
			}

			// Get the filter value safely.
			$is_referral = filter_input( INPUT_GET, 'filter_is_referral' );

			// Skip if no filter is set.
			if ( empty( $is_referral ) ) {
				return;
			}

			// Set up meta query based on the filter selection.
			if ( 'yes' === $is_referral ) {
				$query->set(
					'meta_query',
					array(
						array(
							'key'     => $this->referral_meta_key,
							'compare' => 'EXISTS',
						),
					)
				);
			} elseif ( 'no' === $is_referral ) {
				$query->set(
					'meta_query',
					array(
						array(
							'key'     => $this->referral_meta_key,
							'compare' => 'NOT EXISTS',
						),
					)
				);
			}
		}
	}
}