<?php
/**
 * A class of utilities for dealing with outgoing Webhooks.
 *
 * @since 3.0.0
 */

declare(strict_types=1);
namespace FeData\FastEvents\Utilities;

/**
 * A class of utilities for dealing with JSON.
 */
class WebhookUtil {

	/**

	 * Create a new action in the Action Scheduler to handle a webhook.
	 *
	 * @since 1.0
	 * @since 2.3.0 Use fast_events_json_encode.
	 *
	 * @param string $topic     Webhook for eg 'order.created', ....
	 * @param mixed  $arg       Argument (event_id, order_id, or qrcode with level structure).
	 */
	public static function create_webhook( string $topic, mixed $arg ): void {
		global $wpdb;

		// Check if there are active webhooks for this topic.
		$webhooks = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}fe_event_webhooks WHERE topic = %s AND status = 1", $topic ) );
		if ( null === $webhooks ) {
			return;
		}

		// Walk through all webhooks.
		foreach ( $webhooks as $webhook ) {

			// Update pending counter.
			$result = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->prefix}fe_event_webhooks SET pending = pending + 1 WHERE id = %d", $webhook->id ) );
			if ( false === $result || 0 === $result ) {
				continue;
			}

			// Queue the action.
			as_enqueue_async_action(
				'fast_events_action_webhook',
				array(
					'webhook_id'     => (int) $webhook->id,
					'arg'            => $arg,
					'retry_scheme'   => array_map( 'intval', explode( ',', $webhook->retry_scheme ) ),
					'retry_position' => -1,
				),
				'fast-events-webhook-' . $topic
			);
		}
	}
}
