<?php

namespace Formatrica\Submission\Pipeline\Stages;

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

use Formatrica\Submission\Exception\Submission_Exception;
use Formatrica\Submission\Pipeline\Submission_Context;
use Formatrica\Submission\Pipeline\Submission_Stage;

/**
 * Verify the per-form submission nonce.
 */
final class Token_Validation_Stage implements Submission_Stage
{
    public function handle(Submission_Context $ctx): void
    {
        // Headless API requests (Pro api.headless): the browser nonce is skipped
        // ONLY once the Pro Headless_Auth_Stage has authenticated the key and set
        // 'headless_authenticated'. A request that merely CARRIES the API-key
        // header ('headless_requested') but was never authenticated — e.g. any
        // request to a Free package, where no auth stage exists — fails closed
        // here rather than bypassing the nonce.
        if (!empty($ctx->context['headless_requested'])) {
            if (!empty($ctx->context['headless_authenticated'])) {
                return;
            }
            throw new Submission_Exception(esc_html__('Security verification failed. Please refresh and retry.', 'formatrica'), 403);
        }

        $nonce = $ctx->request_data['_fmt_nonce'] ?? '';
        if (!is_string($nonce) || !wp_verify_nonce($nonce, 'formatrica_submit_' . $ctx->form_id)) {
            throw new Submission_Exception(esc_html__('Security verification failed. Please refresh and retry.', 'formatrica'), 403);
        }
    }
}
