<?php

namespace EasyLinkAutomations\Triggers\JetFormBuilder;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a JetFormBuilder form is submitted successfully.
 */
final class FormSubmittedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'jetformbuilder/form_submitted';
    }

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

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

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

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

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

    public static function getOutputFields(): array
    {
        return [
            'form_id'     => ['label' => 'Form ID', 'type' => 'number'],
            'user_id'     => ['label' => 'User ID', 'type' => 'number'],
            'user_login'  => ['label' => 'Username', 'type' => 'string'],
            'user_email'  => ['label' => 'User Email', 'type' => 'email'],
        ];
    }

    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'      => 'jet-form-builder',
            '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('jet-form-builder/form-handler/after-send', function ($formHandler, $isSuccess): void {
            try {
                if (empty($formHandler->form_id)) {
                    return;
                }
                $data = $this->handle($formHandler, $isSuccess);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] JetFormBuilder trigger error: ' . $e->getMessage());
            }
        }, 10, 2);
    }

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

        if (empty($formHandler->form_id)) {
            return [];
        }

        $formFields = [];

        if (property_exists($formHandler->action_handler, 'request_data')) {
            foreach ($formHandler->action_handler->request_data as $fieldKey => $fieldValue) {
                if (str_starts_with((string) $fieldKey, '__')) {
                    continue;
                }
                if (is_string($fieldValue) && json_decode($fieldValue) !== null) {
                    $formFields[$fieldKey] = json_decode($fieldValue, true);
                } else {
                    $formFields[$fieldKey] = $fieldValue;
                }
            }
        }

        $userId = get_current_user_id();
        $user   = $userId > 0 ? get_userdata($userId) : null;

        $context = [
            'form_id'    => (int) $formHandler->form_id,
            'user_id'    => $userId,
            'user_login' => $user ? $user->user_login : '',
            'user_email' => $user ? $user->user_email : '',
        ];

        foreach ($formFields as $key => $value) {
            if (!isset($context[$key])) {
                $context[$key] = $value;
            }
        }

        return $context;
    }
}
