<?php

namespace EasyLinkAutomations\Triggers\WSForm;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user submits a WS Form.
 */
final class UserSubmitsWSFormTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'ws-form/user_submits_ws_form';
    }

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

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

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

    public static function getIcon(): string
    {
        return 'ws-form';
    }

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

    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'      => 'ws_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('wsf_submit_post_complete', function (object $formSubmit): void {
            try {
                $data = $this->handle($formSubmit);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] WSForm trigger error: ' . $e->getMessage());
            }
        }, 10, 1);
    }

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

        if (empty($formSubmit) || !property_exists($formSubmit, 'form_id')) {
            return [];
        }

        $context = [];

        if (property_exists($formSubmit, 'form_object')) {
            if (function_exists('wsf_form_get_fields')) {
                $fields = wsf_form_get_fields($formSubmit->form_object);
                foreach ($fields as $field) {
                    if (!isset($field->type)) {
                        continue;
                    }
                    $fieldType = $field->type;

                    if (function_exists('wsf_config_get_field_types')) {
                        $fieldTypes = wsf_config_get_field_types();
                        if (!isset($fieldTypes[$fieldType])) {
                            continue;
                        }
                        $fieldTypeConfig = $fieldTypes[$fieldType];
                        $submitSave      = $fieldTypeConfig['submit_save'] ?? false;
                        if (!$submitSave) {
                            continue;
                        }
                    }

                    if (property_exists($field, 'id')) {
                        $fieldName = $field->id;
                        if (function_exists('wsf_submit_get_value')) {
                            $fieldValue = wsf_submit_get_value($formSubmit, 'field_' . $fieldName);
                            if (property_exists($field, 'label')) {
                                $context[$field->label] = $fieldValue;
                            }
                        }
                    }
                }
            }
        }

        $context['form_id'] = absint($formSubmit->form_id);

        return $context;
    }
}
