<?php

namespace EasyLinkAutomations\Triggers\UltimateAddonsForGutenberg;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user submits a Spectra (Ultimate Addons for Gutenberg) form.
 */
final class UserSubmitFormTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'ultimate-addons-for-gutenberg/user_submit_form';
    }

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

    public static function getDescription(): string
    {
        return __('Fires when a user submits a Spectra (Ultimate Addons for Gutenberg) form.', 'easylink-automations');
    }

    public static function getCategory(): string
    {
        return 'Ultimate Addons for Gutenberg';
    }

    public static function getIcon(): string
    {
        return 'ultimate-addons-for-gutenberg';
    }

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

    public static function getOutputFields(): array
    {
        return [
            'form_id'      => ['label' => 'Form ID', 'type' => 'string'],
            'id'           => ['label' => 'Form Block ID', 'type' => 'string'],
            'spectra_form' => ['label' => 'Spectra Form ID', 'type' => 'string'],
        ];
    }

    public static function getConfigFields(): array
    {
        return [
            'form_id' => [
                'label'    => 'Select Form',
                'type'     => 'select',
                'options'  => static::getAvailableForms(),
                'required' => true,
            ],
        ];
    }

    private static function getAvailableForms(): array
    {
        global $wpdb;

        $options = [];
        $results = $wpdb->get_results(
            "SELECT ID, post_title, post_content FROM {$wpdb->posts}
             WHERE post_status = 'publish'
             AND post_content LIKE '%wp-block-uagb-forms%'",
            ARRAY_A
        );

        foreach ($results as $row) {
            $blocks = parse_blocks($row['post_content']);
            self::findUagbForms($blocks, $row['post_title'], $options);
        }

        return $options;
    }

    private static function findUagbForms(array $blocks, string $postTitle, array &$options): void
    {
        foreach ($blocks as $block) {
            if (($block['blockName'] ?? '') === 'uagb/forms') {
                $blockId = $block['attrs']['block_id'] ?? '';
                if ($blockId) {
                    $options[] = ['value' => $blockId, 'label' => $postTitle . ' (Block: ' . $blockId . ')'];
                }
            }
            if (!empty($block['innerBlocks'])) {
                self::findUagbForms($block['innerBlocks'], $postTitle, $options);
            }
        }
    }

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

        add_action('uagb_form_success', function (array $formData): void {
            try {
                if (empty($formData)) {
                    return;
                }
                $data = $this->handle($formData);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] UAG trigger error: ' . $e->getMessage());
            }
        }, 10, 1);
    }

    public function handle(mixed ...$args): array
    {
        [$formData] = $args;

        if (empty($formData)) {
            return [];
        }

        $formData['form_id']      = $formData['id'] ?? '';
        $formData['spectra_form'] = $formData['id'] ?? '';

        return $formData;
    }
}
