<?php
/**
 * Lightweight cooldown helper for the magic-link request form.
 *
 * Uses WordPress transients keyed by a stable hash so users can request
 * a fresh link no more than once per cooldown window.
 *
 * @package KaizenCoders\MagicLink
 */

namespace KaizenCoders\MagicLink;

class Cooldown {

	/**
	 * Default cooldown window in seconds.
	 */
	const DEFAULT_WINDOW = 30;

	/**
	 * Build the transient key.
	 *
	 * @param  string $identifier Usually the user email or IP.
	 * @param  string $scope      Free-form context (e.g. 'magic_link_request').
	 *
	 * @return string
	 */
	public static function key( $identifier, $scope = 'magic_link_request' ) {
		return 'kc_ml_cd_' . md5( $scope . '|' . strtolower( (string) $identifier ) );
	}

	/**
	 * True if the caller is still inside the cooldown window.
	 *
	 * @param  string $identifier Email or IP.
	 * @param  string $scope      Cooldown scope.
	 *
	 * @return bool
	 */
	public static function in_cooldown( $identifier, $scope = 'magic_link_request' ) {
		if ( ! function_exists( 'get_transient' ) ) {
			return false;
		}
		return false !== get_transient( self::key( $identifier, $scope ) );
	}

	/**
	 * Seconds remaining in the current cooldown window, or 0 when not cooling.
	 *
	 * @param  string $identifier Email or IP.
	 * @param  string $scope      Cooldown scope.
	 *
	 * @return int
	 */
	public static function remaining( $identifier, $scope = 'magic_link_request' ) {
		if ( ! function_exists( 'get_transient' ) || ! function_exists( 'wp_cache_get' ) ) {
			return 0;
		}
		$key = self::key( $identifier, $scope );
		$ttl = get_transient( $key . '_until' );
		if ( false === $ttl ) {
			return 0;
		}
		return max( 0, (int) $ttl - time() );
	}

	/**
	 * Start a cooldown window.
	 *
	 * @param  string $identifier Email or IP.
	 * @param  int    $seconds    Window length.
	 * @param  string $scope      Cooldown scope.
	 *
	 * @return void
	 */
	public static function start( $identifier, $seconds = self::DEFAULT_WINDOW, $scope = 'magic_link_request' ) {
		if ( ! function_exists( 'set_transient' ) ) {
			return;
		}
		$key = self::key( $identifier, $scope );
		set_transient( $key, 1, $seconds );
		set_transient( $key . '_until', time() + $seconds, $seconds );
	}

	/**
	 * Clear an active cooldown.
	 *
	 * @param  string $identifier Email or IP.
	 * @param  string $scope      Cooldown scope.
	 *
	 * @return void
	 */
	public static function clear( $identifier, $scope = 'magic_link_request' ) {
		if ( ! function_exists( 'delete_transient' ) ) {
			return;
		}
		$key = self::key( $identifier, $scope );
		delete_transient( $key );
		delete_transient( $key . '_until' );
	}
}
