<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

/**
 * Controller for Convert Pro trigger endpoints.
 */
final class ConvertProController
{
    /**
     * Return form fields for a specific Convert Pro popup/form.
     *
     * Route: convertpro/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);
        }

        if (!class_exists('Convert_Pro')) {
            return Response::error('Convert Pro is not active', 400);
        }

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

        $post = get_post($formId);
        if (!$post) {
            return Response::success(['fields' => $fields]);
        }

        // Convert Pro stores form configuration in post meta.
        $configure = get_post_meta($formId, 'configure', true);
        if (is_array($configure)) {
            foreach ($configure as $key => $value) {
                if (is_string($key) && !empty($key)) {
                    $fields[ucfirst($key)] = ucfirst($key);
                }
            }
        }

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