<?php

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}
if (!class_exists('INTEGRAZO_WZ_WPForms_Helper')) {
    class INTEGRAZO_WZ_WPForms_Helper
    {

        /**
         * Validate that the WPForms plugin is active.
         *
         * @return true|string
         */
        private static function validate_plugin()
        {
            if (!function_exists('wpforms')) {
                return 'WPForms plugin is not installed or activated. Please install and activate WPForms to continue.';
            }
            return true;
        }
        /**
         * Get all WPForms forms with ID and title.
         *
         * @return array|string
         */
        public static function get_all_forms()
        {

            $validation = self::validate_plugin();
            if (is_string($validation)) {
                return $validation;
            }

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

            $forms = get_posts($args);

            if (empty($forms)) {
                return 'No WPForms 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 WPForms form.
         *
         * @param int $form_id
         * @return array|string
         */
        public static function get_form_fields($form_id)
        {

            $form = wpforms()->form->get($form_id);
            $post = get_post($form_id);
            if (!$post || $post->post_type !== 'wpforms' || $post->post_status === 'trash') {
                return 'The selected WPForms form was not found. It may have been deleted or is unavailable.';
            }
            $form_data = apply_filters('wpforms_frontend_form_data', wpforms_decode($form->post_content));

            if (empty($form_data['fields']) || !is_array($form_data['fields'])) {
                return 'This WPForms form does not contain any fields. Please add at least one field to continue.';
            }
            $exclude_type = ['pagebreak', 'content', 'divider', 'html', 'captcha', 'entry-preview', 'layout'];
            $exclude_name = ['Repeater'];

            $fields = [];

            foreach ($form_data['fields'] as $field) {

                $field_name = $field['name'] ?? null;
                $field_type = $field['type'] ?? null;
                $field_id   = $field['id'] ?? null;
                $field_label = $field['label'] ?? '';
                // Skip if type or name is in exclude list
                // if (
                //     in_array($field_type, $exclude_type, true) ||
                //     (!is_null($field_name) && strpos($field_name, 'Repeater') !== false) ||
                //     (!is_null($field_type) && strpos($field_type, 'payment-') !== false)
                // ) {
                //     continue;
                // }
                if (
                    in_array($field_type, $exclude_type, true) ||
                    (!is_null($field_name) && strpos($field_name, 'Repeater') !== false)
                ) {
                    continue;
                }


                // Adjust label for specific types
                if ($field_type === 'name') {
                    $field_label = 'Full Name';
                } elseif ($field_type === 'address') {
                    $field_label = 'Full Address';
                }

                $fields[] = [
                    'name'       => $field_id,
                    'type'       => $field_type,
                    'label'      => $field_label,
                    'identifier' => self::build_field_identifier($field_id, $field_label),
                ];

                if ($field_type === "name" || $field_type === "address") {
                    $added_subfields = [];

                    foreach ($field as $key => $value) {
                        if (preg_match('/^([a-zA-Z0-9_]+)_(placeholder|default)$/', $key, $matches)) {
                            $subfield = $matches[1];

                            if (!in_array($subfield, $added_subfields, true) && !in_array($subfield, ['simple', 'confirmation'], true)) {
                                $added_subfields[] = $subfield;

                                $fields[] = [
                                    'name'       => self::build_field_identifier($field_id, $subfield),
                                    'type'       => 'text',
                                    'label'      => $field['label'] . ' - ' . ucfirst(str_replace('_', ' ', $subfield)),
                                    'identifier' => self::build_field_identifier($field_id, $subfield),
                                ];
                            }
                        }
                    }
                }
            }


            return $fields;
        }


        /**
         * Creates a machine-safe field identifier from a label and ID.
         *
         * @param mixed $field_id
         * @param string $field_label
         * @return string
         */
        public static function build_field_identifier($field_id, $field_label)
        {
            $raw = preg_replace('/[^a-zA-Z0-9]+/', '_', $field_label);
            $clean = trim(preg_replace('/_+/', '_', $raw), '_');

            return strtolower($clean . '_' . $field_id);
        }

        public static function process_wpforms_submission($fields, $entry, $form_data, $entry_id)
        {
            try {
                $form_id = $form_data['id'];
                $form_data = [];
                // Handle uploaded files or nested fields if any
                foreach ($fields as $field_id => $field) {
                    if ($field['type'] === 'file-upload') {
                        $form_data[$field_id] = [$field['value']];
                    } else {
                        if (isset($field['value'])) {
                            $form_data[$field_id] = $field['value'];
                        }
                    }
                    if ($field['type'] === "name" || $field['type'] === "address") {
                        foreach ($field as $sub_key => $sub_value) {
                            if (!in_array($sub_key, ['name', 'value', 'id', 'type', 'style', 'value_raw'])) {

                                $field_key = self::build_field_identifier($field_id, $sub_key);
                                $form_data[$field_key] = $sub_value;
                            }
                        }
                    }
                }
                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $form_data, "wp_form");
            } catch (Throwable $e) {
                return;
            }
        }
    }
}


if (class_exists('INTEGRAZO_WZ_WPForms_Helper')) {
    add_action('wpforms_process_complete', ['INTEGRAZO_WZ_WPForms_Helper', 'process_wpforms_submission'], 10, 4);
}
