<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

/**
 * Controller for Bricks Builder trigger endpoints.
 */
final class BricksBuilderController
{
    /**
     * Return form fields for a Bricks Builder form.
     *
     * Route: bricks-builder/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',
            'template_name' => 'Template Name',
        ];

        // Bricks stores form elements in post meta. Search templates for the form element.
        $bricksSettings = (array) get_option(
            defined('BRICKS_DB_GLOBAL_SETTINGS') ? BRICKS_DB_GLOBAL_SETTINGS : 'bricks_global_settings'
        );
        $postTypes   = $bricksSettings['postTypes'] ?? [];
        $postTypes[] = 'bricks_template';

        $templates = get_posts([
            'post_type'      => $postTypes,
            'post_status'    => 'publish',
            'posts_per_page' => -1,
        ]);

        foreach ($templates as $template) {
            $metaKey    = defined('BRICKS_DB_PAGE_CONTENT') ? BRICKS_DB_PAGE_CONTENT : '_bricks_page_content_2';
            $bbContents = get_post_meta($template->ID, $metaKey, true);
            if (!is_array($bbContents)) {
                continue;
            }
            foreach ($bbContents as $content) {
                if (isset($content['id']) && (string) $formId === (string) $content['id']) {
                    $contentFields = $content['settings']['fields'] ?? [];
                    foreach ($contentFields as $field) {
                        $label    = !empty($field['label']) ? $field['label'] : ($field['id'] ?? '');
                        $labelKey = strtolower(str_replace(' ', '_', trim((string) $label)));
                        if ($labelKey) {
                            $fields[$labelKey] = $label;
                        }
                    }
                    return Response::success(['fields' => $fields]);
                }
            }
        }

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