<?php

namespace Formatrica\Submission\Integrations\Dispatchers;

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

use Formatrica\Submission\Integrations\Http_Client;
use Formatrica\Submission\Integrations\Integration_Dispatcher_Interface;

/**
 * Dispatcher for generic webhooks (Zapier, Make, etc.)
 */
final class Generic_Webhook_Dispatcher implements Integration_Dispatcher_Interface
{
    private Http_Client $client;
    private string $integration_id;

    public function __construct(string $integration_id, ?Http_Client $client = null)
    {
        $this->integration_id = $integration_id;
        $this->client = $client ?? new Http_Client();
    }

    public function dispatch(array $settings, array $form, array $payload, array $context, array $field_meta): void
    {
        $webhook_url = isset($settings['webhook_url']) ? trim((string) $settings['webhook_url']) : '';

        if ($webhook_url === '') {
            return;
        }

        $body = [
            'form' => [
                'id' => $form['id'],
                'title' => $form['title'],
            ],
            'submission' => $payload,
            'meta' => $field_meta,
            'context' => $context,
            'integration' => $this->integration_id,
        ];

        $body = apply_filters('formatrica_webhook_payload', $body, $form, $payload, $context, $field_meta);

        // Edition extension point (Phase-5 completion): the Pro package adds
        // its authenticated-webhook headers (Make signed API key) via this
        // filter; the Free package sends none and never holds the send code.
        $extra_headers = (array) apply_filters('formatrica_webhook_extra_headers', [], $this->integration_id, $settings);

        $this->client->send_json($webhook_url, $body, $this->integration_id, $form, $payload, $context, 'POST', $extra_headers);
    }
}
