<?php

namespace EasyLinkAutomations\Triggers\MetForm;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user submits a MetForm form.
 */
final class UserSubmitFormTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'metform/user_submits_metform';
    }

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

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

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

    public static function getIcon(): string
    {
        return 'metform';
    }

    public static function isAvailable(): bool
    {
        return class_exists('MetForm\Plugin');
    }

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

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

    private static function getAvailableForms(): array
    {
        $options = [];

        $forms = get_posts([
            'post_type'      => 'metform-form',
            'posts_per_page' => -1,
            'post_status'    => 'publish',
            'orderby'        => 'title',
            'order'          => 'ASC',
        ]);

        foreach ($forms as $form) {
            $options[] = [
                'value' => (string) $form->ID,
                'label' => $form->post_title ?: ('Form #' . $form->ID),
            ];
        }

        return $options;
    }

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

        add_action('metform_after_store_form_data', function ($formId, $formData, $formSettings, $attributes): void {
            try {
                if (empty($formId)) {
                    return;
                }
                $data = $this->handle($formId, $formData, $formSettings, $attributes);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] MetForm trigger error: ' . $e->getMessage());
            }
        }, 10, 4);
    }

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

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

        $context            = (array) $formData;
        $context['form_id'] = (int) $formId;

        return $context;
    }
}
