<?php

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}
if (!class_exists('INTEGRAZO_WZ_NEXForms_Helper')) {
    class INTEGRAZO_WZ_NEXForms_Helper
    {
        /**
         * Get all NEX-Forms with ID and title.
         *
         * @return array|string
         */
        public static function get_all_forms()
        {
            global $wpdb;

            // Check if NEXForms5_Config class exists
            if (!class_exists('NEXForms5_Config')) {
                return 'NEX-Forms plugin is not installed or activated. Please install and activate JetFormBuilder to continue.';
            }

            // Get request parameters safely
            $request = $_GET; // or $_POST depending on usage

            $order_by_allowed = array('id', 'title', 'added', 'last_update');
            $order_allowed = array('ASC', 'DESC');

            $order_by = (isset($request['order_by']) && in_array($request['order_by'], $order_by_allowed)) ? $request['order_by'] : 'id';
            $order = (isset($request['order']) && in_array(strtoupper($request['order']), $order_allowed)) ? strtoupper($request['order']) : 'DESC';
            $limit = isset($request['limit']) ? intval($request['limit']) : 200;

            $results = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT id, title, description, added, last_update, is_form, form_status FROM {$wpdb->prefix}wap_nex_forms ORDER BY $order_by $order LIMIT %d",
                    $limit
                ),
                'ARRAY_A'
            );
            if (empty($results) || !is_array($results)) {
                return 'No NEX-Forms forms found. Please create at least one form to continue.';
            }
            $forms = [];
            foreach ($results as $row) {
                $forms[] = [
                    'id'    => (int) $row['id'],
                    'title' => $row['title'],
                ];
            }

            return $forms;
        }


        /**
         * Get all supported fields for a specific NEX-Forms form.
         *
         * @param int $form_id
         * @return array|string
         */
        public static function get_form_fields($form_id)
        {
            // Validate that the form exists
            $all_forms = self::get_all_forms();
            $form_ids = array_column($all_forms, 'id');

            if (!in_array((int)$form_id, $form_ids, true)) {
                return 'The mapped NEX-Form was not found or is inactive/trashed. Please select another form to continue.';
            }

            global $wpdb;

            $result = $wpdb->get_row(
                $wpdb->prepare(
                    "SELECT * FROM {$wpdb->prefix}wap_nex_forms WHERE id = %d",
                    $form_id
                ),
                'ARRAY_A'
            );
            if (!empty($result) && !empty($result['field_details'])) {
                $field_details = json_decode($result['field_details'], true);
                $excluded_types = ['submit', 'button', 'divider', 'html', 'label', 'reset'];
                $fields = [];
                foreach ($field_details as $field) {
                    if (in_array($field['field_type'], $excluded_types, true)) {
                        continue;
                    }
                    $field_name_cleaned = str_replace(['[', ']'], '', $field['field_name']);
                    $fields[] = [
                        'name'       =>  $field_name_cleaned,
                        'type'       => $field['field_type'],
                        'label'      => $field_name_cleaned,
                        'identifier' => $field_name_cleaned,
                    ];
                }

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

                return $fields;
            }

            return 'This NEX-Form does not contain any fields. Please edit the form and add at least one input field.';
        }
        public static function capture_submission()
        {
            try {
                $form_entry = $_POST;
                $form_id = sanitize_text_field($form_entry['nex_forms_Id']);

                $excluded_keys = [
                    'nex_forms_Id',
                    'ip',
                    'nf_page_title',
                    'company_url',
                    'ms_current_step',
                    'action',
                    'paypal_return_url',
                    'nf_page_id',
                    'page',
                ];

                $filtered_entry = [];

                foreach ($form_entry as $key => $value) {
                    // Skip if key is empty
                    if ($key === '' || in_array($key, $excluded_keys) || strpos($key, 'real_val__') === 0) {
                        continue;
                    }

                    // Skip empty string or completely empty array
                    if ((is_string($value) && trim($value) === '') || (is_array($value) && count(array_filter($value)) === 0)) {
                        continue;
                    }

                    if (is_array($value)) {
                        // Filter out empty values in array and skip if key is still empty
                        $cleaned = array_values(array_filter($value, function ($v) {
                            return !empty($v);
                        }));

                        if (!empty($cleaned)) {
                            $filtered_entry[$key] = $cleaned;
                        }
                    } elseif (strpos($value, ',') !== false) {
                        // Handle comma-separated values
                        $filtered_entry[$key] = array_filter(array_map('trim', explode(',', $value)));
                    } elseif (filter_var($value, FILTER_VALIDATE_URL)) {
                        $filtered_entry[$key] = [$value];
                    } else {
                        $filtered_entry[$key] = $value;
                    }
                }

                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $filtered_entry, "nex_forms");
            } catch (Throwable $e) {
            }
        }
    }
}

// ✅ Safe hook, only if class exists
if (class_exists('INTEGRAZO_WZ_NEXForms_Helper')) {
    add_action('NEXForms_submit_form_data', ['INTEGRAZO_WZ_NEXForms_Helper', 'capture_submission'], 10, 0);
}
