<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

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

        if (!class_exists('MetForm\Plugin')) {
            return Response::error('MetForm is not active', 400);
        }

        $fields = [
            'form_id' => 'Form ID',
        ];

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

        // MetForm stores form structure as Elementor data in post meta.
        $elementorData = get_post_meta($formId, '_elementor_data', true);
        if (!empty($elementorData)) {
            $widgets = is_string($elementorData) ? json_decode($elementorData, true) : $elementorData;
            if (is_array($widgets)) {
                $this->extractMetFormFields($widgets, $fields);
            }
        }

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

    /**
     * Recursively extract MetForm widget field names from Elementor data.
     */
    private function extractMetFormFields(array $elements, array &$fields): void
    {
        foreach ($elements as $element) {
            if (isset($element['widgetType']) && str_starts_with((string) $element['widgetType'], 'mf-')) {
                $name  = $element['settings']['mf_input_name'] ?? '';
                $label = $element['settings']['mf_input_label'] ?? $name;
                if ($name) {
                    $fields[$name] = $label ?: $name;
                }
            }
            if (!empty($element['elements']) && is_array($element['elements'])) {
                $this->extractMetFormFields($element['elements'], $fields);
            }
        }
    }
}
