<?php

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

use FluentForm\App\Models\Form;
// Check if the class already exists to avoid redeclaration.
if (!class_exists('INTEGRAZO_WZ_FluentForms_Helper')) {
    class INTEGRAZO_WZ_FluentForms_Helper
    {
        /**
         * Get all Fluent Forms with ID and title.
         *
         * @return array|string
         */
        public static function get_all_forms()
        {
            if (! function_exists('wpFluent')) {
                return 'Fluent Forms plugin is not installed or activated. Please install and activate Fluent Forms to continue.';
            }

            $forms = Form::where('status', 'published')->get();

            if ($forms->isEmpty()) {
                return 'No Fluent 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 Fluent Form.
         *
         * @param int $form_id
         * @return array|string
         */
        public static function get_form_fields($form_id)
        {
            $form = Form::find($form_id);
            if (!$form) {
                return 'The mapped Fluent Form was not found. It may have been deleted or is unavailable.';
            }

            $form_structure = json_decode($form->form_fields, true);
            $form_fields = $form_structure['fields'] ?? [];

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

            $fields = [];

            foreach ($form_fields as $field) {
                $element_exclude = ['tabular_grid', 'custom_submit_button', 'color_picker', 'repeater_container', 'cpt_selection', 'custom_html', 'shortcode', 'action_hook', 'form_step', 'dynamic_field', 'save_progress_button', 'repeater_field', 'chained_select', 'container'];
                $element = $field['element'];

                if (in_array($element, $element_exclude)) {
                    continue;
                }

                $name = $field['attributes']['name'];
                $type = $field['attributes']['type'] ?? ($field['attributes']['data-type'] ?? '');
                $label = '';

                if ($type === 'name-element') {
                    $label = 'Full Name';
                } elseif ($type === 'address-element') {
                    $label = 'Full Address';
                } else {
                    $label = $field['settings']['label'] ??  $field['settings']['admin_field_label'];
                }

                $fields[] = [
                    'name'       => $name,
                    'type'       => $type,
                    'label'      => $label,
                    'identifier' => $name,
                ];

                // Handle composite name/address fields
                if (
                    in_array($type, ['name-element', 'address-element']) &&
                    isset($field['fields']) &&
                    is_array($field['fields'])
                ) {
                    foreach ($field['fields'] as $key => $sub_field) {
                        if (!empty($sub_field['settings']['visible']) && $sub_field['settings']['visible'] == 1) {
                            $prefix_sub = ($type === 'name-element') ? 'Name' : 'Address';
                            $sub_label = $prefix_sub . ' - ' . ($sub_field['settings']['label']);

                            $sub_identifier = INTEGRAZO_WZ_Identifier_Util::build_field_identifier($name, $key);

                            $fields[] = [
                                'name'       => $sub_identifier,
                                'type'       => $type,
                                'label'      => $sub_label,
                                'identifier' => $sub_identifier,
                            ];
                        }
                    }
                }
            }

            return $fields;
        }



        public static function capture_submission($entryId, $form, $field_details)
        {
            try {
                $form_data = [];
                $form_id = $field_details->id;
                // Decode form structure
                $form_structure = json_decode($field_details->form_fields, true);
                $form_fields = $form_structure['fields'];

                // Loop through the form fields
                foreach ($form_fields as $field) {

                    $original_name = $field['attributes']['name'];
                    $field_type = $field['attributes']['type'] ?? $field['attributes']['data-type'] ?? 'text';

                    // Handle complex fields like 'name-element', 'address-element'
                    if ($field_type === 'name-element' || $field_type === 'address-element') {
                        $collected_parts = [];

                        foreach ($form[$original_name] as $sub_key => $value) {
                            $sub_identifier = INTEGRAZO_WZ_Identifier_Util::build_field_identifier($original_name, $sub_key);
                            $form_data[$sub_identifier] = $value;
                            $collected_parts[] = $value;
                        }

                        $form_data[$original_name] = implode(' ', $collected_parts);
                    } else {
                        $form_data[$original_name] = $form[$original_name];
                    }
                }
                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $form_data, "fluent_form");
            } catch (Throwable $e) {
            }
        }
    }
}


// ✅ Safe hook, only if class exists
if (class_exists('INTEGRAZO_WZ_FluentForms_Helper')) {
    add_action('fluentform_submission_inserted', ['INTEGRAZO_WZ_FluentForms_Helper', 'capture_submission'], 10, 3);
}
