<?php

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}
if (!class_exists('INTEGRAZO_WZ_KaliForms_Helper')) {
    class INTEGRAZO_WZ_KaliForms_Helper
    {
        /**
         * Get all Kali Forms with ID and title.
         *
         * @return array|string
         */
        public static function get_all_forms()
        {
            if (! class_exists('KaliForms\Inc\Frontend\Form_Processor')) {
                return 'Kali Forms plugin is not installed or activated. Please install and activate it to continue.';
            }

            // Fetch forms
            $args = array(
                'post_type'      => 'kaliforms_forms',
                'numberposts'    => -1, // Get all forms
                'post_status'    => 'publish',
                'orderby'        => 'post_modified',
                'order'          => 'DESC',
            );

            $forms_list = get_posts($args);

            if (empty($forms_list)) {
                return 'No Kali Forms found. Please create at least one form to continue.';
            }

            $data = [];
            foreach ($forms_list as $form) {
                $data[] = [
                    'id'    => (int) $form->ID,
                    'title' => $form->post_title,
                ];
            }

            return $data;
        }



        /**
         * Get all supported fields for a specific Kali Form.
         *
         * @param int $form_id
         * @return array|string
         */
        public static function get_form_fields($form_id)
        {
            $form_list = self::get_all_forms();

            if (! is_array($form_list)) {
                return $form_list;
            }

            $found = false;
            foreach ($form_list as $form) {
                if (isset($form['id']) && (int)$form['id'] === (int)$form_id) {
                    $found = true;
                    break;
                }
            }

            if (! $found) {
                return 'The mapped Kali Form was not found or is inactive/trashed. Please select another form to continue.';
            }

            // Get the raw meta array and extract the first element (JSON string)
            $form_data_raw = get_post_meta($form_id, 'kaliforms_field_components', true);

            // Decode JSON string into PHP array
            $fields_array = json_decode($form_data_raw, true);

            $excluded_types = ['submitButton', 'grecaptcha'];
            $fields = [];

            foreach ($fields_array as $field) {

                // Skip excluded types
                if (in_array($field['id'], $excluded_types, true)) {
                    continue;
                }

                // Use safe fallback values
                $properties = $field['properties'] ?? [];

                $fields[] = [
                    'name'       => $properties['name'],
                    'type'       => $properties['type'],
                    'label' => !empty($properties['caption']) ? $properties['caption'] : $properties['name'],
                    'identifier' => $properties['name'],
                ];
            }

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

            return $fields;
        }
        public static function capture_submission($form_obj)
        {
            try {
                $form_id = $form_obj['data']['formId'];
                $form_data = $form_obj['data'];

                // Define keys to exclude (exact match)
                $excluded_keys = [
                    'sitetitle',
                    'tagline',
                    'siteurl',
                    'homeurl',
                    'admin_email',
                    'entryCounter',
                    'thisPermalink',
                    'submission_link',
                    'userId',
                    'userEmail',
                    'userNicename',
                    'userLogin',
                    'userDisplayName',
                    'formId',
                    'nonce',
                    'formName',
                    'allFields',
                ];

                // Define keys to exclude if they contain these substrings
                $exclude_if_contains = [
                    ':title',
                    ':image',
                    ':imagePath',
                    ':value',
                    ':url',
                ];

                $filtered_placeholders = [];

                foreach ($form_obj['placeholders'] as $key => $value) {
                    $clean_key = trim($key, '{}[]');

                    // Check exact match exclusion
                    if (in_array($clean_key, $excluded_keys)) {
                        continue;
                    }

                    // Check if key contains any of the blocked substrings
                    $contains_blocked_substring = false;
                    foreach ($exclude_if_contains as $needle) {
                        if (strpos($clean_key, $needle) !== false) {
                            $contains_blocked_substring = true;
                            break;
                        }
                    }

                    if ($contains_blocked_substring) {
                        continue;
                    }

                    if (strpos($clean_key, ':id') !== false) {
                        // Split by ":" and take the first part as the new key
                        $parts = explode(':', $clean_key);
                        $new_key = $parts[0];

                        // Convert comma-separated string to array of file IDs
                        $file_id_list = explode(',', $form_data[$new_key]);

                        $listtemp = [];

                        foreach ($file_id_list as $file_id) {
                            $file_id = intval(trim($file_id)); // Clean and cast to int
                            if ($file_id) {
                                $file_path = get_attached_file($file_id);
                                $listtemp[] = $file_path;
                            }
                        }

                        $filtered_placeholders[$new_key] = $listtemp;
                    } else {
                        // Add if not excluded
                        $filtered_placeholders[$clean_key] = $value;
                    }
                }

                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $filtered_placeholders, "kali_forms");
            } catch (Throwable $e) {
            }
        }
    }
}


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