<?php

if (!defined('ABSPATH')) {
    exit;
}
if (!class_exists('INTEGRAZO_WZ_Elementor_Helper')) {
    class INTEGRAZO_WZ_Elementor_Helper
    {
        /**
         * Validate if the Elementor plugin is active.
         *
         * @return true|string
         */
        private static function validate_plugin()
        {
            if (!did_action('elementor/loaded')) {
                return 'Elementor plugin is not active. Please install and activate the Elementor plugin to continue.';
            }

            if (!defined('ELEMENTOR_PRO_VERSION')) {
                return 'Elementor Pro is required for form integration. Please install and activate Elementor Pro to continue.';
            }

            return true;
        }

        /**
         * Get all posts or pages that contain Elementor forms.
         *
         * @return array|string Array of forms or a user-friendly error message.
         */
        public static function get_all_forms()
        {
            $validation = self::validate_plugin();
            if (is_string($validation)) {
                return $validation;
            }

            $args = [
                'post_type'      => ['page', 'post'],
                'posts_per_page' => -1,
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
                'meta_query'     => [
                    [
                        'key'     => '_elementor_data',
                        'compare' => 'EXISTS',
                    ],
                ],
            ];

            $posts = get_posts($args);
            $forms = [];

            foreach ($posts as $post) {
                $content = get_post_meta($post->ID, '_elementor_data', true);
                $data = json_decode($content, true);

                if (!$data) {
                    continue;
                }

                $widgets = new RecursiveIteratorIterator(
                    new RecursiveArrayIterator($data),
                    RecursiveIteratorIterator::SELF_FIRST
                );

                foreach ($widgets as $key => $value) {
                    if (is_array($value) && isset($value['widgetType']) && $value['widgetType'] === 'form') {
                        $form_name = $value['settings']['form_name'] ?? 'Untitled Form';
                        $form_id   = $value['id'] ?? uniqid('form_');

                        $forms[] = [
                            'id'    => $post->ID . '_' . $form_id, // Combined ID
                            'title' => $form_name . ' (Page: ' . $post->post_title . ')',
                            'page_id' => $post->ID,
                            'form_widget_id' => $form_id,
                        ];
                    }
                }
            }

            if (empty($forms)) {
                return 'No forms found. Please make sure at least one Elementor form widget is added to a page or post.';
            }

            return $forms;
        }

        /**
         * Get all fields from a specific Elementor form using a combined ID.
         *
         * @param string $combined_id Format: postId_formWidgetId
         * @return array|string Array of fields or a user-friendly error message.
         */
        public static function get_form_fields($combined_id)
        {

            // Split the combined form ID
            $parts = explode('_', $combined_id);

            $post_id = (int) $parts[0];
            $form_widget_id = $parts[1];

            $data = get_post_meta($post_id, '_elementor_data', true);
            if ($data == []  || empty($data)) {
                return 'The mapped Elementor form was not found. It may have been deleted or is unavailable.';
            }

            $data = json_decode($data, true);
            if (!self::find_id_in_data($data, $form_widget_id)) {
                return 'The mapped Elementor form was not found. It may have been deleted or is unavailable.';
            }

            $fields = [];

            $widgets = new RecursiveIteratorIterator(
                new RecursiveArrayIterator($data),
                RecursiveIteratorIterator::SELF_FIRST
            );

            foreach ($widgets as $key => $value) {
                if (
                    is_array($value)
                    && isset($value['widgetType'], $value['id'])
                    && $value['widgetType'] === 'form'
                    && $value['id'] === $form_widget_id
                ) {
                    $form_fields = $value['settings']['form_fields'] ?? [];

                    foreach ($form_fields as $field) {
                        $field_type = $field['field_type'] ?? 'text'; // default to 'text' if not set
                        if (!in_array($field_type, ['step', 'html', 'recaptcha', 'recaptcha_v3', 'honeypot'])) {
                            $fields[] = [
                                'name'       => $field['_id'],
                                'type'       => $field_type,
                                'label'      => $field['field_label'],
                                'identifier' => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field['_id'], $field['field_label']),
                            ];
                        }
                    }


                    break;
                }
            }

            if (empty($fields)) {
                return 'No fields found in the selected form. Please edit the form and add at least one input field.';
            }

            return $fields;
        }
        private static function find_id_in_data($data, $form_widget_id)
        {
            foreach ($data as $item) {
                if (isset($item['id']) && $item['id'] === $form_widget_id) {
                    return true;
                }
                if (!empty($item['elements']) && is_array($item['elements'])) {
                    if (self::find_id_in_data($item['elements'], $form_widget_id)) {
                        return true;
                    }
                }
            }
            return false;
        }
        /**
         * Capture Elementor form submission.
         *
         * @param \ElementorPro\Modules\Forms\Classes\Record $record
         * @param \ElementorPro\Modules\Forms\Classes\Ajax_Handler $handler
         */
        public static function capture_submission($record, $handler)
        {
            try {
                $form_data = [];

                // Get raw fields from submitted data
                $raw_fields = $record->get('fields');

                // Get field definitions from form settings
                $form_fields = $record->get_form_settings('form_fields');
                // Build a map: custom_id => _id
                $custom_id_map = [];
                foreach ($form_fields as $field_def) {
                    if (isset($field_def['custom_id']) && isset($field_def['_id'])) {
                        $custom_id_map[$field_def['custom_id']] = $field_def['_id'];
                    }
                }
                foreach ($raw_fields as $id => $field) {
                    $value = $field['value'];

                    // Get corresponding _id from form settings
                    $field_key = isset($custom_id_map[$id]) ? $custom_id_map[$id] : $id;

                    if ($field['type'] === 'upload') {
                        $paths = array_map('trim', explode(',', $value));
                        $form_data[$field_key] = $paths;
                    } else {
                        $form_data[$field_key] = $value;
                    }
                }

                $form_widget_id = $record->get_form_settings('id');
                $form_id = $record->get_form_settings('form_post_id') . "_" . $form_widget_id;

                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $form_data, "elementor_form");
            } catch (Throwable $e) {
                return;
            }
        }
    }
}


// ✅ Safe hook, only if class exists
if (class_exists('INTEGRAZO_WZ_Elementor_Helper')) {
    add_action('elementor_pro/forms/new_record', ['INTEGRAZO_WZ_Elementor_Helper', 'capture_submission'], 10, 2);
}
