<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

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

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

        // Use WSForm API to get form fields if available.
        if (function_exists('wsf_form_get_form_object') && function_exists('wsf_form_get_fields')) {
            try {
                $formObject  = wsf_form_get_form_object($formId);
                $formFields  = wsf_form_get_fields($formObject);

                foreach ($formFields as $field) {
                    if (!isset($field->type)) {
                        continue;
                    }
                    if (property_exists($field, 'label') && property_exists($field, 'id')) {
                        $fields[$field->label] = $field->label;
                    }
                }
            } catch (\Throwable $e) {
                // WSForm API not available or form not found
            }
        }

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