<?php

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

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

            $forms = get_posts($args);

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

            $post_content = $form->post_content;

            // Match all SureForms Gutenberg blocks like <!-- wp:srfm/fieldtype {...} /-->
            preg_match_all('/<!--\s*wp:srfm\/([a-zA-Z0-9_-]+)\s+({.*?})\s*\/-->/', $post_content, $matches, PREG_SET_ORDER);

            $fields = [];
            foreach ($matches as $match) {

                $field_type = $match[1]; // e.g. email, textarea
                $field_json = $match[2];

                $field = json_decode($field_json, true);
                if (is_array($field)) {
                    $label = $field['label'] ?? ucfirst($field_type);
                    $id = $field['slug'];

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




        /**
         * Validate that the SureForms plugin is active.
         *
         * @return true|string
         */
        private static function validate_sureforms_plugin()
        {
            // Make sure the function is available.
            if (!function_exists('is_plugin_active')) {
                require_once ABSPATH . 'wp-admin/includes/plugin.php';
            }

            if (!is_plugin_active('sureforms/sureforms.php')) {
                return 'SureForms plugin is not installed or activated. Please install and activate SureForms to continue.';
            }

            return true;
        }


        /**
         * Validate that the SureForms 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); // Return as an object

            if (!$post || $post->post_type !== 'sureforms_form' || $post->post_status === 'trash') {
                return 'The mapped SureForms 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($form_object)
        {
            try {

                $form_data = [];
                $form_id = isset($form_object['form_id']) ? $form_object['form_id'] : '';
                $fields = isset($form_object['data']) ? $form_object['data'] : [];
                foreach ($fields as $key => $value) {

                    // Trim and check if the value contains ',' or '|'
                    if (is_string($value) && (strpos($value, ',') !== false || strpos($value, '|') !== false)) {
                        // Split by comma or pipe and trim each item
                        $form_data[$key] = array_map('trim', preg_split('/[|,]/', $value));
                    } else {
                        if (filter_var($value, FILTER_VALIDATE_URL) && preg_match('/\/[^\/]+\.[a-z0-9]{1,5}(\?.*)?$/i', $value)) {
                            $form_data[$key] = [$value];
                        } else {
                            // Keep original value
                            $form_data[$key] = $value;
                        }
                    }
                }

                // Continue your processing
                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $form_data, "sure_form");
            } catch (Throwable $e) {
            }
        }
    }
}

// ✅ Safe hook, only if class exists
if (class_exists('INTEGRAZO_WZ_SureForms_Helper')) {
    add_action('srfm_form_submit', ['INTEGRAZO_WZ_SureForms_Helper', 'capture_submission'], 10, 1);
}
