<?php

namespace EasyLinkAutomations\Triggers\WPForms;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user submits a WPForms form (fields keyed by field name).
 */
final class FormSubmittedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'wpforms/form_submitted';
    }

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

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

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

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

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

    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'],
            'submission_date' => ['label' => 'Submission Date', 'type' => 'datetime'],
        ];
    }

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

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

        $context = [
            'form_id'         => (int) ($formData['id'] ?? 0),
            'form_title'      => $formData['settings']['form_title'] ?? '',
            'entry_id'        => (int) $entryId,
            'submission_date' => isset($formData['created'])
                ? gmdate('d M Y', strtotime($formData['created']))
                : gmdate('d M Y'),
        ];

        foreach ($fields as $field) {
            if (($field['type'] ?? '') === 'name') {
                if (!empty($field['first']) || !empty($field['middle']) || !empty($field['last'])) {
                    if (!empty($field['first'])) {
                        $context['First Name'] = $field['first'];
                    }
                    if (!empty($field['middle'])) {
                        $context['Middle Name'] = $field['middle'];
                    }
                    if (!empty($field['last'])) {
                        $context['Last Name'] = $field['last'];
                    }
                } else {
                    $context[$field['name'] ?? ''] = $field['value'] ?? '';
                }
            } else {
                $context[$field['name'] ?? ''] = $field['value'] ?? '';
            }
        }

        return $context;
    }
}
