<?php

namespace EasyLinkAutomations\Triggers\KadenceForms;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a Kadence Blocks form is submitted.
 */
final class KadenceFormSubmitTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'kadence-forms/kadenceform_submitted';
    }

    public static function getName(): string
    {
        return __('Form Submitted', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Fires when a Kadence Blocks form is submitted.', 'easylink-automations');
    }

    public static function getCategory(): string
    {
        return 'Kadence Forms';
    }

    public static function getIcon(): string
    {
        return 'kadence-forms';
    }

    public static function isAvailable(): bool
    {
        return class_exists('Kadence_Blocks_Form_Block');
    }

    public static function getOutputFields(): array
    {
        return [
            'form_id' => ['label' => 'Form ID', 'type' => 'number'],
            'post_id' => ['label' => 'Post ID', 'type' => 'number'],
            'fields'  => ['label' => 'Form Fields', 'type' => 'json'],
        ];
    }

    public static function getConfigFields(): array
    {
        return [];
    }

    public function register(callable $callback): void
    {
        $this->callback = $callback;

        add_action('kadence_blocks_form_submission', function ($formArgs, $fields, $formId, $postId): void {
            try {
                $data = $this->handle($formArgs, $fields, $formId, $postId);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] KadenceForms trigger error: ' . $e->getMessage());
            }
        }, 10, 4);

        add_action('kadence_blocks_advanced_form_submission', function ($formArgs, $processedFields, $postId): void {
            try {
                $data = $this->handleAdvanced($formArgs, $processedFields, $postId);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] KadenceForms trigger error: ' . $e->getMessage());
            }
        }, 10, 3);
    }

    public function handle(mixed ...$args): array
    {
        [$formArgs, $fields, $formId, $postId] = $args;

        $context = [
            'form_id' => (int) $formId,
            'post_id' => (int) $postId,
        ];

        foreach ((array) $fields as $field) {
            $value = $field['value'] ?? '';
            if (strpos((string) $value, ', ') !== false) {
                $value = explode(', ', (string) $value);
            }
            $label           = str_replace([' ', '-'], '_', strtolower($field['label'] ?? ''));
            $context[$label] = $value;
        }

        return $context;
    }

    private function handleAdvanced(mixed $formArgs, mixed $processedFields, mixed $postId): array
    {
        $formId = isset($formArgs['attributes']['formID']) ? $formArgs['attributes']['formID'] : 'advanced_form';

        $context = [
            'form_id' => $formId,
            'post_id' => (int) $postId,
        ];

        foreach ((array) $processedFields as $field) {
            $label = str_replace([' ', '-'], '_', strtolower($field['label'] ?? ''));
            $value = $field['value'] ?? '';
            if (strpos((string) $value, ', ') !== false) {
                $value = explode(', ', (string) $value);
            }
            $context[$label] = $value;
        }

        return $context;
    }
}
