<?php
/**
 * Ecre_Orders_Column class for handling custom WooCommerce order columns
 *
 * This class adds and manages a 'Referral Order' column in the WooCommerce orders admin interface,
 * as well as a dedicated 'Referral Orders' tab for filtering orders.
 *
 * @package ECRE\Admin
 * @since   2.3.1
 */

namespace ECRE\Admin;

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

if ( ! class_exists( 'Ecre_Orders_Column' ) ) {
	/**
	 * The Ecre_Orders_Column class
	 *
	 * Adds a custom 'Referral Order' column to the WooCommerce orders admin interface
	 * and related functionality.
	 *
	 * @since 2.3.1
	 */
	class Ecre_Orders_Column {

		/**
		 * Ecre_Orders_Column constructor.
		 *
		 * Initializes the class and hooks it to WooCommerce actions for managing order columns.
		 */
		public function __construct() {
			add_filter( 'woocommerce_shop_order_list_table_columns', array( $this, 'ecre_add_referral_order_column' ) );
			add_action( 'woocommerce_shop_order_list_table_custom_column', array( $this, 'ecre_populate_referral_order_column' ), 10, 2 );
			add_filter( 'woocommerce_shop_order_list_table_sortable_columns', array( $this, 'ecre_make_referral_order_column_sortable' ) );
		}

		/**
		 * Add Referral Order column to orders table.
		 *
		 * @param array $columns Existing order columns.
		 * @return array Modified columns array with referral order column added.
		 */
		public function ecre_add_referral_order_column( $columns ) {
			$columns['referral_order'] = __( 'Referral Order', 'echo-rewards' );
			return $columns;
		}

		/**
		 * Populate the Referral Order column data.
		 *
		 * @param string   $column Current column name.
		 * @param WC_Order $order Current order object.
		 * @return void
		 */
		public function ecre_populate_referral_order_column( $column, $order ) {
			if ( 'referral_order' === $column ) {
				// Get the referral status from order meta.
				$referral_user_id = get_post_meta( $order->get_id(), '_referral_user_id', true );

				if ( ! empty( $referral_user_id ) ) {
					echo esc_html__( 'Yes', 'echo-rewards' );
				} else {
					echo esc_html__( 'No', 'echo-rewards' );
				}
			}
		}

		/**
		 * Make the Referral Order column sortable.
		 *
		 * @param array $columns Sortable columns array.
		 * @return array Modified sortable columns array.
		 */
		public function ecre_make_referral_order_column_sortable( $columns ) {
			$columns['referral_order'] = 'referral_order';
			return $columns;
		}
	}
}
