<?php

namespace EasyLinkAutomations\Triggers\PieForms;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user submits a Pie Forms form.
 */
final class UserSubmitFormTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'pie-forms/user_submits_pieforms';
    }

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

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

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

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

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

    public static function getOutputFields(): array
    {
        return [
            'form_id'  => ['label' => 'Form ID', 'type' => 'number'],
            'entry_id' => ['label' => 'Entry ID', 'type' => 'number'],
            'fields'   => ['label' => 'Form Fields', 'type' => 'json'],
        ];
    }

    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'      => 'flavor',
            '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('pie_forms_complete_entry_save', function ($entryId, $fields, $entry, $formId, $formData): void {
            try {
                if (empty($formData)) {
                    return;
                }
                $data = $this->handle($entryId, $fields, $entry, $formId, $formData);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] PieForms trigger error: ' . $e->getMessage());
            }
        }, 10, 5);
    }

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

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

        $context            = [];
        $context['form_id'] = (int) $formId;
        $context['entry_id'] = (int) $entryId;

        foreach ((array) $formData as $value) {
            $context[$value['name']] = $value['value'];
        }

        return $context;
    }
}
