<?php

namespace EasyLinkAutomations\Triggers\Forminator;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

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

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

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

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

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

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

    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 = [];

        if (class_exists('Forminator_API')) {
            $forms = \Forminator_API::get_forms(null, 1, -1);
            if (is_array($forms)) {
                foreach ($forms as $form) {
                    $options[] = [
                        'value' => (string) $form->id,
                        'label' => $form->settings['formName'] ?? ('Form #' . $form->id),
                    ];
                }
            }
        }

        return $options;
    }

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

        add_action('forminator_custom_form_submit_before_set_fields', function ($entry, $formId, $fieldDataArray): void {
            try {
                $data = $this->handle($entry, $formId, $fieldDataArray);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] Forminator trigger error: ' . $e->getMessage());
            }
        }, 10, 3);
    }

    public function handle(mixed ...$args): array
    {
        [$entry, $formId, $fieldDataArray] = $args;

        $formFields = [];
        foreach ((array) $fieldDataArray as $field) {
            if (!isset($field['name']) || !isset($field['value'])) {
                continue;
            }
            $formFields[$field['name']] = $field['value'];
        }

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

        $context = [
            'form_id'    => (int) $formId,
            '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;
    }
}
