<?php

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

            $args = [
                'post_type'      => 'jet-form-builder',
                'posts_per_page' => -1,
                'post_status'    => ['publish'],
            ];

            $forms = get_posts($args);

            if (empty($forms)) {
                return 'No JetFormBuilder 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 JetFormBuilder 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 = get_post($form_id);

            // Set up JetFormBuilder parser
            \jet_fb_context()->set_parsers(
                \Jet_Form_Builder\Blocks\Block_Helper::get_blocks_by_post($form)
            );

            $fields = [];

            foreach (\jet_fb_context()->iterate_parsers() as $name => $parser) {
                if ($parser->is_secure()) {
                    continue;
                }

                $fields[] = [
                    'name'       => $name,
                    'label'      => $parser->get_label(),
                    'type'       => $parser->get_type(),
                    'identifier' =>  $name,
                ];
            }
            if (empty($fields)) {
                return 'This JetFormBuilder Form does not contain any fields. Please edit the form and add at least one input field.';
            }
            return $fields;
        }


        /**
         * Validate that the JetFormBuilder plugin is active.
         *
         * @return true|string
         */
        private static function validate_jetformbuilder_plugin()
        {
            if (!class_exists('\Jet_Form_Builder\Classes\Tools')) {
                return 'JetFormBuilder plugin is not installed or activated. Please install and activate JetFormBuilder to continue.';
            }

            return true;
        }

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

            $post = get_post($form_id);
            if (!$post || $post->post_type !== 'jet-form-builder' || $post->post_status === 'trash') {
                return 'The mapped JetFormBuilder Form was not found or is inactive/trashed. Please select another form to continue.';
            }

            return true;
        }
        public static function capture_submission($handler, $status)
        {
            try {
                $form_id = $handler->form_id;

                // Get saved record IDs
                $ids = $handler->action_handler->context['save_record'] ?? [];

                $form_data = [];

                foreach ($ids as $id) {
                    $fields = \JFB_Modules\Form_Record\Query_Views\Record_Fields_View::get_request($id);
                    foreach ($fields as $field) {
                        $value = $field["field_value"];

                        if ($field["field_type"] === "media-field") {
                            // Always wrap media field in array format (if not already)
                            if (is_array($value)) {
                                $form_data[$field["field_name"]] = $value;
                            } elseif (is_string($value) && strpos($value, ',') !== false) {
                                $form_data[$field["field_name"]] = array_map('trim', explode(',', $value));
                            } else {
                                $form_data[$field["field_name"]] = [$value];
                            }
                        } else {
                            // Try decoding if it's a valid JSON string
                            $decoded = json_decode($value, true);
                            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                                $value = $decoded; // Use decoded array
                            }
                            $form_data[$field["field_name"]] = $value;
                        }
                    }
                }


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

// ✅ Safe hook, only if class exists
if (class_exists('INTEGRAZO_WZ_JetFormBuilder_Helper')) {
    add_action('jet-form-builder/form-handler/after-send', ['INTEGRAZO_WZ_JetFormBuilder_Helper', 'capture_submission'], 10, 2);
}
