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

namespace DDWCPointsAndRewards\Helper\Rank;

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

if ( ! class_exists( 'DDWCPR_Rank_Helper' ) ) {
	/**
	 * Rank helper class
	 */
	class DDWCPR_Rank_Helper {
		/**
		 * Database object
		 *
		 * @var object
		 */
		protected $wpdb;

		/**
		 * Configuration Variable
		 *
		 * @var array
		 */
		protected $ddwcpr_configuration;

		/**
		 * Point Helper Variable
		 *
		 * @var object
		 */
		protected $point_helper;

		/**
		 * Construct
		 */
		public function __construct( $ddwcpr_configuration ) {
			global $wpdb;
			$this->wpdb                 = $wpdb;
			$this->ddwcpr_configuration = $ddwcpr_configuration;
		}

		/**
		 * Get user rank function
		 *
		 * @param int $user_id
		 * @return int
		 */
		public function ddwcpr_get_user_rank( $user_id ) {
			// Get the user's total earned points
			$user_points = $this->wpdb->get_var(
				$this->wpdb->prepare(
					"SELECT SUM(points) FROM {$this->wpdb->ddwcpr_points_log} WHERE user_id = %d",
					$user_id
				)
			);

			if ( ! $user_points ) {
				$user_points = 0;
			}

			// Get the rank: count users with more points than this user, then add 1
			$rank = $this->wpdb->get_var(
				$this->wpdb->prepare(
					"SELECT COUNT(*) + 1 FROM (
						SELECT user_id, SUM(points) as total_points
						FROM {$this->wpdb->ddwcpr_points_log}
						GROUP BY user_id
						HAVING total_points > %d
					) as ranked",
					$user_points
				)
			);

			return intval( $rank );
		}
	}
}
