<?php

namespace WC_Affiliate\Traits;

defined( 'ABSPATH' ) || exit;

/**
 * Trait Limiter
 *
 * This trait provides methods to implement rate limiting for user requests in the WordPress plugin.
 *
 * @package WC_Affiliate
 */
trait Limiter {

	/**
	 * Meta key for the request count.
	 *
	 * @var string
	 */
	private string $count_key = '_request_count';

	/**
	 * Meta key for the first request time.
	 *
	 * @var string
	 */
	private string $time_key = '_first_request_time';

	/**
	 * Check the rate limit for a user.
	 *
	 * @param int $user_id  The user ID.
	 * @param int $limit    The maximum number of requests allowed within the interval. Default is 100.
	 * @param int $interval The time interval in seconds within which the requests are limited. Default is 3600 (1 hour).
	 *
	 * @return bool True if the request is within the limit, false if the limit is exceeded.
	 */
	protected function check_rate_limit( int $user_id, int $limit = 100, int $interval = 3600 ): bool {
		$user_model = new \WC_Affiliate\Models\User( $user_id );

		$request_count      = $user_model->get_meta( $this->count_key );
		$first_request_time = $user_model->get_meta( $this->time_key );

		// If there is no recorded first request time, set it to the current time.
		if ( ! $first_request_time ) {
			$first_request_time = date_i18n( 'U' );
			$user_model->update_meta( $this->time_key, $first_request_time );
		}

		// If the current time exceeds the interval since the first request, reset the count and time.
		if ( date_i18n( 'U' ) - $first_request_time > $interval ) {
			$user_model->update_meta( $this->count_key, 1 );
			$user_model->update_meta( $this->time_key, date_i18n( 'U' ) );
		} elseif ( $request_count >= $limit ) {
			// If the request count exceeds the limit, deny the request.
			return false;
		} else {
			// Increment the request count.
			$user_model->update_meta( $this->count_key, $request_count + 1 );
		}

		return true;
	}
}
