<?php

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}
if (!class_exists('INTEGRAZO_WZ_HappyForms_Helper')) {
    class INTEGRAZO_WZ_HappyForms_Helper
    {
        /**
         * Get all HappyForms forms with ID and title.
         *
         * @return array|string
         */
        public static function get_all_forms()
        {
            $validation = self::validate_happyforms_plugin();
            if (is_string($validation)) {
                return $validation;
            }

            $args = [
                'post_type'      => 'happyform',
                'posts_per_page' => -1,
                'post_status'    => ['publish'],
            ];

            $forms = get_posts($args);

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

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

            return $data;
        }


        /**
         * Get all supported fields for a specific HappyForms form.
         *
         * @param int $form_id
         * @return array|string
         */
        public static function get_form_fields($form_id)
        {
            $post = get_post($form_id);

            if (!$post || $post->post_type !== 'happyform' || $post->post_status === 'trash') {
                return 'The mapped HappyForms was not found or is inactive/trashed. Please select another form to continue.';
            }
            $form = happyforms_get_form_controller()->get($form_id);

            $fields = $form['parts'];

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

            $result = [];
            foreach ($fields as $field) {
                $field_type = $field['type'];
                $excluded_types = ['page_break', 'layout_title', 'toggletip', 'audio', 'video', 'image', 'placeholder'];

                if (in_array($field_type, $excluded_types)) {
                    // continue or skip logic here
                    continue;
                }

                $result[] = [
                    'name'       => $field['id'],
                    'type'       => $field_type,
                    'label'      => $field['label'],
                    'identifier' => $field['id'],
                ];
            }

            return $result;
        }
        private static function validate_happyforms_plugin()
        {
            if (! function_exists('HappyForms')) {
                return 'HappyForms plugin is not installed or activated. Please install and activate the HappyForms plugin to continue.';
            }
            return true;
        }
        public static function capture_submission($submission_obj, $form_obj, $args)
        {
            try {
                $form_id = isset($form_obj['ID']) ? $form_obj['ID'] : null;
                $form_data = [];

                foreach ($submission_obj as $key => $val) {
                    if (str_contains($key, 'attachment')) {
                        $form_data[$key] = [];

                        $img = maybe_unserialize($val);
                        $hash_ids = array_filter(array_values((array) $img));

                        if (!empty($hash_ids)) {
                            $attachments = happyforms_get_attachment_controller()->get([
                                'hash_id' => $hash_ids,
                            ]);

                            $attachment_ids = wp_list_pluck($attachments, 'ID');
                            $links = array_map('wp_get_attachment_url', $attachment_ids);

                            $form_data[$key] = $links;
                        }
                    } else {
                        $form_data[$key] = $val;
                    }
                }
                // Continue processing
                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $form_data, "happy_form");
            } catch (Throwable $e) {
            }
        }
    }
}
// ✅ Safe hook, only if class exists
if (class_exists('INTEGRAZO_WZ_HappyForms_Helper')) {
    add_action('happyforms_submission_success', ['INTEGRAZO_WZ_HappyForms_Helper', 'capture_submission'], 10, 3);
}
