<?php

namespace EasyLinkAutomations\Triggers\ElementorPro;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user submits an Elementor Pro form.
 */
final class FormSubmittedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'elementor-pro/form_submitted';
    }

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

    public static function getDescription(): string
    {
        return __('Fires when a user submits an Elementor Pro form.', 'easylink-automations');
    }

    public static function getCategory(): string
    {
        return 'Elementor Pro';
    }

    public static function getIcon(): string
    {
        return 'elementor-pro';
    }

    public static function isAvailable(): bool
    {
        return class_exists('ElementorPro\Plugin');
    }

    public static function getOutputFields(): array
    {
        return [
            'form_id'   => ['label' => 'Form ID', 'type' => 'string'],
            'form_name' => ['label' => 'Form Name', '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
    {
        global $wpdb;

        $options = [];
        $results = $wpdb->get_results(
            "SELECT pm.post_id, pm.meta_value, p.post_title
             FROM {$wpdb->postmeta} pm
             LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
             WHERE p.post_status = 'publish'
             AND pm.meta_key = '_elementor_data'
             AND pm.meta_value LIKE '%\"widgetType\":\"form\"%'",
            ARRAY_A
        );

        foreach ($results as $row) {
            $data = json_decode($row['meta_value'], true);
            if (is_array($data)) {
                self::findFormWidgets($data, (int) $row['post_id'], $row['post_title'], $options);
            }
        }

        return $options;
    }

    private static function findFormWidgets(array $elements, int $postId, string $postTitle, array &$options): void
    {
        foreach ($elements as $element) {
            if (($element['widgetType'] ?? '') === 'form') {
                $settings    = $element['settings'] ?? [];
                $formName    = $settings['form_name'] ?? 'Unnamed Form';
                // Widget ID is at element top level, not inside settings.
                // At runtime Elementor copies it to form_settings['id'].
                $formId      = $element['id'] ?? '';
                $compositeId = $postId . '_' . $formId;
                $options[]   = ['value' => $compositeId, 'label' => $formName . ' (' . $postTitle . ')'];
            }
            if (!empty($element['elements'])) {
                self::findFormWidgets($element['elements'], $postId, $postTitle, $options);
            }
        }
    }

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

        add_action('elementor_pro/forms/new_record', function ($record, $handler): void {
            try {
                if (!is_object($record) || !method_exists($record, 'get')) {
                    error_log('[EasyLink Automations] ElementorPro: record is not a valid Form_Record object');
                    return;
                }
                $data = $this->handle($record, $handler);
                if (empty($data)) {
                    error_log('[EasyLink Automations] ElementorPro: handle() returned empty data');
                    return;
                }
                error_log('[EasyLink Automations] ElementorPro: firing trigger with form_id=' . ($data['form_id'] ?? 'N/A'));
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] ElementorPro trigger error: ' . $e->getMessage());
            }
        }, 10, 2);
    }

    public function handle(mixed ...$args): array
    {
        [$record] = $args;

        if (!is_object($record) || !method_exists($record, 'get')) {
            return [];
        }

        $formSettings = $record->get('form_settings');
        $fields       = [];

        foreach ($record->get('fields') as $field) {
            $key          = str_replace(' ', '_', strtolower($field['title'] ?? $field['id'] ?? ''));
            $fields[$key] = $field['value'] ?? '';
        }

        // Composite form_id matching getAvailableForms() format: "postId_widgetId".
        // Matches SureTriggers: direct access — Elementor Pro always injects form_post_id.
        return array_merge([
            'form_id'   => $formSettings['form_post_id'] . '_' . $formSettings['id'],
            'form_name' => $formSettings['form_name'] ?? '',
        ], $fields);
    }
}
