<?php

namespace EasyLinkAutomations\Triggers\HappyForms;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

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

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

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

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

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

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

    public static function getOutputFields(): array
    {
        return [
            'form_id'     => ['label' => 'Form ID', 'type' => 'number'],
            'user_id'     => ['label' => 'User ID', 'type' => 'number'],
            'user_login'  => ['label' => 'Username', 'type' => 'string'],
            'user_email'  => ['label' => 'User Email', 'type' => 'email'],
        ];
    }

    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('happyforms_get_form_controller')) {
            $controller = happyforms_get_form_controller();
            $forms      = $controller->do_get();
            if (is_array($forms)) {
                foreach ($forms as $form) {
                    $options[] = [
                        'value' => (string) ($form['ID'] ?? 0),
                        'label' => $form['post_title'] ?? ('Form #' . ($form['ID'] ?? 0)),
                    ];
                }
            }
        }

        return $options;
    }

    public function register(callable $callback): void
    {
        $this->callback = $callback;

        add_action('happyforms_submission_success', function ($submission, $form, $misc): void {
            try {
                if (!function_exists('happyforms_get_form_controller')) {
                    return;
                }
                $data = $this->handle($submission, $form, $misc);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] HappyForms trigger error: ' . $e->getMessage());
            }
        }, 20, 3);
    }

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

        if (!function_exists('happyforms_get_form_controller')) {
            return [];
        }

        $formId         = absint($form['ID'] ?? 0);
        $formController = happyforms_get_form_controller();
        $formData       = $formController->get($formId);
        $formFields     = [];

        if (is_array($formData) && !empty($formData['parts'])) {
            foreach ($formData['parts'] as $field) {
                $inputId    = $field['id'];
                $inputTitle = $field['label'];
                if (isset($submission[$inputId])) {
                    $formFields[$inputTitle] = $submission[$inputId];
                }
            }
        }

        $userId = get_current_user_id();
        $user   = $userId > 0 ? get_userdata($userId) : null;

        $context = [
            'form_id'    => $formId,
            'user_id'    => $userId,
            'user_login' => $user ? $user->user_login : '',
            'user_email' => $user ? $user->user_email : '',
        ];

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

        return $context;
    }
}
