<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

/**
 * Controller for HappyForms trigger endpoints.
 */
final class HappyFormsController
{
    /**
     * Return form fields for a specific HappyForms form.
     *
     * Route: happyforms/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('happyforms_get_form_controller')) {
            return Response::error('HappyForms is not active', 400);
        }

        $fields = [
            'form_id'    => 'Form ID',
            'user_id'    => 'User ID',
            'user_login' => 'Username',
            'user_email' => 'User Email',
        ];

        $controller = happyforms_get_form_controller();
        $formData   = $controller->get($formId);

        if (is_array($formData) && !empty($formData['parts'])) {
            foreach ($formData['parts'] as $part) {
                $label = $part['label'] ?? '';
                if ($label) {
                    $fields[$label] = $label;
                }
            }
        }

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