<?php

namespace EasyLinkAutomations\Triggers\FluentForm;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

final class FormSubmittedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'fluent-form/user_submits_fluentform';
    }

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

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

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

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

    public static function isAvailable(): bool
    {
        return defined('FLUENTFORM') || class_exists('\FluentForm\App\Modules\Form\FormFieldsParser');
    }

    public static function getOutputFields(): array
    {
        return [
            'form_id'          => ['label' => 'Form ID', 'type' => 'number'],
            'form_title'       => ['label' => 'Form Title', 'type' => 'string'],
            'entry_id'         => ['label' => 'Entry ID', 'type' => 'number'],
            'entry_source_url' => ['label' => 'Entry Source URL', 'type' => 'string'],
            'submission_date'  => ['label' => 'Submission Date', 'type' => 'string'],
            'user_ip'          => ['label' => 'User IP', 'type' => 'string'],
        ];
    }

    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 (function_exists('wpFluent')) {
            $forms = wpFluent()->table('fluentform_forms')
                ->select(['id', 'title'])
                ->orderBy('title', 'ASC')
                ->get();

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

        return $options;
    }

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

        add_action('fluentform/before_insert_submission', function ($insert_data, $data, $form): void {
            try {
                if (empty($form)) {
                    return;
                }
                $result = $this->handle($insert_data, $data, $form);
                if (empty($result)) {
                    return;
                }
                $this->fire($result);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] FluentForm trigger error: ' . $e->getMessage());
            }
        }, 10, 3);
    }

    public function handle(mixed ...$args): array
    {
        [$insert_data, $data, $form] = $args;

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

        $context = (array) json_decode($insert_data['response'], true);

        $context['form_id'] = (int) ($form->id ?? 0);
        if (isset($form->title)) {
            $context['form_title'] = $form->title;
        }

        $context['entry_id']         = $insert_data['serial_number'];
        $context['entry_source_url'] = $insert_data['source_url'];
        $context['submission_date']  = $insert_data['created_at'];
        $context['user_ip']          = $insert_data['ip'];

        return $context;
    }
}
