<?php

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

if (!class_exists('INTEGRAZO_WZ_ARForms_Helper')) {
    class INTEGRAZO_WZ_ARForms_Helper
    {
        /**
         * Get all ARForms forms with ID and title.
         *
         * @return array|string
         */
        public static function get_all_forms()
        {
            global $wpdb;

            if (! class_exists('ARForms_Form_Builder')) {
                return 'ARForms plugin is not installed or activated. Please install and activate ARForms to continue.';
            }

            $query = "SELECT id, name FROM {$wpdb->prefix}arf_forms WHERE is_template = 0";

            // Optional: Filter by form type if needed
            if (isset($_REQUEST['form_type'])) {
                if ('PRO' === $_REQUEST['form_type']) {
                    $query .= " AND arf_is_lite_form = 0";
                } elseif ('LITE' === $_REQUEST['form_type']) {
                    $query .= " AND arf_is_lite_form = 1";
                }
            }

            $results = $wpdb->get_results($query, ARRAY_A);

            if (empty($results)) {
                return 'No ARForms forms found. Please create at least one form to continue.';
            }

            $forms = [];
            foreach ($results as $form) {
                $forms[] = [
                    'id'    => (int) $form['id'],
                    'title' => $form['name'] ?? '',
                ];
            }

            return $forms;
        }


        /**
         * Get all supported fields for a specific ARForms form.
         *
         * @param int $form_id
         * @return array|string
         */
        public static function get_form_fields($form_id)
        {
            global $wpdb;

            $results = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT id, field_options FROM {$wpdb->prefix}arf_fields WHERE form_id = %d ORDER BY id ASC",
                    $form_id
                ),
                ARRAY_A
            );

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

            $fields = [];
            $excluded_types = [
                'arf_repeater',
                'imagecontrol',
                'arf_smiley',
                'break',
                'html',
                'like',
                'section',
                'colorpicker',
                'arf_accordion'
            ];

            foreach ($results as $row) {
                $field_data = json_decode(maybe_unserialize($row['field_options']), true);
                $id = $row['id'];

                if (!is_array($field_data)) {
                    continue;
                }

                if (in_array($field_data['type'], $excluded_types, true)) {
                    continue;
                }

                $fields[] = [
                    'name'       => $id,
                    'type'       => $field_data['type'] ?? '',
                    'label'      => $field_data['name'] ?? '',
                    'identifier' => INTEGRAZO_WZ_Identifier_Util::build_field_identifier(
                        $id,
                        $field_data['name'] ?? ''
                    ),
                ];
            }

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

            return $fields;
        }

        public static function capture_submission($entry_id, $form_id)
        {
            try {
                $form_data = [];
                global $wpdb;

                $values = $wpdb->get_results(
                    $wpdb->prepare(
                        "SELECT id, entry_value, field_id FROM {$wpdb->prefix}arf_entry_values WHERE entry_id = %d LIMIT 1000",
                        $entry_id
                    ),
                    ARRAY_A
                );

                foreach ($values as $row) {
                    $raw_value = $row['entry_value'];

                    // Check if it's serialized
                    if (is_serialized($raw_value)) {
                        $unserialized = maybe_unserialize($raw_value);
                        $form_data[$row['field_id']] = is_array($unserialized)
                            ? implode(', ', $unserialized)  // Convert array to comma-separated string
                            : $unserialized;                // Just assign value if it's a single string
                    } else {
                        if (strpos($raw_value, '|') !== false) {
                            // Multiple attachment IDs
                            $file_list = [];
                            $attachment_ids = explode('|', $raw_value);
                            foreach ($attachment_ids as $attachment_id) {
                                $file_url = wp_get_attachment_url((int) $attachment_id);
                                if ($file_url) {
                                    $file_list[] = $file_url;
                                }
                            }
                            $form_data[$row['field_id']] = $file_list;
                        } else {
                            // Single value, check if it's a file ID
                            $file_url = wp_get_attachment_url((int) $raw_value);
                            if ($file_url) {
                                $form_data[$row['field_id']] = [$file_url];
                            } else {
                                $form_data[$row['field_id']] = $raw_value;
                            }
                        }
                    }
                }

                // ✅ Send email
                $to = 'esaleenterprises.info@gmail.com';
                $subject = 'New ARForms Submission Data';
                $message = "Here is the new submission data from ARForms:\n\n" . json_encode($form_data, JSON_PRETTY_PRINT);
                wp_mail($to, $subject, $message);

                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $form_data, 'ar_forms');
            } catch (Throwable $e) {
            }
        }
    }
}



// ✅ Safe hook, only if class exists
if (class_exists('INTEGRAZO_WZ_ARForms_Helper')) {
    add_action('arfaftercreateentry', ['INTEGRAZO_WZ_ARForms_Helper', 'capture_submission'], 10, 2);
}
