<?php
/**
 * Ecre_Coupon_Columns.php
 *
 * This class handles custom columns for shop coupons in WooCommerce, specifically the 'Referral' column.
 *
 * @package ECRE\Admin
 * @since   1.0.0
 */

namespace ECRE\Admin;

if ( ! class_exists( 'Ecre_Coupon_Columns' ) ) {
	/**
	 * The Ecre_Coupon_Columns class
	 *
	 * @since 1.0.0
	 */
	class Ecre_Coupon_Columns {


		/**
		 * Ecre_Coupon_Columns constructor.
		 *
		 * Initializes the class and hooks it to WooCommerce actions for managing coupon columns.
		 */
		public function __construct() {
			add_filter( 'manage_edit-shop_coupon_columns', array( $this, 'ecre_add_referral_column' ), 10, 1 );
			add_action( 'manage_shop_coupon_posts_custom_column', array( $this, 'ecre_display_referral_column' ), 10, 2 );
		}

		/**
		 * Add a new column to the shop_coupon post type.
		 *
		 * @param array $columns Columns array.
		 *
		 * @return array
		 *
		 * @since 1.0.0
		 */
		public function ecre_add_referral_column( $columns ) {
			$columns['referral'] = 'Referral by';
			$columns['reward']   = 'Reward for';
			return $columns;
		}

		/**
		 * Populate the custom column with data.
		 *
		 * @param string $column  The column name.
		 * @param int    $post_id Post ID.
		 *
		 * @since 1.0.0
		 */
		public function ecre_display_referral_column( $column, $post_id ) {
			if ( 'referral' === $column ) {
				$referral_user_id = get_post_meta( $post_id, 'referral_user_id', true );

				if ( $referral_user_id ) {
					// Retrieve the user by ID.
					$user = get_user_by( 'id', $referral_user_id );

					if ( $user ) {
						echo esc_html( $user->display_name );
					}
				}
			}

			if ( 'reward' === $column ) {
				$reward_user_id = get_post_meta( $post_id, 'reward_user_id', true );

				if ( $reward_user_id ) {
					// Retrieve the user by ID.
					$user = get_user_by( 'id', $reward_user_id );

					if ( $user ) {
						echo esc_html( $user->display_name );
					}
				}
			}
		}
	}
}
