<?php

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}
if (!class_exists('INTEGRAZO_WZ_weForms_Helper')) {
    class INTEGRAZO_WZ_weForms_Helper
    {
        /**
         * Get all weForms forms with ID and title.
         *
         * @return array|string
         */
        public static function get_all_forms()
        {

            if (!function_exists('weforms')) {
                return 'weForms plugin is not installed or activated. Please install and activate weForms to continue.';
            }

            $result = weforms()->form->all();

            $data = [];
            foreach ($result['forms'] as $form) {
                if (isset($form->data->ID, $form->data->post_title)) {
                    $data[] = [
                        'id'    => (int) $form->data->ID,
                        'title' => $form->data->post_title,
                    ];
                }
            }
            if (empty($data)) {
                return 'No weForms forms found. Please create at least one form to continue.';
            }

            return $data;
        }


        /**
         * Get all supported fields for a specific weForms form.
         *
         * @param int $form_id
         * @return array|string
         */
        public static function get_form_fields($form_id)
        {
            $form = weforms()->form->get($form_id);

            if (!$form) {
                return 'The mapped weForms form was not found. It may have been deleted or is unavailable. Please select another form to continue.';
            }

            $fields = $form->get_fields();

            if (empty($fields) || !is_array($fields)) {
                return 'This weForms form does not contain any fields. Please edit the form and add at least one input field.';
            }

            $result = [];

            foreach ($fields as $field) {

                $base_type = $field['template'];

                if (in_array($base_type, ['multiple_choice_grid', 'checkbox_grid', 'linear_scale', 'action_hook', 'shortcode', 'signature_field', 'custom_html', 'section_break', 'column_field', 'step_start'])) {
                    continue;
                }

                $base_id = $field['id'];
                $base_name = $field['name'];
                $base_label = !empty($field['label']) ? $field['label'] : $base_name;

                // Main field entry
                $result[] = [
                    'name'       => $base_name,
                    'type'       => $base_type,
                    'label'      => (in_array($base_type, ['address_field', 'name_field']) ? 'Full ' : '') . $base_label,
                    'identifier' => $base_name,
                ];

                // Handle sub-fields for name_field and address_field
                if (in_array($base_type, ['address_field', 'name_field'])) {
                    foreach ($field as $key => $sub_field) {
                        if (is_array($sub_field) && isset($sub_field['sub'])) {
                            $sub_label = $sub_field['sub'];
                            $result[] = [
                                'name'       => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($base_name, $key),
                                'type'       => $base_type,
                                'label'      => 'Name - ' . $sub_label,
                                'identifier' => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($base_name, $key),
                            ];
                        } elseif ($key === 'address' && is_array($sub_field)) {
                            foreach ($sub_field as $address_key => $address_value) {
                                $address_label = $address_value['label'] ?? $address_key;
                                $result[] = [
                                    'name'       => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($base_name, $address_key),
                                    'type'       => $base_type,
                                    'label'      => 'Address - ' . $address_label,
                                    'identifier' => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($base_name, $address_key),
                                ];
                            }
                        }
                    }
                }
            }

            return $result;
        }
        public static function capture_submission($entry_id, $form_id, $page_id, $form_settings)
        {
            try {
                $formatted_data = [];

                $entry_data = weforms_get_entry_data($entry_id);
                $form = new WeForms_Form($form_id);
                $form_entry = new WeForms_Form_Entry($entry_id, $form);
                $form_fields = $form_entry->get_fields();

                foreach ($form_fields as $field) {
                    $field_type = $field['template'];
                    $field_name = $field['name'];

                    if ($field_type === 'name_field') {
                        $value = $entry_data['data'][$field_name];
                        $name_parts = explode('|', $value);

                        $first_name  = trim($name_parts[0] ?? '');
                        $middle_name = trim($name_parts[1] ?? '');
                        $last_name   = trim($name_parts[2] ?? '');

                        // Only join non-empty parts with a single space
                        $full_name = trim(implode(' ', array_filter([$first_name, $middle_name, $last_name])));

                        $formatted_data[$field_name]               = $full_name;
                        $formatted_data["first_name_$field_name"]  = $first_name;
                        $formatted_data["middle_name_$field_name"] = $middle_name;
                        $formatted_data["last_name_$field_name"]   = $last_name;
                    } elseif ($field_type === 'address_field') {
                        $address_data = $entry_data['data'][$field_name];
                        $collected_parts = [];

                        if (is_array($address_data)) {
                            foreach ($address_data as $address_key => $address_value) {
                                $formatted_data[$address_key . '_' . $field_name] = $address_value;
                                $collected_parts[] = $address_value;
                            }
                        }

                        $formatted_data[$field_name] = implode(' ', array_filter($collected_parts));
                    } elseif ($field_type === 'file_upload' || $field_type === 'image_upload') {

                        $raw_value = $entry_data['data'][$field_name] ?? '';
                        // Match all href values from anchor tags
                        preg_match_all('/href=["\']([^"\']+)["\']/', $raw_value, $matches);
                        $file_urls = $matches[1] ?? [];

                        // Always return as an array, even if only one file is found
                        $formatted_data[$field_name] = $file_urls;
                    } else {
                        $formatted_data[$field_name] = $entry_data['data'][$field_name] ?? '';
                    }
                }

                // Continue processing
                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $formatted_data, "we_form");
            } catch (Throwable $e) {
            }
        }
    }
}


// ✅ Safe hook, only if class exists
if (class_exists('INTEGRAZO_WZ_weForms_Helper')) {
    add_action('weforms_entry_submission', ['INTEGRAZO_WZ_weForms_Helper', 'capture_submission'], 10, 4);
}
