<?php
/**
 * Reward helper
 *
 * @package WooCommerce Points and Rewards
 * @version 1.0.0
 */

namespace DDWCPointsAndRewards\Helper\Reward;

use DDWCPointsAndRewards\Helper\Point\DDWCPR_Point_Helper;
use DDWCPointsAndRewards\Helper\Rule\DDWCPR_Rule_Helper;

defined( 'ABSPATH' ) || exit();

if ( ! class_exists( 'DDWCPR_Reward_Helper' ) ) {
	/**
	 * Reward helper class
	 */
	class DDWCPR_Reward_Helper {
		/**
		 * Configuration Variable
		 *
		 * @var array
		 */
		protected $ddwcpr_configuration;

		/**
		 * Log Helper Variable
		 *
		 * @var object
		 */
		protected $rule_helper;

		/**
		 * Construct
		 */
		public function __construct( $ddwcpr_configuration ) {
			$this->ddwcpr_configuration = $ddwcpr_configuration;
			$this->rule_helper          = new DDWCPR_Rule_Helper( $ddwcpr_configuration );
		}

		/**
		 * Get coupon details HTML function
		 *
		 * @param int $coupon_id
		 * @param bool $as_table
		 * @return string
		 */
		public function ddwcpr_get_coupon_details_html( $coupon_id, $as_table = false ) {
			$coupon = new \WC_Coupon( $coupon_id );

			if ( ! $coupon->get_id() ) {
				return '';
			}

			$rule_type = get_post_meta( $coupon->get_id(), 'ddwcpr_rule_type', true );
			$details_rows = [];

			if ( $as_table ) {
				ob_start();
				?>
				<table class="ddwcpr-tooltip-details-table">
					<thead>
						<tr>
							<th colspan="2"><?php esc_html_e( 'Coupon Details', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td><strong><?php esc_html_e( 'Amount', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong></td>
							<td><?php echo wp_kses_post( wc_price( $coupon->get_amount() ) ); ?></td>
						</tr>
						<?php
						if ( $coupon->get_minimum_amount() ) {
							?>
							<tr>
								<td><strong><?php esc_html_e( 'Minimum Cart Amount', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong></td>
								<td><?php echo wc_price( $coupon->get_minimum_amount() ); ?></td>
							</tr>
							<?php
						}
						if ( $coupon->get_maximum_amount() ) {
							?>
							<tr>
								<td><strong><?php esc_html_e( 'Maximum Cart Amount', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong></td>
								<td><?php echo wc_price( $coupon->get_maximum_amount() ); ?></td>
							</tr>
							<?php
						}
						if ( $coupon->get_product_ids() ) {
							?>
							<tr>
								<td><strong><?php esc_html_e( 'Applicable Products', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong></td>
								<td>
									<?php
									$product_links = [];
									foreach ( $coupon->get_product_ids() as $pid ) {
										$product = wc_get_product( $pid );
										if ( $product ) {
											$product_links[] = '<a href="' . esc_url( get_permalink( $pid ) ) . '" target="_blank">' . esc_html( $product->get_name() ) . '</a>';
										}
									}
									echo implode( ', ', $product_links );
									?>
								</td>
							</tr>
							<?php
						}
						if ( $coupon->get_product_categories() ) {
							?>
							<tr>
								<td><strong><?php esc_html_e( 'Applicable Categories', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong></td>
								<td>
									<?php
									$cat_links = [];
									foreach ( $coupon->get_product_categories() as $cat_id ) {
										$cat = get_term( $cat_id, 'product_cat' );
										if ( $cat && ! is_wp_error( $cat ) ) {
											$cat_links[] = '<a href="' . esc_url( get_category_link( $cat_id ) ) . '" target="_blank">' . esc_html( $cat->name ) . '</a>';
										}
									}
									echo implode( ', ', $cat_links );
									?>
								</td>
							</tr>
							<?php
						}
						if ( $coupon->get_excluded_product_ids() ) {
							?>
							<tr>
								<td><strong><?php esc_html_e( 'Excluded Products', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong></td>
								<td>
									<?php
									$product_links = [];
									foreach ( $coupon->get_excluded_product_ids() as $pid ) {
										$product = wc_get_product( $pid );
										if ( $product ) {
											$product_links[] = '<a href="' . esc_url( get_permalink( $pid ) ) . '" target="_blank">' . esc_html( $product->get_name() ) . '</a>';
										}
									}
									echo implode( ', ', $product_links );
									?>
								</td>
							</tr>
							<?php
						}
						if ( $coupon->get_excluded_product_categories() ) {
							?>
							<tr>
								<td><strong><?php esc_html_e( 'Excluded Categories', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong></td>
								<td>
									<?php
									$cat_links = [];
									foreach ( $coupon->get_excluded_product_categories() as $cat_id ) {
										$cat = get_term( $cat_id, 'product_cat' );
										if ( $cat && ! is_wp_error( $cat ) ) {
											$cat_links[] = '<a href="' . esc_url( get_category_link( $cat_id ) ) . '" target="_blank">' . esc_html( $cat->name ) . '</a>';
										}
									}
									echo implode( ', ', $cat_links );
									?>
								</td>
							</tr>
							<?php
						}
						if ( $coupon->get_exclude_sale_items() ) {
							?>
							<tr>
								<td><strong><?php esc_html_e( 'Excludes Sale Items', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong></td>
								<td><?php esc_html_e( 'Yes', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></td>
							</tr>
							<?php
						}
						// Add custom rows for special coupon types
						foreach ( $details_rows as $row ) {
							?>
							<tr>
								<td><strong><?php echo esc_html( $row['label'] ); ?></strong></td>
								<td><?php echo wp_kses_post( $row['value'] ); ?></td>
							</tr>
							<?php
						}
						?>
					</tbody>
				</table>
				<?php
				return ob_get_clean();
			}

			// Default: <p> structure
			ob_start();
			?>
			<p>
				<strong><?php esc_html_e( 'Code:', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong> <?php echo esc_html( strtoupper( $coupon->get_code() ) ); ?><br>
				<strong><?php esc_html_e( 'Type:', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong> <?php echo esc_html( ddwcpr_get_translation( $rule_type ) ); ?><br>
				<strong><?php esc_html_e( 'Amount:', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong> <?php echo wp_kses_post( wc_price( $coupon->get_amount() ) ); ?><br>
				<strong><?php esc_html_e( 'Usage Limit:', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong> <?php echo esc_html( $coupon->get_usage_limit() ? $coupon->get_usage_limit() : esc_html__( 'No limit', 'loyaltyx-points-and-rewards-for-woocommerce' ) ); ?><br>
				<strong><?php esc_html_e( 'Expiry Date:', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong> <?php echo esc_html( $coupon->get_date_expires() ? $coupon->get_date_expires()->date_i18n( get_option( 'date_format' ) ) : esc_html__( 'Never', 'loyaltyx-points-and-rewards-for-woocommerce' ) ); ?><br>
				<?php 
				if ( $coupon->get_minimum_amount() ) {
					?>
					<strong><?php esc_html_e( 'Minimum Cart Amount:', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong> <?php echo wc_price( $coupon->get_minimum_amount() ); ?><br>
					<?php
				}
				if ( $coupon->get_maximum_amount() ) {
					?>
					<strong><?php esc_html_e( 'Maximum Cart Amount:', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong> <?php echo wc_price( $coupon->get_maximum_amount() ); ?><br>
					<?php
				}
				if ( $coupon->get_product_ids() ) {
					?>
					<strong><?php esc_html_e( 'Applicable Products:', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong> <?php
					$product_links = [];
					foreach ( $coupon->get_product_ids() as $pid ) {
						$product = wc_get_product( $pid );
						if ( $product ) {
							$product_links[] = '<a href="' . esc_url( get_permalink( $pid ) ) . '" target="_blank">' . esc_html( $product->get_name() ) . '</a>';
						}
					}
					echo implode( ', ', $product_links );
					?><br>
					<?php
				}
				if ( $coupon->get_product_categories() ) {
					?>
					<strong><?php esc_html_e( 'Applicable Categories:', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong> <?php
					$cat_links = [];
					foreach ( $coupon->get_product_categories() as $cat_id ) {
						$cat = get_term( $cat_id, 'product_cat' );
						if ( $cat && ! is_wp_error( $cat ) ) {
							$cat_links[] = '<a href="' . esc_url( get_category_link( $cat_id ) ) . '" target="_blank">' . esc_html( $cat->name ) . '</a>';
						}
					}
					echo implode( ', ', $cat_links );
					?><br>
					<?php
				}
				if ( $coupon->get_exclude_sale_items() ) {
					?>
					<strong><?php esc_html_e( 'Excludes Sale Items:', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></strong> <?php esc_html_e( 'Yes', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?><br>
					<?php
				}
				// Add custom rows for special coupon types
				foreach ( $details_rows as $row ) {
					?>
					<strong><?php echo esc_html( $row['label'] ); ?>:</strong> <?php echo wp_kses_post( $row['value'] ); ?><br>
					<?php
				}
				?>
			</p>
			<?php
			return ob_get_clean();
		}

		/**
		 * Create coupon reward function
		 * 
		 * @return void
		 */
		public function ddwcpr_create_coupon_reward() {
			$user         = wp_get_current_user();
			$user_id      = $user->ID;
			$rule_id      = ! empty( $_POST['ddwcpr_rule_id'] ) ? intval( wp_unslash( $_POST['ddwcpr_rule_id'] ) ) : 0;
			$rule         = $this->rule_helper->ddwcpr_get_redeeming_rule_by_id( $rule_id );
			$point_helper = new DDWCPR_Point_Helper( $this->ddwcpr_configuration );

			if ( $rule ) {
				$additional_data  = maybe_unserialize( $rule['additional_data'] );
				$available_points = $point_helper->ddwcpr_get_user_available_points( $user_id );
				$points_to_redeem = absint( $additional_data['points_value'] );

				// Allow manual points for points_conversion rule type
				if ( 'points_conversion' === $rule['type'] && ! empty( $_POST['ddwcpr_points_conversion_input'] ) ) {
					$ddwcpr_points_conversion_input = absint( $_POST['ddwcpr_points_conversion_input'] );
					if ( $ddwcpr_points_conversion_input > 0 && $ddwcpr_points_conversion_input <= $available_points ) {
						$points_to_redeem = $ddwcpr_points_conversion_input;
					}
				}

				if ( $available_points >= $points_to_redeem ) {
					$result = $this->create_coupon_common(
						[
							'user_id'          => $user_id,
							'rule'             => $rule,
							'additional_data'  => $additional_data,
							'points_to_redeem' => $points_to_redeem,
							'user'             => $user,
						]
					);
					if ( is_wp_error( $result ) ) {
						wc_add_notice( $result->get_error_message(), 'error' );
					}
				} else {
					wc_add_notice( esc_html__( 'You do not have sufficient points to redeem this reward.', 'loyaltyx-points-and-rewards-for-woocommerce' ), 'error' );
				}

				wp_safe_redirect( add_query_arg( null, null ) );
				exit;
			}
		}

		/**
		 * Create a coupon for global points conversion with all restrictions
		 *
		 * @param int $user_id
		 * @param int $points_to_redeem
		 * @return int|\WP_Error Coupon ID on success, WP_Error on failure
		 */
		public function ddwcpr_global_points_conversion_to_coupon() {
			$user_id                    = get_current_user_id();
			$this->ddwcpr_configuration = $this->ddwcpr_configuration;
			$point_helper               = new DDWCPR_Point_Helper( $this->ddwcpr_configuration );
			$points_to_redeem           = isset( $_POST['ddwcpr_points_conversion_input'] ) ? absint( $_POST['ddwcpr_points_conversion_input'] ) : 0;

			if ( $points_to_redeem <= 0 ) {
				return new \WP_Error( 'invalid_points', esc_html__( 'Please enter a valid number of points to redeem.', 'loyaltyx-points-and-rewards-for-woocommerce' ) );
			}

			$available_points = $point_helper->ddwcpr_get_user_available_points( $user_id );

			$min_points   = ! empty( $this->ddwcpr_configuration['points_redeeming_min_points'] ) ? absint( $this->ddwcpr_configuration['points_redeeming_min_points'] ) : 0;
			$max_points   = ! empty( $this->ddwcpr_configuration['points_redeeming_max_points'] ) ? absint( $this->ddwcpr_configuration['points_redeeming_max_points'] ) : 0;
			$points_value = ! empty( $this->ddwcpr_configuration['points_redeeming_value'] ) ? absint( $this->ddwcpr_configuration['points_redeeming_value'] ) : 1;
			$amount_value = ! empty( $this->ddwcpr_configuration['points_redeeming_amount'] ) ? floatval( $this->ddwcpr_configuration['points_redeeming_amount'] ) : 1;

			if ( $points_to_redeem < $min_points ) {
				return new \WP_Error( 'min_points', sprintf( esc_html__( 'You must redeem at least %d points.', 'loyaltyx-points-and-rewards-for-woocommerce' ), $min_points ) );
			}
			if ( $max_points && $points_to_redeem > $max_points ) {
				return new \WP_Error( 'max_points', sprintf( esc_html__( 'You can redeem a maximum of %d points per order.', 'loyaltyx-points-and-rewards-for-woocommerce' ), $max_points ) );
			}
			if ( $points_to_redeem > $available_points ) {
				return new \WP_Error( 'insufficient_points', esc_html__( 'You do not have enough points to redeem.', 'loyaltyx-points-and-rewards-for-woocommerce' ) );
			}
			if ( $points_value <= 0 || $amount_value <= 0 ) {
				return new \WP_Error( 'invalid_config', esc_html__( 'Invalid points conversion configuration.', 'loyaltyx-points-and-rewards-for-woocommerce' ) );
			}

			// Calculate discount
			$discount = ( $points_to_redeem / $points_value ) * $amount_value;
			if ( $discount <= 0 ) {
				return new \WP_Error( 'invalid_discount', esc_html__( 'Calculated discount is invalid.', 'loyaltyx-points-and-rewards-for-woocommerce' ) );
			}

			// Use the common coupon creation logic
			return $this->create_coupon_common([
				'user_id'          => $user_id,
				'points_to_redeem' => $points_to_redeem,
				'discount'         => $discount,
				'rule_type'        => 'points_conversion',
			]);
		}

		/**
		 * Common coupon creation logic for both global and rule-based rewards
		 * @param array $args
		 * @return int|\WP_Error
		 */
		private function create_coupon_common( $args ) {
			// If called from rule-based reward
			if ( isset( $args['rule'] ) ) {
				extract( $args );
				$discount      = ! empty( $additional_data['discount_value'] ) ? floatval( $additional_data['discount_value'] ) : 1;
				$coupon_type   = 'fixed_cart';
				$coupon_amount = $discount;

				switch ( $rule['type'] ) {
					case 'points_conversion':
						$conversion_rate = ! empty( $additional_data['points_value'] ) ? absint( $additional_data['points_value'] ) : 1;
						$coupon_type     = 'fixed_cart';
						$coupon_amount   = ( $points_to_redeem / $conversion_rate ) * $discount;
						break;
				}

				$coupon_code = 'PRW-' . strtoupper( wp_generate_password( 8, false ) );
				$coupon = [
					'post_title'   => $coupon_code,
					'post_content' => '',
					'post_status'  => 'publish',
					'post_author'  => $user_id,
					'post_type'    => 'shop_coupon'
				];
				$new_coupon_id = wp_insert_post( $coupon );
				if ( $new_coupon_id ) {
					update_post_meta( $new_coupon_id, 'discount_type', $coupon_type );
					update_post_meta( $new_coupon_id, 'coupon_amount', $coupon_amount );
					update_post_meta( $new_coupon_id, 'individual_use', 'no' );
					update_post_meta( $new_coupon_id, 'usage_limit', 1 );
					update_post_meta( $new_coupon_id, 'usage_limit_per_user', 1 );
					update_post_meta( $new_coupon_id, 'ddwcpr_rule_type', $rule['type'] );

					if ( ! empty( $additional_data['coupon_expiry'] ) ) {
						update_post_meta( $new_coupon_id, 'date_expires', strtotime( '+' . absint( $additional_data['coupon_expiry'] ) . ' days' ) );
					}
					if ( ! empty( $additional_data['coupon_label'] ) ) {
						update_post_meta( $new_coupon_id, 'ddwcpr_coupon_label', sanitize_text_field( $additional_data['coupon_label'] ) );
					}
					if ( ! empty( $rule['sharing'] ) && 'no' === $rule['sharing'] ) {
						update_post_meta( $new_coupon_id, 'customer_email', $user->user_email );
					}
					// Deduct points from the user
					$data = [
						'points'      => -$points_to_redeem,
						'user_id'     => $user_id,
						'related_id'  => $new_coupon_id,
						'description' => sprintf( esc_html__( 'Redeemed %d %s for %s reward.', 'loyaltyx-points-and-rewards-for-woocommerce' ), $points_to_redeem, ddwcpr_get_points_label( $points_to_redeem ), ddwcpr_get_translation( $rule['type'] ) ),
						'event'       => $rule['type'],
					];
					$point_helper = new DDWCPR_Point_Helper( $this->ddwcpr_configuration );
					$point_helper->ddwcpr_deduct_user_points( $data );
					wc_add_notice( sprintf( esc_html__( 'Coupon %s created successfully!%s', 'loyaltyx-points-and-rewards-for-woocommerce' ), '<strong>' . $coupon_code . '</strong>', ! empty( $additional_data['coupon_expiry'] ) ? ' ' . sprintf( esc_html__( 'It will expire in %d days.', 'loyaltyx-points-and-rewards-for-woocommerce' ), absint( $additional_data['coupon_expiry'] ) ) : '' ), 'success' );
					if ( function_exists( 'WC' ) && WC()->cart ) {
						WC()->cart->add_discount( $coupon_code );
					}
					wp_safe_redirect( add_query_arg( null, null ) );
					exit;
				} else {
					return new \WP_Error( 'coupon_error', esc_html__( 'There was an error creating your coupon.', 'loyaltyx-points-and-rewards-for-woocommerce' ) );
				}
			}
			// If called from global points conversion
			extract( $args );
			$coupon_code = 'PRW-' . strtoupper( wp_generate_password( 8, false ) );
			$coupon = [
				'post_title'   => $coupon_code,
				'post_content' => '',
				'post_status'  => 'publish',
				'post_author'  => $user_id,
				'post_type'    => 'shop_coupon'
			];
			$new_coupon_id = wp_insert_post( $coupon );
			if ( $new_coupon_id ) {
				update_post_meta( $new_coupon_id, 'discount_type', 'fixed_cart' );
				update_post_meta( $new_coupon_id, 'coupon_amount', $discount );
				update_post_meta( $new_coupon_id, 'individual_use', 'no' );
				update_post_meta( $new_coupon_id, 'usage_limit', 1 );
				update_post_meta( $new_coupon_id, 'usage_limit_per_user', 1 );
				update_post_meta( $new_coupon_id, 'ddwcpr_rule_type', 'points_conversion' );
				if ( ! empty( $this->ddwcpr_configuration['points_redeeming_exclude_sale_products_enabled'] ) ) {
					update_post_meta( $new_coupon_id, 'exclude_sale_items', 'yes' );
				}
				if ( ! empty( $this->ddwcpr_configuration['points_redeeming_excluded_products'] ) && is_array( $this->ddwcpr_configuration['points_redeeming_excluded_products'] ) ) {
					update_post_meta( $new_coupon_id, 'exclude_product_ids', array_map( 'absint', $this->ddwcpr_configuration['points_redeeming_excluded_products'] ) );
				}
				if ( ! empty( $this->ddwcpr_configuration['points_redeeming_excluded_categories'] ) && is_array( $this->ddwcpr_configuration['points_redeeming_excluded_categories'] ) ) {
					update_post_meta( $new_coupon_id, 'exclude_product_categories', array_map( 'absint', $this->ddwcpr_configuration['points_redeeming_excluded_categories'] ) );
				}
				if ( ! empty( $this->ddwcpr_configuration['points_redeeming_min_cart_amount'] ) ) {
					update_post_meta( $new_coupon_id, 'minimum_amount', floatval( $this->ddwcpr_configuration['points_redeeming_min_cart_amount'] ) );
				}
				if ( ! empty( $this->ddwcpr_configuration['points_redeeming_max_cart_amount'] ) ) {
					update_post_meta( $new_coupon_id, 'maximum_amount', floatval( $this->ddwcpr_configuration['points_redeeming_max_cart_amount'] ) );
				}
				$data = [
					'points'      => -$points_to_redeem,
					'user_id'     => $user_id,
					'related_id'  => $new_coupon_id,
					'description' => sprintf( esc_html__( 'Redeemed %d %s for global points conversion.', 'loyaltyx-points-and-rewards-for-woocommerce' ), $points_to_redeem, ddwcpr_get_points_label( $points_to_redeem ) ),
					'event'       => 'points_conversion',
				];
				$point_helper = new DDWCPR_Point_Helper( $this->ddwcpr_configuration );
				$point_helper->ddwcpr_deduct_user_points( $data );
				wc_add_notice( sprintf( esc_html__( 'Coupon %s created successfully!', 'loyaltyx-points-and-rewards-for-woocommerce' ), '<strong>' . $coupon_code . '</strong>' ), 'success' );
				if ( function_exists( 'WC' ) && WC()->cart ) {
					WC()->cart->add_discount( $coupon_code );
				}
				wp_safe_redirect( add_query_arg( null, null ) );
				exit;
			} else {
				return new \WP_Error( 'coupon_error', esc_html__( 'There was an error creating your coupon.', 'loyaltyx-points-and-rewards-for-woocommerce' ) );
			}
		}

		/**
		 * Get coupon rewards function
		 *
		 * @param array $args
		 * @return array
		 */
		public function ddwcpr_get_coupon_rewards( $args ) {
			extract( $args );

			$args = [
				'post_type'      => 'shop_coupon',
				'post_status'    => 'publish',
				'posts_per_page' => $per_page,
				'offset'         => $offset,
				'orderby'        => 'date',
				'order'          => 'DESC',
				'author'         => $user_id,
				'meta_query'     => [
					[
						'key'     => 'ddwcpr_rule_type',
						'compare' => 'EXISTS',
					],
				],
			];

			$coupons = get_posts( $args );
			$rewards = [];

			foreach ( $coupons as $coupon_post ) {
				$coupon = new \WC_Coupon( $coupon_post->ID );
				$rewards[] = [
					'id'           => $coupon->get_id(),
					'code'         => strtoupper( $coupon->get_code() ),
					'type'         => ddwcpr_get_translation( get_post_meta( $coupon->get_id(), 'ddwcpr_rule_type', true ) ),
					'amount'       => $coupon->get_amount(),
					'date_created' => $coupon->get_date_created()->date_i18n( get_option( 'date_format' ) ),
					'expiry'       => $coupon->get_date_expires() ? $coupon->get_date_expires()->date_i18n( get_option( 'date_format' ) ) : '',
					'details_html' => $this->ddwcpr_get_coupon_details_html( $coupon->get_id(), true ),
					'status'       => ( $coupon->get_date_expires() && $coupon->get_date_expires()->getTimestamp() < time() )
						? 'expired'
						: ( $coupon->get_usage_count() > 0
							? 'redeemed'
							: 'active'
						),
				];
			}

			return $rewards;
		}

		/**
		 * Get rewards count function
		 *
		 * @param array $args
		 * @return int
		 */
		public function ddwcpr_get_rewards_count( $args ) {
			extract( $args );

			$args = [
				'post_type'      => 'shop_coupon',
				'post_status'    => 'publish',
				'posts_per_page' => 1,
				'fields'         => 'ids',
				'orderby'        => 'date',
				'order'          => 'DESC',
				'author'         => $user_id,
				'meta_query'     => [
					[
						'key'     => 'ddwcpr_rule_type',
						'compare' => 'EXISTS',
					],
				],
			];

			$query = new \WP_Query( $args );
			return $query->found_posts;
		}

		/**
		 * Apply reward points to cart function
		 *
		 * @param string $coupon_code
		 * @return void
		 */
		public function ddwcpr_apply_reward_points_to_cart( $coupon_code ) {
			if ( ! empty( $coupon_code ) && WC()->cart && ! WC()->cart->has_discount( $coupon_code ) ) {
				WC()->cart->add_discount( $coupon_code );
				wp_safe_redirect( add_query_arg( null, null ) );
				exit;
			}
		}

		/**
		 * Render rewards table rows function
		 *
		 * @param array $rewards
		 * @return void
		 */
		public function ddwcpr_render_rewards_table_rows( $rewards ) {
			if ( ! empty( $rewards ) ) {
				foreach ( $rewards as $result ) {
					?>
					<tr>
						<td>
							<div class="ddwcpr-reward-code-container">
								<?php ddwcpr_get_copy_text_field( $result['code'], 18 ); ?>
								<span class="ddwcpr-tooltip-icon">
									&#9432;
									<span class="ddwcpr-tooltip-content">
										<?php echo wp_kses_post( $result['details_html'] ); ?>
									</span>
								</span>
							</div>
						</td>
						<td><?php echo esc_html( $result['type'] ); ?></td>
						<td><?php echo esc_html( $result['date_created'] ); ?></td>
						<td><?php echo esc_html( $result['expiry'] ? $result['expiry'] : esc_html__( 'Never', 'loyaltyx-points-and-rewards-for-woocommerce' ) ); ?></td>
						<td><mark class="ddwcpr-status ddwcpr-status-<?php echo esc_attr( $result['status'] ); ?>"><?php echo esc_html( ddwcpr_get_translation( $result['status'] ) ); ?></mark></td>
						<td>
							<?php
							if ( 'active' === $result['status'] ) {
								?>
								<form method="post" class="ddwcpr-apply-reward-form">
									<?php wp_nonce_field( 'ddwcpr_nonce_action', 'ddwcpr_nonce' ); ?>
									<input type="hidden" name="ddwcpr_coupon_code" value="<?php echo esc_attr( $result['code'] ); ?>" />
									<button type="submit" class="ddwcpr-apply-reward-button" name="ddwcpr_apply_reward_points_submit" value="yes"><?php esc_html_e( 'Apply', 'loyaltyx-points-and-rewards-for-woocommerce' ); ?></button>
								</form>
								<?php
							} else {
								esc_html_e( 'N/A', 'loyaltyx-points-and-rewards-for-woocommerce' );
							}
							?>
						</td>
					</tr>
					<?php
				}
			}
		}
	}
}
