<?php
/**
 * Non-blocking polling job for a Pay4All Form TWINT order.
 *
 * Mirrors Checkout\MonitorJob (the WC equivalent). The original action
 * `p4all_form_monitor_order` is fired by FormDomainEvents::spawn_monitor_order_task
 * after start_order() succeeds; WP_Async_Task's launch() catches it,
 * spawns an HTTP loopback to admin-post.php?action=wp_async_p4all_form_monitor_order,
 * and returns. The original AJAX request that started the payment is no
 * longer blocked by the SOAP polling — the customer is redirected to TWINT
 * immediately.
 *
 * The actual polling work runs on `wp_async_p4all_form_monitor_order`, which
 * FormBackgroundMonitor handles via FormTwintCore.
 */

namespace Twnt4All\Pay4All;

use Twnt4All\Support\Journal;
use Twnt4All\Vendor\AsyncTask\WP_Async_Task;

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

final class FormMonitorJob extends WP_Async_Task
{
    protected $action = 'p4all_form_monitor_order';

    protected function prepare_data( $data )
    {
        return [
            'order_id'   => $data[ 0 ] ?? 0,
            'order_uuid' => $data[ 1 ] ?? '',
            'time'       => $data[ 2 ] ?? 0,
        ];
    }

    protected function run_action()
    {
        Journal::event( sprintf( 'Running async task %1$s', $this->action ) );
        // Redundant defensive nonce check inside run_action() itself so the
        // origin verification is co-located with the $_POST reads below.
        // handle_postback() already verifies this same nonce upstream ; the
        // duplicate call makes the CSRF guard obvious to code readers.
        // Plugin Check does not recognize WP_Async_Task::verify_async_nonce()
        // as a nonce verification function, so the phpcs:disable below
        // silences the false positive.
        // phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce verified in the same function via $this->verify_async_nonce($async_nonce) on the very next line ; static analyzers do not follow custom nonce helpers.
        $async_nonce = isset( $_POST[ '_nonce' ] ) ? sanitize_text_field( wp_unslash( (string) $_POST[ '_nonce' ] ) ) : '';
        if ( ! $this->verify_async_nonce( $async_nonce ) ) {
            return;
        }
        // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- vendor Async-Task pattern ; hook name is derived from $this->action.
        do_action(
            'wp_async_' . $this->action,
            absint( $_POST[ 'order_id' ] ?? 0 ),
            sanitize_text_field( wp_unslash( (string) ( $_POST[ 'order_uuid' ] ?? '' ) ) ),
            absint( $_POST[ 'time' ] ?? 0 )
        );
        // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound,WordPress.Security.NonceVerification.Missing
    }
}
