<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

/**
 * Controller for Meta Box trigger endpoints.
 */
final class MetaBoxController
{
    /**
     * Return form fields for a Meta Box frontend form submission.
     *
     * Route: metabox/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);
        }

        // Meta Box frontend form fields are based on post type meta fields.
        $fields = [
            'form_id'    => 'Form ID',
            'post_id'    => 'Post ID',
            'post_title' => 'Post Title',
            'post_url'   => 'Post URL',
            'post_type'  => 'Post Type',
        ];

        // If rwmb_get_object_fields function exists, try to get meta box fields for the post.
        if (function_exists('rwmb_get_object_fields')) {
            $post = get_post($formId);
            if ($post) {
                $metaFields = rwmb_get_object_fields($post);
                if (is_array($metaFields)) {
                    foreach ($metaFields as $field) {
                        $id    = $field['id'] ?? '';
                        $label = $field['name'] ?? $id;
                        if ($id) {
                            $fields['form_' . $id] = $label ?: $id;
                        }
                    }
                }
            }
        }

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