<?php

namespace EasyLinkAutomations\Triggers\FormidableForms;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a Formidable Forms entry is created (form submitted).
 */
final class FormSubmittedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'formidable-forms/form_submitted';
    }

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

    public static function getDescription(): string
    {
        return __('Fires when a Formidable Forms entry is created after form submission.', 'easylink-automations');
    }

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

    public static function getIcon(): string
    {
        return 'formidable-forms';
    }

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

    public static function getOutputFields(): array
    {
        return [
            'form_id'         => ['label' => 'Form ID', 'type' => 'number'],
            'entry_id'        => ['label' => 'Entry 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('FrmForm')) {
            $forms = \FrmForm::getAll(['is_template' => 0, 'status' => 'published'], 'name ASC');
            if (is_array($forms)) {
                foreach ($forms as $form) {
                    $options[] = [
                        'value' => (string) $form->id,
                        'label' => $form->name ?: ('Form #' . $form->id),
                    ];
                }
            }
        }

        return $options;
    }

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

        add_action('frm_after_create_entry', function (int $entryId, int $formId): void {
            try {
                $data = $this->handle($entryId, $formId);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] FormidableForms trigger error: ' . $e->getMessage());
            }
        }, 20, 2);
    }

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

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

        $fields = [];

        if (class_exists('FrmEntryMeta')) {
            global $wpdb;
            $metas = \FrmEntryMeta::get_entry_meta_info($entryId);
            foreach ($metas as $meta) {
                $fieldId   = $meta->field_id;
                $fieldName = $wpdb->get_var(
                    $wpdb->prepare(
                        'SELECT name FROM ' . $wpdb->prefix . 'frm_fields WHERE id=%d',
                        $fieldId
                    )
                );
                $unserialized = @unserialize($meta->meta_value);
                $dataVal      = (false !== $unserialized) ? $unserialized : $meta->meta_value;
                if (is_array($dataVal)) {
                    foreach ($dataVal as $key => $val) {
                        $fields[$key] = $val;
                    }
                } else {
                    $fields[$fieldName] = $dataVal;
                }
            }
        }

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

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

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

        return $context;
    }
}
