<?php

namespace EasyLinkAutomations\Triggers\SureForms;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a SureForms form is submitted.
 */
final class SureFormsFormSubmittedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'sureforms/sureforms_form_submitted';
    }

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

    public static function getDescription(): string
    {
        return __('Fires when a SureForms form is submitted.', 'easylink-automations');
    }

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

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

    public static function isAvailable(): bool
    {
        return class_exists('SRFM\Inc\Plugin');
    }

    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'],
            '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'      => 'sureforms_form',
            '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('srfm_form_submit', function ($response): void {
            try {
                if (empty($response)) {
                    return;
                }
                $data = $this->handle($response);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] SureForms trigger error: ' . $e->getMessage());
            }
        }, 10, 1);
    }

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

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

        $data = (array) $response;
        $data['form_id'] = (int) ($data['form_id'] ?? 0);

        return $data;
    }
}
