<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

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

        $fields = [
            'form_id'          => 'Form ID',
            'form_title'       => 'Form Title',
            'entry_id'         => 'Entry ID',
            'entry_source_url' => 'Entry Source URL',
            'submission_date'  => 'Submission Date',
            'user_ip'          => 'User IP',
        ];

        $form = wpFluent()->table('fluentform_forms')->find($formId);
        if (!$form) {
            return Response::success(['fields' => $fields]);
        }

        $formFields = json_decode($form->form_fields, true);
        if (is_array($formFields) && !empty($formFields['fields'])) {
            foreach ($formFields['fields'] as $field) {
                $name  = $field['attributes']['name'] ?? '';
                $label = $field['settings']['label'] ?? $name;
                if ($name) {
                    $fields[$name] = $label ?: $name;
                }
            }
        }

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