<?php

namespace EasyLinkAutomations\Triggers\DiviBuilder;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user submits a Divi Builder contact form.
 */
final class FormSubmittedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'divi-builder/form_submitted';
    }

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

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

    public static function getCategory(): string
    {
        return 'Divi Builder';
    }

    public static function getIcon(): string
    {
        return 'divi-builder';
    }

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

    public static function getOutputFields(): array
    {
        return [
            'form_id'     => ['label' => 'Form ID', 'type' => 'string'],
            'divi_form'   => ['label' => 'Divi Form Unique ID', '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 ID, post_title, post_content FROM {$wpdb->posts}
             WHERE post_status = 'publish'
             AND post_content LIKE '%et_pb_contact_form%'",
            ARRAY_A
        );

        // Parse shortcodes to extract individual forms with _unique_id
        // (matching SureTriggers compound format: "{postId}-{uniqueId}")
        foreach ($results as $row) {
            if (preg_match_all('/\[et_pb_contact_form(.*?)]/s', $row['post_content'], $matches)) {
                foreach ($matches[1] as $attrs) {
                    $parsed   = shortcode_parse_atts($attrs);
                    $uniqueId = $parsed['_unique_id'] ?? '';
                    if ($uniqueId) {
                        $formId    = $row['ID'] . '-' . $uniqueId;
                        $title     = $parsed['title'] ?? 'Contact Form';
                        $options[] = ['value' => $formId, 'label' => $title . ' (' . $row['post_title'] . ')'];
                    }
                }
            }
        }

        return $options;
    }

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

        add_action('et_pb_contact_form_submit', function ($fieldsValues, $etContactError, $contactFormInfo): void {
            try {
                if (true === $etContactError) {
                    return;
                }
                if (!isset($contactFormInfo['contact_form_unique_id'])) {
                    return;
                }
                $data = $this->handle($fieldsValues, $etContactError, $contactFormInfo);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] DiviBuilder trigger error: ' . $e->getMessage());
            }
        }, 10, 3);
    }

    public function handle(mixed ...$args): array
    {
        [$fieldsValues, $etContactError, $contactFormInfo] = $args;

        if (true === $etContactError) {
            return [];
        }
        if (!isset($contactFormInfo['contact_form_unique_id'])) {
            return [];
        }

        $uniqueId  = $contactFormInfo['contact_form_unique_id'];
        $postId    = $contactFormInfo['post_id'];
        $formId    = "{$postId}-{$uniqueId}";
        $formFields = [];

        foreach ((array) $fieldsValues as $key => $value) {
            $formFields[$key] = is_array($value) ? stripslashes((string) ($value['value'] ?? '')) : stripslashes((string) $value);
        }

        $context = [
            'form_id'   => $formId,
            'divi_form' => $formId,
        ];

        foreach ($formFields as $key => $value) {
            if (!isset($context[$key])) {
                $context[$key] = $value;
            }
        }

        return $context;
    }
}
