<?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;
use Formatrica\Submission\Submission_Service;

/**
 * Honeypot + minimum-elapsed-time anti-bot checks (only when honeypot enabled).
 */
final class Anti_Bot_Stage implements Submission_Stage
{
    public function handle(Submission_Context $ctx): void
    {
        // Authenticated headless API requests have no browser artifacts
        // (honeypot/timestamp fields are render-time); the key auth is their
        // gate. Skip only once authenticated — a merely-requested (unverified)
        // headless request still runs the anti-bot checks.
        if (!empty($ctx->context['headless_authenticated'])) {
            return;
        }

        if (empty($ctx->options['honeypot'])) {
            return;
        }

        $form_id = $ctx->form_id;
        $request_data = $ctx->request_data;

        $honeypot_field = Submission_Service::honeypot_field_name($form_id);
        $honeypot = isset($request_data[$honeypot_field]) ? trim((string) $request_data[$honeypot_field]) : '';
        if ($honeypot !== '') {
            throw new Submission_Exception(esc_html__('Submission flagged as spam.', 'formatrica'), 400);
        }

        $timestamp_field = Submission_Service::timestamp_field_name($form_id);
        $rendered_at = isset($request_data[$timestamp_field]) ? (int) $request_data[$timestamp_field] : 0;
        $minimum_elapsed = apply_filters('formatrica_min_submission_time', 2, $form_id);
        if ($rendered_at > 0) {
            $elapsed = time() - $rendered_at;
            if ($elapsed >= 0 && $elapsed < (int) $minimum_elapsed) {
                throw new Submission_Exception(esc_html__('Submission received too quickly. Please try again.', 'formatrica'), 400);
            }
        }
    }
}
