<?php

namespace EasyLinkAutomations\Triggers\BricksBuilder;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user submits a Bricks Builder form.
 */
final class FormSubmittedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'bricks-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 Bricks Builder form.', 'easylink-automations');
    }

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

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

    public static function isAvailable(): bool
    {
        return class_exists('Bricks\Database');
    }

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

        $bricksSettings = (array) get_option(
            defined('BRICKS_DB_GLOBAL_SETTINGS') ? BRICKS_DB_GLOBAL_SETTINGS : 'bricks_global_settings'
        );
        $postTypes   = $bricksSettings['postTypes'] ?? [];
        $postTypes[] = 'bricks_template';

        $templates = get_posts([
            'post_type'      => array_unique($postTypes),
            'post_status'    => 'publish',
            'posts_per_page' => -1,
        ]);

        $metaKey = defined('BRICKS_DB_PAGE_CONTENT') ? BRICKS_DB_PAGE_CONTENT : '_bricks_page_content_2';

        foreach ($templates as $template) {
            $elements = get_post_meta($template->ID, $metaKey, true);
            if (!is_array($elements)) {
                continue;
            }
            foreach ($elements as $el) {
                if (($el['name'] ?? '') === 'form' && !empty($el['id'])) {
                    $label     = $template->post_title . ' (ID: ' . $el['id'] . ')';
                    $options[] = ['value' => $el['id'], 'label' => $label];
                }
            }
        }

        return $options;
    }

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

        // Bricks Builder fires bricks/form/response; we bridge it to our own action.
        add_filter('bricks/form/response', function ($response, $obj) {
            try {
                do_action('bricksbuilder_after_form_submit', $response, $obj);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] BricksBuilder trigger error: ' . $e->getMessage());
            }
            return $response;
        }, 10, 2);

        add_action('bricksbuilder_after_form_submit', function ($response, $obj): void {
            try {
                if (!check_ajax_referer('bricks-nonce-form', 'nonce', false)) {
                    return;
                }
                $data = $this->handle($response, $obj);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] BricksBuilder trigger error: ' . $e->getMessage());
            }
        }, 10, 2);
    }

    public function handle(mixed ...$args): array
    {
        /** @var mixed $obj */
        [$response, $obj] = $args;

        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        $postData = sanitize_post($_POST);

        $formId       = isset($postData['formId']) ? sanitize_text_field($postData['formId']) : '';
        $fields       = [];
        $formFields   = [];
        $templateName = '';

        foreach ($postData as $key => $value) {
            if (str_contains((string) $key, 'form-field-')) {
                $fieldId          = str_replace('form-field-', '', (string) $key);
                $fields[$fieldId] = $value;
            } else {
                $fields[$key] = $value;
            }
        }

        if (!empty($formId)) {
            $bricksSettings = (array) get_option(defined('BRICKS_DB_GLOBAL_SETTINGS') ? BRICKS_DB_GLOBAL_SETTINGS : 'bricks_global_settings');
            $bricksPosts    = $bricksSettings['postTypes'] ?? [];
            $bricksPosts[]  = 'bricks_template';

            $templates = get_posts([
                'post_type'      => $bricksPosts,
                'post_status'    => 'publish',
                'posts_per_page' => -1,
            ]);

            foreach ($templates as $template) {
                $bbContents = get_post_meta($template->ID, defined('BRICKS_DB_PAGE_CONTENT') ? BRICKS_DB_PAGE_CONTENT : '_bricks_page_content_2', true);
                if (!empty($bbContents) && is_array($bbContents)) {
                    foreach ($bbContents as $content) {
                        if (isset($content['id']) && $formId === $content['id']) {
                            $templateName = html_entity_decode(get_the_title($template->ID), ENT_QUOTES, 'UTF-8');
                            $contentFields = $content['settings']['fields'] ?? [];
                            foreach ($contentFields as $field) {
                                $fdLabel = !empty($field['label']) ? $field['label'] : ($field['id'] ?? '');
                                $labelKey = strtolower(str_replace(' ', '_', trim((string) $fdLabel)));
                                if (isset($fields[$field['id'] ?? ''])) {
                                    $formFields[$labelKey] = $fields[$field['id']];
                                } elseif (isset($fields[str_replace(' ', '_', (string) ($field['name'] ?? ''))])) {
                                    $formFields[$labelKey] = $fields[str_replace(' ', '_', $field['name'])];
                                }
                            }
                        }
                    }
                }
            }
        }

        $context = [
            'form_id'       => $formId,
            'template_name' => $templateName,
        ];

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

        return $context;
    }
}
