<?php
/**
 * Ownership-proof challenge — REST fallback exposure surface.
 *
 * Serves the same VPS-issued one-time verification nonce as the /.well-known
 * path, for hosts where that path is blocked but /wp-json still resolves. Public
 * by necessity (the VPS is unauthenticated when it fetches), but read-only,
 * single-value, and returns 404 when no handshake is pending — so it is not an
 * oracle: it accepts no input and reveals nothing beyond the live token.
 *
 * @package TamRank
 */

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

class TamRank_REST_Verify
{
    /**
     * @var string Same namespace as the rest of FREE's REST surface.
     */
    protected $namespace = 'tamrank/v1';

    /**
     * @var string
     */
    protected $rest_base = 'site-verify';

    /**
     * Register the public read route.
     *
     * @return void
     */
    public function register_routes()
    {
        register_rest_route(
            $this->namespace,
            '/' . $this->rest_base,
            array(
                array(
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => array($this, 'get_token'),
                    // Public: the VPS has no credential during first registration.
                    // Safe because the route is read-only, takes no params, and
                    // returns only the single live nonce (or 404).
                    'permission_callback' => '__return_true',
                ),
            )
        );
    }

    /**
     * Return the live nonce as { "token": "<nonce>" }, or 404 when none pending.
     *
     * @return WP_REST_Response
     */
    public function get_token()
    {
        if (!defined('DONOTCACHEPAGE')) {
            define('DONOTCACHEPAGE', true); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- WordPress-ecosystem standard constant read by caching plugins; must not be prefixed.
        }

        $nonce = function_exists('tamrank_get_pending_verify_nonce') ? tamrank_get_pending_verify_nonce() : '';

        if ($nonce === '') {
            $response = new WP_REST_Response(null, 404);
        } else {
            $response = new WP_REST_Response(array('token' => $nonce), 200);
        }

        // Keep caches/CDNs from serving a stale token.
        $response->header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
        $response->header('Pragma', 'no-cache');

        return $response;
    }
}
