<?php

namespace EasyLinkAutomations\Triggers\ContactForm7;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a Contact Form 7 form is submitted.
 */
final class FormSubmittedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'contact-form7/form_submitted';
    }

    public static function getName(): string
    {
        return __('Form Submitted', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Fires when a Contact Form 7 form is submitted successfully.', 'easylink-automations');
    }

    public static function getCategory(): string
    {
        return 'Contact Form 7';
    }

    public static function getIcon(): string
    {
        return 'contact-form7';
    }

    public static function isAvailable(): bool
    {
        return class_exists('WPCF7');
    }

    public static function getOutputFields(): array
    {
        return [
            'form_id'    => ['label' => 'Form ID', 'type' => 'number'],
            'form_name'  => ['label' => 'Form Name', 'type' => 'string'],
            'form_title' => ['label' => 'Form Title', 'type' => 'string'],
        ];
    }

    public static function getConfigFields(): array
    {
        return [
            'form_id' => [
                'label'    => 'Select Form',
                'type'     => 'select',
                'options'  => static::getAvailableForms(),
                'required' => true,
            ],
        ];
    }

    private static function getAvailableForms(): array
    {
        $options = [];

        $forms = get_posts([
            'post_type'      => 'wpcf7_contact_form',
            'posts_per_page' => -1,
            'post_status'    => 'publish',
            'orderby'        => 'title',
            'order'          => 'ASC',
        ]);

        foreach ($forms as $form) {
            $options[] = [
                'value' => (string) $form->ID,
                'label' => $form->post_title ?: ('Form #' . $form->ID),
            ];
        }

        return $options;
    }

    public function register(callable $callback): void
    {
        $this->callback = $callback;

        add_action('wpcf7_before_send_mail', function ($contactForm, $abort, $submission): void {
            try {
                if (!is_object($submission) || !method_exists($submission, 'get_posted_data')) {
                    return;
                }
                if (!is_object($contactForm) || !method_exists($contactForm, 'id')) {
                    return;
                }
                $data = $this->handle($contactForm, $abort, $submission);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] ContactForm7 trigger error: ' . $e->getMessage());
            }
        }, 99, 3);
    }

    public function handle(mixed ...$args): array
    {
        [$contactForm, $abort, $submission] = $args;

        if (!is_object($submission) || !method_exists($submission, 'get_posted_data')) {
            return [];
        }
        if (!is_object($contactForm) || !method_exists($contactForm, 'id')) {
            return [];
        }

        $submittedData = $submission->get_posted_data();

        $context = [
            'form_id'    => (int) $contactForm->id(),
            'form_name'  => method_exists($contactForm, 'name') ? (string) $contactForm->name() : '',
            'form_title' => method_exists($contactForm, 'title') ? (string) $contactForm->title() : '',
        ];

        // Flatten submitted fields to top level so placeholders like
        // {{your-email}} resolve directly against the trigger data.
        if (is_array($submittedData)) {
            foreach ($submittedData as $key => $value) {
                if (!isset($context[$key])) {
                    $context[$key] = $value;
                }
            }
        }

        return $context;
    }
}
