<?php

namespace EasyLinkAutomations\Triggers\ConvertPro;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a Convert Pro form is submitted.
 */
final class FormSubmittedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'convertpro/form_submitted';
    }

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

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

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

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

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

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

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

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

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

        $styleId    = isset($postData['style_id']) ? (int) sanitize_text_field((string) $postData['style_id']) : 0;
        $formFields = [];

        if (isset($postData['param']) && is_array($postData['param'])) {
            foreach ($postData['param'] as $key => $value) {
                $formFields[ucfirst((string) $key)] = $value;
            }
        }

        $context = [
            'form_id' => $styleId,
        ];

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

        return $context;
    }
}
