<?php

namespace EasyLinkAutomations\HTTP\Controllers\Triggers;

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

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

/**
 * Controller for Contact Form 7 trigger endpoints.
 */
final class ContactForm7Controller
{
    /**
     * Return form fields for a specific Contact Form 7 form.
     *
     * Route: contact-form7/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('WPCF7_ContactForm')) {
            return Response::error('Contact Form 7 is not active', 400);
        }

        $form = \WPCF7_ContactForm::get_instance($formId);
        if (!$form) {
            return Response::error('Form not found', 404);
        }

        $fields = [
            'form_id'    => 'Form ID',
            'form_name'  => 'Form Name',
            'form_title' => 'Form Title',
        ];

        $tags = $form->scan_form_tags();
        foreach ($tags as $tag) {
            if (empty($tag->name)) {
                continue;
            }
            $fields[$tag->name] = $tag->name;
        }

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