<?php

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}
// Check if the class already exists to avoid redeclaration.
if (!class_exists('INTEGRAZO_WZ_EverestForms_Helper')) {
    class INTEGRAZO_WZ_EverestForms_Helper
    {
        /**
         * Get all Everest Forms with ID and title.
         *
         * @return array|string
         */
        public static function get_all_forms()
        {
            if (!function_exists('evf')) {
                return 'Everest Forms plugin is not installed or activated. Please install and activate Everest Forms to continue.';
            }

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

            $forms = get_posts($args);

            if (empty($forms)) {
                return 'No Everest 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 Everest 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_status === 'trash') {
                return 'The mapped Everest Form was not found. It may have been deleted or is unavailable.';
            }
            $form = evf()->form->get($form_id);

            $json = json_decode($form->post_content);
            $form_fields = $json->form_fields ?? [];

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

            $fields = [];

            foreach ($form_fields as $field) {
                if (
                    !in_array($field->type, ["signature", "divider", "title", "private-note", "html", "wysiwyg", "progress", "color", "reset"])
                ) {

                    $field_data = [
                        'name'       => strtolower($field->id),
                        'type'       =>  $field->type,
                        'label'       => $field->type === 'address' ? 'Full ' . $field->label : $field->label,
                        'identifier' => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field->id, $field->label),
                    ];

                    $fields[] = $field_data;
                    if ($field->type === 'address') {
                        // Extract subfields of the address field with "Address - " prefix
                        $address_subfields = [
                            'address1' => 'Address - ' . $field->address1_label,
                            'address2' => 'Address - ' . $field->address2_label,
                            'city'     => 'Address - ' . $field->city_label,
                            'state'    => 'Address - ' . $field->state_label,
                            'postal'   => 'Address - ' . $field->postal_label,
                            'country'  => 'Address - ' . $field->country_label,
                        ];

                        foreach ($address_subfields as $key => $label) {
                            $fields[] = [
                                'name'       => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field->id, $key),
                                'type'       => 'text',
                                'label'      => $label,
                                'identifier' => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field->id, $key),
                            ];
                        }

                        continue; // Skip regular processing for this composite field
                    }
                }
            }


            return $fields;
        }
        public static function capture_submission($form, $entry)
        {
            try {

                $form_id = $entry['id'];
                $form_fields = $form;
                $entriesfields = $entry['form_fields'];
                $form_data = [];

                foreach ($form as $key => $fieldObj) {

                    $type  = $fieldObj['type'];
                    // $id    = $fieldObj['id'];
                    $label = $fieldObj['name'] ?? '';

                    if ($type === 'address' && isset($entry['form_fields'][$key]) && is_array($entry['form_fields'][$key])) {
                        $collected_parts = [];
                        foreach ($entry['form_fields'][$key] as $sub_key => $sub_value) {
                            if (!empty($sub_value)) {
                                $identifier = INTEGRAZO_WZ_Identifier_Util::build_field_identifier($key, $sub_key);
                                $form_data[$identifier] = $sub_value;
                                $collected_parts[] = $sub_value;
                            }
                        }
                        $form_data[strtolower($key)] = implode(' ', array_filter($collected_parts));
                    } elseif (($type === 'file-upload' || $type === 'image-upload') && isset($fieldObj['value_raw'][0]['value'])) {
                        // Handle multiple file uploads
                        $file_urls = [];
                        foreach ($fieldObj['value_raw'] as $file) {
                            if (!empty($file['value'])) {
                                $file_urls[] = $file['value'];
                            }
                        }
                        $form_data[strtolower($key)] = $file_urls;
                    } elseif ($type === 'privacy-policy') {
                        $form_data[strtolower($key)] = isset($entry['form_fields'][$key]) ? true : false;
                    } elseif (isset($entry['form_fields'][$key])) {
                        // Normal fields
                        $form_data[strtolower($key)] = $entry['form_fields'][$key];
                    }
                }

                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $form_data, "everest_form");
            } catch (Throwable $e) {
                return;
            }
        }
    }
}
// ✅ Safe hook, only if class exists
if (class_exists('INTEGRAZO_WZ_EverestForms_Helper')) {
    add_action('everest_forms_process_complete', ['INTEGRAZO_WZ_EverestForms_Helper', 'capture_submission'], 10, 2);
}
