<?php

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

            $forms = GFAPI::get_forms();

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

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

            return $data;
        }

        /**
         * Get all supported fields for a specific Gravity Form.
         *
         * @param int $form_id
         * @return array|string
         */
        public static function get_form_fields($form_id)
        {
            $validation = self::validate_form_plugin_and_id($form_id);
            if (is_string($validation)) {
                return $validation;
            }

            $form = GFAPI::get_form($form_id);
            if (!$form || empty($form['fields'])) {
                return 'This Gravity Form does not contain any fields. Please edit the form and add at least one input field.';
            }
            $exclude_type = ['html', 'section', 'page', 'html', 'captcha'];

            $fields = [];
            foreach ($form['fields'] as $field) {
                $label = $field->label;
                $type = $field->type;
                if (
                    in_array($type, $exclude_type, true)
                ) {
                    continue;
                }

                if (isset($field->inputs) && in_array($type, ['name', 'address'], true)) {
                    $label = 'Full ' . $field->label;
                }
                // Single input fields
                $fields[] = [
                    'name'       => $field->id,
                    'type'       => $field->type,
                    'label'      => $label,
                    'identifier' => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field->id, $field->label),
                ];
                // Check for multi-input fields (e.g., Name, Address)
                if (!empty($field->inputs) && is_array($field->inputs) && in_array($type, ['name', 'address'], true)) {
                    foreach ($field->inputs as $input) {
                        if (empty($input['isHidden'])) {
                            $fields[] = [
                                'name'       => $input['id'],
                                'type'       => 'text',
                                'label'      => $field->label . " - " . $input['label'],
                                'identifier' => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($input['id'], $input['label']),
                            ];
                        }
                    }
                }
            }


            return $fields;
        }


        /**
         * Validate that the Gravity Forms plugin is active.
         *
         * @return true|string
         */
        private static function validate_gravityforms_plugin()
        {
            if (!class_exists('GFAPI')) {
                return 'Gravity Forms plugin is not installed or activated. Please install and activate Gravity Forms to continue.';
            }
            return true;
        }

        /**
         * Validate plugin and form ID.
         *
         * @param int $form_id
         * @return true|string
         */
        private static function validate_form_plugin_and_id($form_id)
        {

            global $wpdb;
            $table = $wpdb->prefix . 'gf_form';

            $form = $wpdb->get_row(
                $wpdb->prepare("SELECT id, is_active, is_trash FROM $table WHERE id = %d", $form_id),
                ARRAY_A
            );

            if (!$form || $form['is_trash'] || !$form['is_active']) {
                return 'The mapped Gravity Form was not found or is inactive/trashed. Please select another form to continue.';
            }

            return true;
        }

        public static function capture_submission($entry, $form)
        {
            try {
                $form_id   = $form['id'];
                $form_data = [];

                foreach ($form['fields'] as $field) {
                    $field_id    = $field->id;
                    $field_type  = $field->type;
                    $field_value = isset($entry[$field_id]) ? $entry[$field_id] : null;

                    // Handle file uploads
                    if ($field_type === 'fileupload') {
                        if (!empty($field_value)) {
                            if (!empty($field->multipleFiles)) {
                                $clean_string = stripslashes($field_value);
                                $decoded = json_decode($clean_string, true);
                                $cleaned = (json_last_error() === JSON_ERROR_NONE && is_array($decoded))
                                    ? $decoded
                                    : array_map('trim', explode(',', $clean_string));
                            } else {
                                $decoded = json_decode($field_value, true);
                                $cleaned = $decoded ?: [$field_value];
                            }
                        } else {
                            $cleaned = [];
                        }
                        $form_data[$field_id] = $cleaned;
                    }

                    // Handle checkboxes
                    elseif ($field_type === 'checkbox' && is_array($field->inputs)) {
                        $checkbox_values = [];
                        foreach ($field->inputs as $input) {
                            $input_id = $input['id'];
                            if (!empty($entry[$input_id])) {
                                $checkbox_values[] = $entry[$input_id];
                            }
                        }
                        $form_data[$field_id] = $checkbox_values;
                    }


                    // Handle consent fields
                    elseif ($field_type === 'consent' && is_array($field->inputs)) {
                        $value_set = false;
                        foreach ($field->inputs as $input) {
                            $input_id = $input['id'];
                            if (isset($entry[$input_id])) {
                                $form_data[$field_id] = stripslashes($entry[$input_id]);
                                $value_set = true;
                                break;
                            }
                        }
                        if (!$value_set) {
                            $form_data[$field_id] = null;
                        }
                    }
                    // Handle checkboxes
                    elseif ($field_type === 'list') {
                        $form_data[$field_id] = maybe_unserialize($field_value);
                    }

                    // Handle name or address fields
                    elseif (in_array($field_type, ['name', 'address']) && is_array($field->inputs)) {
                        $collected_parts = [];
                        foreach ($field->inputs as $input) {
                            $input_id = $input['id'];
                            $part = isset($entry[$input_id]) ? stripslashes($entry[$input_id]) : null;
                            $form_data[$input_id] = $part;
                            $collected_parts[] = $part;
                        }
                        $form_data[$field_id] = implode(' ', array_filter($collected_parts));
                    }

                    // Handle all other fields
                    else {
                        if (is_string($field_value)) {
                            $trimmed = trim($field_value);
                            if (str_starts_with($trimmed, '[') && str_ends_with($trimmed, ']')) {
                                $decoded = json_decode(stripslashes($field_value), true);
                                if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                                    $field_value = $decoded;
                                }
                            }
                        }
                        $form_data[$field_id] = $field_value;
                    }
                }

                // Log the final cleaned data
                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $form_data, "gravity_form");
            } catch (Throwable $e) {
                return;
            }
        }
    }
}
// ✅ Safe hook, only if class exists
if (class_exists('INTEGRAZO_WZ_GravityForms_Helper')) {
    add_action('gform_after_submission', ['INTEGRAZO_WZ_GravityForms_Helper', 'capture_submission'], 10, 2);
}
