<?php
/**
 * Stateless email-link token for the "Return this order" button included in
 * WooCommerce customer emails.
 *
 * The token lets a guest customer click the button in their order
 * confirmation mail and land directly on the wizard, without having to
 * re-enter their email + order number on the verify form. Logged-in users
 * get the wizard via the standard ?order=ID flow; guests get it via this
 * HMAC token.
 *
 * Token = first 32 hex chars of HMAC-SHA256(secret, "fill|<order_id>") with
 * a per-site secret persisted in `wpnest_rfw_email_link_secret`.
 * Deterministic — no DB storage of tokens themselves, validation is one
 * hash + hash_equals(). Rotating the option invalidates every email link
 * already in circulation (useful after an incident).
 *
 * @package WPNest_Returns_For_WooCommerce
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class WPNest_RFW_Email_Token {

    const OPTION = 'wpnest_rfw_email_link_secret';

    public static function make( $order_id ) {
        $order_id = (int) $order_id;
        if ( $order_id <= 0 ) {
            return '';
        }
        return substr( hash_hmac( 'sha256', 'fill|' . $order_id, self::secret() ), 0, 32 );
    }

    public static function validate( $order_id, $token ) {
        $token = (string) $token;
        if ( '' === $token || ! preg_match( '/^[a-f0-9]{32}$/', $token ) ) {
            return false;
        }
        return hash_equals( self::make( $order_id ), $token );
    }

    private static function secret() {
        $secret = get_option( self::OPTION, '' );
        if ( ! is_string( $secret ) || strlen( $secret ) < 32 ) {
            $secret = wp_generate_password( 64, false );
            update_option( self::OPTION, $secret, false );
        }
        return $secret;
    }
}
