<?php

/**
 * A simplified version of the WordPress nonce system
 *
 * @package Northmill_Express_Order
 */
declare (strict_types=1);
namespace Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Helpers;

/**
 * Class Simple_Nonce
 */
class Simple_Nonce
{
    /**
     * Creates a cryptographic token tied to a specific action and window of time.
     *
     * @param string|int $action Scalar value to add context to the nonce.
     * @return string The token.
     */
    public static function create(string|int $action = -1): string
    {
        $i = wp_nonce_tick($action);
        return self::generate_nonce_hash($i, $action);
    }
    /**
     * Verifies that a correct security nonce was used with time limit.
     *
     * A nonce is valid for 24 hours (by default).
     *
     * @since 2.0.3
     *
     * @param string     $nonce  The nonce value that was used for verification, usually via a form field.
     * @param string|int $action Should give context to what is taking place and be the same when nonce was created.
     * @return int|false 1 if the nonce is valid and generated between 0-12 hours ago,
     *                   2 if the nonce is valid and generated between 12-24 hours ago.
     *                   False if the nonce is invalid.
     */
    public static function verify(string $nonce, string|int $action = -1): int|false
    {
        if (empty($nonce)) {
            return \false;
        }
        $i = wp_nonce_tick($action);
        // Nonce generated 0-12 hours ago.
        $expected = self::generate_nonce_hash($i, $action);
        if (hash_equals($expected, $nonce)) {
            return 1;
        }
        // Nonce generated 12-24 hours ago.
        $expected = self::generate_nonce_hash($i - 1, $action);
        if (hash_equals($expected, $nonce)) {
            return 2;
        }
        // Invalid nonce.
        return \false;
    }
    /**
     * Generates a hashed nonce value based on a tick and action.
     *
     * @param float      $tick   The tick value used to generate the nonce.
     * @param string|int $action The action value used to generate the nonce.
     *
     * @return string  The hashed nonce value.
     */
    private static function generate_nonce_hash(float $tick, string|int $action): string
    {
        return substr(wp_hash($tick . '|' . $action . '|', 'nonce'), -12, 10);
    }
}
