<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

/**
 * Controller for SureForms trigger endpoints.
 */
final class SureFormsController
{
    /**
     * Return form fields for a specific SureForms form.
     *
     * Route: sureforms/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',
            'form_title' => 'Form Title',
            'entry_id'   => 'Entry ID',
        ];

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

        // SureForms stores fields as Gutenberg blocks in post_content.
        $blocks = parse_blocks($form->post_content);
        $this->extractSureFormsFields($blocks, $fields);

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

    /**
     * Recursively extract field names from SureForms blocks.
     */
    private function extractSureFormsFields(array $blocks, array &$fields): void
    {
        foreach ($blocks as $block) {
            $name = $block['blockName'] ?? '';
            if (!empty($name) && str_starts_with($name, 'srfm/')) {
                $label    = $block['attrs']['label'] ?? '';
                $fieldSlug = $block['attrs']['slug'] ?? '';
                if ($fieldSlug) {
                    $fields[$fieldSlug] = $label ?: $fieldSlug;
                } elseif ($label) {
                    $key = sanitize_title($label);
                    $fields[$key] = $label;
                }
            }
            if (!empty($block['innerBlocks']) && is_array($block['innerBlocks'])) {
                $this->extractSureFormsFields($block['innerBlocks'], $fields);
            }
        }
    }
}
