<?php

namespace EasyLinkAutomations\Triggers\FluentForm;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

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

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

    public static function getDescription(): string
    {
        return __('Fires for each field when a Fluent Form is submitted, allowing filtering by field value.', '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'],
            'field_id'         => ['label' => 'Field ID', 'type' => 'string'],
            'field_value'      => ['label' => 'Field Value', '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 {
            if (empty($form)) {
                return;
            }
            $results = $this->handle($insert_data, $data, $form);
            foreach ($results as $result) {
                if (!empty($result)) {
                    $this->fire($result);
                }
            }
        }, 10, 3);
    }

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

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

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

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

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

        $results = [];
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $k => $v) {
                    $ctx              = $base;
                    $ctx['field_id']  = $k;
                    $ctx['field_value'] = $v;
                    $results[]        = $ctx;
                }
            } else {
                $ctx              = $base;
                $ctx['field_id']  = $key;
                $ctx['field_value'] = $value;
                $results[]        = $ctx;
            }
        }

        return $results;
    }
}
