<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

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

        $form = \GFAPI::get_form($formId);
        if (!$form || is_wp_error($form)) {
            return Response::error('Form not found', 404);
        }

        $fields = [
            'entry_id'     => 'Entry ID',
            'form_id'      => 'Form ID',
            'form_title'   => 'Form Title',
            'date_created' => 'Date Created',
            'source_url'   => 'Source URL',
            'ip'           => 'IP Address',
        ];

        if (!empty($form['fields'])) {
            foreach ($form['fields'] as $field) {
                $fields['field_' . $field->id] = $field->label;
            }
        }

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