<?php

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}
if (!class_exists('INTEGRAZO_WZ_WSForm_Helper')) {
    class INTEGRAZO_WZ_WSForm_Helper
    {
        /**
         * Get all WS Form forms with ID and title.
         *
         * @return array|string
         */
        public static function get_all_forms()
        {
            if (! class_exists('WS_Form_Form')) {
                return 'WS Form plugin is not installed or activated. Please install and activate WS Form to continue.';
            }

            // Get all WS Forms
            $forms = wsf_form_get_all(true, 'label');

            if (empty($forms)) {
                return 'No WS Form forms found. Please create at least one form to continue.';
            }

            $data = [];
            foreach ($forms as $form) {
                $data[] = [
                    'id'    => (int) $form['id'],
                    'title' => $form['label'],
                ];
            }

            return $data;
        }

        /**
         * Get all supported fields for a specific WS Form form.
         *
         * @param int $form_id
         * @return array|string
         */
        public static function get_form_fields($form_id)
        {
            $form_obj = new WS_Form_Form();
            $form_obj->id = $form_id;
            try {
                $form_detail = $form_obj->db_read(false, true);
            } catch (Exception $e) {
                return 'The mapped WS Form was not found. It may have been deleted or is unavailable. Please select another form to continue.';
            }


            $fields = [];
            $excluded_types = [
                'color',
                'legal',
                'search',
                'googlemap',
                'googleaddress',
                'googleroute',
                'trustedform',
                'html',
                'note',
                'summary',
                'message',
                'texteditor',
                'save',
                'clear',
                'button',
                'section_add',
                'section_delete',
                'section_up',
                'section_down',
                'section_icons',
                'recaptcha',
                'hcaptcha',
                'turnstile',
                'divider',
                'spacer',
                'submit',
                'reset',
                'tab_previous',
                'tab_next',
                'signature',
            ];



            if (!empty($form_detail->groups)) {
                foreach ($form_detail->groups as $group) {
                    if (!empty($group->sections)) {
                        foreach ($group->sections as $section) {
                            if (!empty($section->fields)) {
                                foreach ($section->fields as $field) {
                                    if (!is_object($field) || in_array($field->type, $excluded_types, true)) {
                                        continue;
                                    }
                                    $fields[] = [
                                        'name'       => $field->id,
                                        'type'       => $field->type,
                                        'label'      => $field->label,
                                        'identifier' => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field->id, $field->label),
                                    ];
                                }
                            }
                        }
                    }
                }
            }

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

            return $fields;
        }

        public static function capture_submission($submission)
        {
            try {
                $form_data     = [];
                $form_id       = $submission->form_id;
                $submit_id     = $submission->id;
                $form_object   = $submission->form_object;

                $excluded_field_types = [
                    'color',
                    'legal',
                    'search',
                    'googlemap',
                    'googleaddress',
                    'googleroute',
                    'trustedform',
                    'html',
                    'note',
                    'summary',
                    'message',
                    'texteditor',
                    'save',
                    'clear',
                    'button',
                    'section_add',
                    'section_delete',
                    'section_up',
                    'section_down',
                    'section_icons',
                    'recaptcha',
                    'hcaptcha',
                    'turnstile',
                    'divider',
                    'spacer',
                    'submit',
                    'reset',
                    'tab_previous',
                    'tab_next',
                    'signature'
                ];

                if (!empty($form_object->groups)) {
                    foreach ($form_object->groups as $group) {
                        if (!empty($group->sections)) {
                            foreach ($group->sections as $section) {
                                if (!empty($section->fields)) {
                                    foreach ($section->fields as $field) {
                                        if (!is_object($field) || in_array($field->type, $excluded_field_types, true)) {
                                            continue;
                                        }

                                        $field_key   = 'field_' . $field->id;
                                        $field_value = wsf_submit_get_value($submission, $field_key);
                                        // ✅ Handle file and signature fields
                                        if (in_array($field->type, ['file']) && is_array($field_value)) {
                                            $file_paths   = [];
                                            $has_multiple = false;

                                            foreach ($field_value as $file_info) {
                                                if (!empty($file_info['attachment_id'])) {
                                                    $file_paths[] = wp_get_attachment_url($file_info['attachment_id']);
                                                    if (isset($file_info['hash'])) {
                                                        $has_multiple = true;
                                                    }
                                                }
                                            }

                                            $form_data[$field->id] = $has_multiple ? $file_paths : ($file_paths[0] ?? '');
                                        } else {
                                            $form_data[$field->id] = $field_value;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // ✅ Pass to next logic
                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $form_data, 'ws_form');
            } catch (Throwable $e) {
            }
        }
    }
}


// ✅ Safe hook, only if class exists
if (class_exists('INTEGRAZO_WZ_WSForm_Helper')) {
    add_action('wsf_submit_post_complete', ['INTEGRAZO_WZ_WSForm_Helper', 'capture_submission'], 10, 1);
}
