<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

/**
 * Controller for Pie Forms trigger endpoints.
 */
final class PieFormsController
{
    /**
     * Return form fields for a specific Pie Forms form.
     *
     * Route: pie-forms/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('Pie_Forms')) {
            return Response::error('Pie Forms is not active', 400);
        }

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

        // Pie Forms stores form structure in post content as JSON.
        $form = get_post($formId);
        if ($form) {
            $formData = json_decode($form->post_content, true);
            if (is_array($formData) && !empty($formData['form_fields'])) {
                foreach ($formData['form_fields'] as $fieldId => $field) {
                    $label = $field['label'] ?? '';
                    $name  = $field['meta-key'] ?? $fieldId;
                    if ($name) {
                        $fields[$name] = $label ?: $name;
                    }
                }
            }
        }

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