<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

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

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

        $formFields = Ninja_Forms()->form($formId)->get_fields();
        if (is_array($formFields)) {
            foreach ($formFields as $field) {
                $key   = $field->get_setting('key');
                $label = $field->get_setting('label') ?: $key;
                if ($key) {
                    $fields[$key] = $label;
                }
            }
        }

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