<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

/**
 * Controller for Elementor Pro trigger endpoints.
 */
final class ElementorProController
{
    /**
     * Return form fields for an Elementor Pro form.
     *
     * Route: elementor-pro/form-fields
     */
    public function formFields(Request $request): Response
    {
        $formId = $request->get('form_id', '');
        if (empty($formId)) {
            return Response::error('form_id is required', 400);
        }

        // Elementor form_id is a composite string: "postId_formId".
        // Return standard output fields.
        $fields = [
            'form_id'   => 'Form ID',
            'form_name' => 'Form Name',
        ];

        // Try to extract post ID from composite form_id and read Elementor data.
        $parts  = explode('_', (string) $formId, 2);
        $postId = (int) ($parts[0] ?? 0);

        if ($postId > 0) {
            $elementorData = get_post_meta($postId, '_elementor_data', true);
            if (!empty($elementorData)) {
                $widgets = is_string($elementorData) ? json_decode($elementorData, true) : $elementorData;
                if (is_array($widgets)) {
                    $this->extractFormFields($widgets, $formId, $fields);
                }
            }
        }

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

    /**
     * Recursively find the matching Elementor form widget and extract its fields.
     *
     * The targetFormId is a composite "postId_widgetFormId". Elementor doesn't
     * always store form_post_id in the saved JSON (it's a runtime property),
     * so we match by the widget's settings.id against the second part of the
     * composite ID.
     */
    private function extractFormFields(array $elements, string $targetFormId, array &$fields): void
    {
        // Extract the widget form ID part from the composite "postId_widgetFormId".
        $parts          = explode('_', $targetFormId, 2);
        $targetWidgetId = $parts[1] ?? $targetFormId;

        foreach ($elements as $element) {
            if (isset($element['widgetType']) && $element['widgetType'] === 'form') {
                $settings = $element['settings'] ?? [];
                $elFormId = $settings['id'] ?? '';

                if ($elFormId === $targetWidgetId) {
                    $formFields = $settings['form_fields'] ?? [];
                    foreach ($formFields as $field) {
                        $key = str_replace(' ', '_', strtolower($field['custom_id'] ?? $field['_id'] ?? ''));
                        $label = $field['field_label'] ?? $key;
                        if ($key) {
                            $fields[$key] = $label ?: $key;
                        }
                    }
                    return;
                }
            }
            if (!empty($element['elements']) && is_array($element['elements'])) {
                $this->extractFormFields($element['elements'], $targetFormId, $fields);
            }
        }
    }
}
