<?php

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

            $forms = FrmForm::getAll(['is_template' => false, 'status' => 'published']);

            if (empty($forms)) {
                return 'No Formidable 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 Formidable 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;
            }

            $fields = FrmField::get_all_for_form($form_id);

            $filtered_fields = [];

            foreach ($fields as $field) {
                $field_type = $field->type;

                // Skip button/display fields
                if (in_array($field_type, ['submit', 'html', 'divider', 'end_divider', 'break', 'captcha', 'credit_card', 'form', 'summary', 'data'], true)) {
                    continue;
                }

                $label = $field->name;
                $field_key = $field->id;
                if ($field_type === 'address' || $field_type === 'name') {
                    $label = 'Full ' . $field->name;
                }
                //
                $filtered_fields[] = [
                    'name'       => $field_key,
                    'type'       => $field_type,
                    'label'      => $label,
                    'identifier' => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field_key, $label),
                ];
                // Handle Address field (expand each subfield)
                if ($field_type === 'address' || $field_type === 'name') {
                    foreach ($field->default_value as $part_key => $_) {
                        $sub_label = ucfirst($part_key); // e.g., Line1, Cisty
                        // $sub_id = $field_key . '_' . $part_key;
                        $filtered_fields[] = [
                            'name'       => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field_key, $sub_label),
                            'type'       => $field_type,
                            'label'      => "$field->name - $sub_label",
                            'identifier' => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field_key, $sub_label),

                        ];
                    }
                }
            }

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

        /**
         * Validate that the Formidable Forms plugin is active.
         *
         * @return true|string
         */
        private static function validate_formidableforms_plugin()
        {
            if (!function_exists('load_formidable_forms')) {
                return __('Formidable Forms plugin is not installed or activated. Please install and activate Formidable Forms to continue.', 'integrazo-integration-for-zoho-apps');
            }

            return true;
        }

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

            $form = FrmForm::getOne($form_id);
            if (!$form || $form->status === 'trash') {
                return 'The mapped Formidable Form was not found. It may have been deleted or is unavailable. Please select another form to continue.';
            }
            return true;
        }

        public static function capture_submission($entry_id, $form_id)
        {
            try {
                $entry = FrmEntry::getOne($entry_id, true); // Fetch full entry object
                if (!$entry) {
                    return;
                }

                $form_fields = FrmField::get_all_for_form($form_id); // Array of field objects
                $raw_fields = $entry->metas; // submitted values

                // Convert form fields array to associative array with ID as key
                $fields_by_id = [];
                foreach ($form_fields as $field_obj) {
                    $fields_by_id[$field_obj->id] = $field_obj;
                }

                $form_data = [];
                foreach ($raw_fields as $id => $value) {

                    if (!isset($fields_by_id[$id])) {
                        continue; // skip unknown fields
                    }

                    $field_obj = $fields_by_id[$id];
                    $type = $field_obj->type;

                    if (in_array($type, ['name', 'address']) && is_array($value)) {
                        $collected_parts = [];

                        foreach ($field_obj->default_value as $sub_label => $_) {
                            $identifier = INTEGRAZO_WZ_Identifier_Util::build_field_identifier($id, $sub_label);
                            $sub_value = isset($value[$sub_label]) ? $value[$sub_label] : '';
                            $form_data[$identifier] = $sub_value;
                            $collected_parts[] = $sub_value;
                        }

                        if (!empty($collected_parts)) {
                            $form_data[$id] = implode(' ', array_filter($collected_parts));
                        }
                    } elseif (in_array($type, ['file', 'upload'])) {
                        $paths = [];

                        // Handle string input (comma-separated URLs)
                        if (is_string($value)) {
                            $urls = array_map('trim', explode(',', $value));
                            foreach ($urls as $url) {
                                $original_path = wp_get_original_image_path($url);
                                $paths[] = $original_path ? $original_path : $url; // fallback to URL if path not found
                            }
                        }
                        // Handle already-array input (uploaded file URLs)
                        elseif (is_array($value)) {
                            foreach ($value as $url) {
                                $original_path = wp_get_original_image_path($url);
                                $paths[] = $original_path ? $original_path : $url;
                            }
                        }

                        $form_data[$id] = $paths;
                    } else {
                        $form_data[$id] = $value;
                    }
                }

                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $form_data, "formidable_form");
            } catch (Throwable $e) {
                return;
            }
        }
    }
}


// ✅ Safe to hook only if the helper class exists
if (class_exists('INTEGRAZO_WZ_FormidableForms_Helper')) {
    add_action('frm_after_create_entry', ['INTEGRAZO_WZ_FormidableForms_Helper', 'capture_submission'], 10, 2);
}
