<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

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

        $model = \Forminator_API::get_form($formId);
        if (is_wp_error($model) || empty($model)) {
            return Response::error('Form not found', 404);
        }

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

        $formFields = $model->get_fields();
        if (is_array($formFields)) {
            foreach ($formFields as $field) {
                $slug  = $field->slug ?? '';
                $label = $field->field_label ?? $slug;
                if ($slug) {
                    $fields[$slug] = $label;
                }
            }
        }

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