<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

/**
 * Controller for WPForms trigger endpoints.
 */
final class WPFormsController
{
    /**
     * Return form fields for a specific WPForms form.
     *
     * Route: wpforms/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 (!function_exists('wpforms_decode')) {
            return Response::error('WPForms is not active', 400);
        }

        $form = get_post($formId);
        if (!$form) {
            return Response::error('Form not found', 404);
        }

        $fields = [
            'form_id'         => 'Form ID',
            'form_title'      => 'Form Title',
            'entry_id'        => 'Entry ID',
            'submission_date' => 'Submission Date',
        ];

        $content    = wpforms_decode($form->post_content);
        $formFields = $content['fields'] ?? [];

        foreach ($formFields as $field) {
            $label = $field['label'] ?? ('Field ' . ($field['id'] ?? ''));
            $fields[$label] = $label;
        }

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