<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

/**
 * Controller for Ultimate Addons for Gutenberg (Spectra) trigger endpoints.
 */
final class UAGController
{
    /**
     * Return form fields for a Spectra (UAG) form.
     *
     * Route: ultimate-addons-for-gutenberg/form-fields
     */
    public function formFields(Request $request): Response
    {
        $formId = $request->get('form_id', '');
        if (empty($formId)) {
            return Response::error('form_id is required', 400);
        }

        $fields = [
            'form_id'      => 'Form ID',
            'id'           => 'Form Block ID',
            'spectra_form' => 'Spectra Form ID',
        ];

        // Search posts containing this UAG form block to extract field definitions.
        global $wpdb;
        $results = $wpdb->get_results(
            "SELECT post_content FROM {$wpdb->posts}
             WHERE post_status = 'publish'
             AND post_content LIKE '%wp-block-uagb-forms%'",
            ARRAY_A
        );

        foreach ($results as $row) {
            $blocks = parse_blocks($row['post_content']);
            if ($this->extractFormFields($blocks, (string) $formId, $fields)) {
                break;
            }
        }

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

    /**
     * Recursively find the matching UAG form block and extract its inner field blocks.
     */
    private function extractFormFields(array $blocks, string $targetBlockId, array &$fields): bool
    {
        foreach ($blocks as $block) {
            if (($block['blockName'] ?? '') === 'uagb/forms') {
                $blockId = $block['attrs']['block_id'] ?? '';
                if ((string) $blockId === $targetBlockId && !empty($block['innerBlocks'])) {
                    foreach ($block['innerBlocks'] as $innerBlock) {
                        $name  = $innerBlock['blockName'] ?? '';
                        $attrs = $innerBlock['attrs'] ?? [];
                        // UAG inner blocks are named like uagb/forms-name, uagb/forms-email, etc.
                        if (str_starts_with($name, 'uagb/forms-')) {
                            $fieldType = str_replace('uagb/forms-', '', $name);
                            $label     = $attrs['name'] ?? $attrs['label'] ?? ucfirst($fieldType);
                            $key       = strtolower(str_replace(' ', '_', $label));
                            $fields[$key] = $label;
                        }
                    }
                    return true;
                }
            }
            if (!empty($block['innerBlocks'])) {
                if ($this->extractFormFields($block['innerBlocks'], $targetBlockId, $fields)) {
                    return true;
                }
            }
        }

        return false;
    }
}
