<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

/**
 * Controller for Divi Builder trigger endpoints.
 */
final class DiviBuilderController
{
    /**
     * Return form fields for a Divi Builder contact form.
     *
     * Route: divi-builder/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);
        }

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

        $post = get_post($formId);
        if ($post && !empty($post->post_content)) {
            $this->extractDiviFormFields($post->post_content, $fields);
        }

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

    /**
     * Parse Divi shortcode content to extract contact form field names.
     */
    private function extractDiviFormFields(string $content, array &$fields): void
    {
        // Match et_pb_contact_field shortcodes within contact forms.
        if (preg_match_all('/\[et_pb_contact_field[^\]]*\]/s', $content, $matches)) {
            foreach ($matches[0] as $shortcode) {
                $fieldId    = '';
                $fieldLabel = '';

                if (preg_match('/field_id="([^"]*)"/', $shortcode, $m)) {
                    $fieldId = $m[1];
                }
                if (preg_match('/field_title="([^"]*)"/', $shortcode, $m)) {
                    $fieldLabel = $m[1];
                }

                if ($fieldId) {
                    $key          = strtolower(str_replace(' ', '_', $fieldId));
                    $fields[$key] = $fieldLabel ?: $fieldId;
                }
            }
        }
    }
}
