<?php

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

            $forms = Forminator_API::get_forms();

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

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

            return $data;
        }

        /**
         * Get all supported fields for a specific Forminator form.
         *
         * @param int $form_id
         * @return array|string
         */
        public static function get_form_fields($form_id)
        {
            if (!class_exists('Forminator')) {
                return 'Forminator plugin is not installed or activated. Please install and activate Forminator to continue.';
            }

            $form_object = Forminator_API::get_form($form_id, ['content_only' => true]);


            // Check if 'fields' key exists and is not null
            if (!isset($form_object->fields)) {
                return 'The mapped Forminator form was not found. It may have been deleted or is unavailable.';
            }

            $form_fields_raw = $form_object->fields;

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

            $processed_fields = [];

            foreach ($form_fields_raw as $form_field_model) {
                $raw_field_data = $form_field_model->raw;
                $field_type = $raw_field_data['type'];
                $field_id = $raw_field_data['element_id'];
                $field_label = $raw_field_data['field_label'];

                if (in_array($field_type, ['html', 'calculation', 'captcha', 'postdata', 'page-break', 'section', 'stripe-ocs', 'slider', 'group'], true)) {
                    continue; // Skip non-input fields
                }
                if (isset($field_type) && in_array($field_type, ['name', 'address'], true)) {
                    $field_label = 'Full ' . $field_label;
                }
                $processed_fields[] = [
                    'name'       => $field_id,
                    'type'       => $field_type,
                    'label'      => $field_label,
                    'identifier' => $field_id,
                ];
                if (isset($field_type) && in_array($field_type, ['name', 'address'], true)) {
                    // Find all keys ending with '_label'
                    $composite_labels = array_filter($raw_field_data, function ($key) {
                        return str_ends_with($key, '_label');
                    }, ARRAY_FILTER_USE_KEY);

                    if (count($composite_labels) > 1) {
                        foreach ($composite_labels as $composite_key => $composite_label) {
                            $original_sub_key = str_replace('_label', '', $composite_key);
                            $normalized_sub_key = $original_sub_key;

                            // Normalize for label/identifier purposes
                            if (strpos($original_sub_key, 'fname') !== false) {
                                $normalized_sub_key = 'first-name';
                            } elseif (strpos($original_sub_key, 'lname') !== false) {
                                $normalized_sub_key = 'last-name';
                            } elseif (strpos($original_sub_key, 'mname') !== false) {
                                $normalized_sub_key = 'middle-name';
                            } elseif (strpos($original_sub_key, 'prefix') !== false) {
                                $normalized_sub_key = 'prefix';
                            } elseif (strpos($original_sub_key, 'address_city') !== false) {
                                $normalized_sub_key = 'city';
                            } elseif (strpos($original_sub_key, 'address_state') !== false) {
                                $normalized_sub_key = 'state';
                            } elseif (strpos($original_sub_key, 'address_zip') !== false) {
                                $normalized_sub_key = 'zip';
                            } elseif (strpos($original_sub_key, 'address_country') !== false) {
                                $normalized_sub_key = 'country';
                            } elseif (strpos($original_sub_key, 'address_line') !== false) {
                                $normalized_sub_key = 'address-line';
                            }

                            // Use original_sub_key to check if data exists
                            if (!empty($raw_field_data[$original_sub_key])) {
                                $processed_fields[] = [
                                    'name'       => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field_id, $normalized_sub_key),
                                    'type'       => $field_type,
                                    'label'      => ucfirst($field_type) . ' - ' . $composite_label,
                                    'identifier' => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field_id, $normalized_sub_key),
                                ];
                            }
                        }
                    }
                }
            }


            return $processed_fields;
        }
        public static function capture_submission($email_details, $form_object, $submitted_data, $entry_object)
        {
            try {
                $form_data = [];
                $form_id = $entry_object->form_id;
                $form_values = $entry_object->meta_data;

                foreach ($form_object->fields as $field) {

                    $raw_field_data = $field->raw;
                    $field_type = $raw_field_data['type'];
                    $field_id = $raw_field_data['element_id'];
                    $field_label = $raw_field_data['field_label'];

                    if (isset($field_type) && in_array($field_type, ['name', 'address'], true)) {
                        $sub_fields = $form_values[$field_id]['value'] ?? [];

                        if (is_array($sub_fields)) {
                            foreach ($sub_fields as $sub_key => $sub_value) {
                                $identifier = INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field_id, $sub_key);
                                $form_data[$identifier] = $sub_value;
                            }

                            $form_data[$field_id] = implode(' ', array_filter($sub_fields));
                        } else {
                            $form_data[$field_id] = $form_values[$field_id]['value'] ?? '';
                        }
                    } elseif (isset($field_type) && $field_type === 'upload') {
                        $file_data = $form_values[$field_id]['value']['file'] ?? null;

                        if ($file_data && isset($file_data['file_path'])) {
                            if (is_array($file_data['file_path'])) {
                                // Multi-file upload
                                $form_data[$field_id] = array_filter($file_data['file_path']);
                            } else {
                                // Single-file upload
                                if (!empty($file_data['file_path'])) {
                                    $form_data[$field_id] = [$file_data['file_path']];
                                }
                            }
                        }
                    } elseif (isset($field_type) && $field_type === 'rating') {
                        if (strpos($form_values[$field_id]['value'], '/') !== false) {
                            $parts = explode('/', $form_values[$field_id]['value']);
                            if (!empty($parts[0])) {
                                $form_data[$field_id] = $parts[0];
                            }
                        }
                        // Your upload field logic here
                    } else {
                        $form_data[$field_id] = $form_values[$field_id]['value'] ?? '';
                    }
                }


                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $form_data, "forminator_form");
            } catch (Throwable $e) {
            }
        }
    }
}
// ✅ Safe hook, only if class exists
if (class_exists('INTEGRAZO_WZ_Forminator_Helper')) {
    add_action('forminator_custom_form_mail_before_send_mail', ['INTEGRAZO_WZ_Forminator_Helper', 'capture_submission'], 10, 4);
}
