<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

/**
 * Controller for JetFormBuilder trigger endpoints.
 */
final class JetFormBuilderController
{
    /**
     * Return form fields for a specific JetFormBuilder form.
     *
     * Route: jetformbuilder/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);
        }

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

        $form = get_post($formId);
        if (!$form) {
            return Response::success(['fields' => $fields]);
        }

        // JetFormBuilder stores fields as blocks in post_content.
        // Fields may be nested inside container/column blocks, so
        // we recursively walk the full block tree.
        $blocks = parse_blocks($form->post_content);
        $this->extractFieldBlocks($blocks, $fields);

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

    /**
     * Recursively extract field names from nested block structures.
     */
    private function extractFieldBlocks(array $blocks, array &$fields): void
    {
        foreach ($blocks as $block) {
            $name  = $block['attrs']['name'] ?? '';
            $label = $block['attrs']['label'] ?? $name;
            if ($name && !str_starts_with($name, '__')) {
                $fields[$name] = $label ?: $name;
            }
            if (!empty($block['innerBlocks'])) {
                $this->extractFieldBlocks($block['innerBlocks'], $fields);
            }
        }
    }
}
