<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

use EasyLinkAutomations\HTTP\Request\Request;
use EasyLinkAutomations\HTTP\Response;

/**
 * Controller for MailPoet trigger endpoints.
 */
final class MailPoetController
{
    /**
     * Return form fields for a specific MailPoet form.
     *
     * Route: mailpoet/form-fields
     */
    public function formFields(Request $request): Response
    {
        $formId = (int) $request->get('form_id', 0);
        if ($formId <= 0) {
            return Response::error('form_id is required', 400);
        }

        $fields = [
            'form_id'    => 'Form ID',
            'form_title' => 'Form Title',
        ];

        if (!class_exists('\MailPoet\API\API')) {
            return Response::success(['fields' => $fields]);
        }

        try {
            $mailpoet         = \MailPoet\API\API::MP('v1');
            $subscriberFields = $mailpoet->getSubscriberFields();
            if (is_array($subscriberFields)) {
                foreach ($subscriberFields as $field) {
                    $id   = $field['id'] ?? '';
                    $name = $field['name'] ?? $id;
                    if ($id) {
                        $fields[$id] = $name;
                    }
                }
            }
        } catch (\Exception $e) {
            // MailPoet API not available
        }

        return Response::success(['fields' => $fields]);
    }
}
