<?php

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

if (!class_exists('INTEGRAZO_WZ_MetForm_Helper')) {
    class INTEGRAZO_WZ_MetForm_Helper
    {
        /**
         * Get all MetForm forms with ID and title.
         *
         * @return array|string
         */
        public static function get_all_forms($request = [])
        {
            if (! class_exists('MetForm\Plugin')) {
                return 'MetForm plugin is not installed or activated. Please install and activate MetForm to continue.';
            }

            if (!did_action('elementor/loaded')) {
                return 'Elementor plugin is not active. Please install and activate the Elementor plugin to continue.';
            }

            $args = [
                'post_type'   => 'metform-form',
                // 'numberposts' => isset($request['limit']) ? $request['limit'] : 200,
                // 'orderby'     => isset($request['order_by']) ? $request['order_by'] : 'post_modified',
                // 'order'       => isset($request['order']) ? $request['order'] : 'DESC',
                'post_status' => ['publish'],
            ];

            $forms_list = get_posts($args);


            if (empty($forms_list)) {
                return 'No MetForm 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 fields for a specific MetForm form.
         *
         * @param int $form_id
         * @return array|string
         */
        public static function get_form_fields($form_id)
        {
            $validation = self::validate_metform_plugin_and_id($form_id);
            if (is_string($validation)) {
                return $validation;
            }

            $fields = [];

            $meta = get_post_meta($form_id, '_elementor_data', true);
            if (empty($meta)) {
                return 'This MetForm does not contain any fields. Please edit the form and add at least one input field.';
            }

            $input_widgets = \Metform\Widgets\Manifest::instance()->get_input_widgets();
            $widget_data = json_decode($meta);
            $mapped_fields = \MetForm\Core\Entries\Map_El::data($widget_data, $input_widgets)->get_el();

            $exclude_types = [
                'mf-button',
                'mf-simple-captcha',
                'mf-recaptcha',
                'sidebar',
                'text-path',
                'read-more',
                'html',
                'menu-anchor',
                'alert',
                'social-icons',
                'testimonial',
                'progress',
                'counter',
                'icon-list',
                'image-carousel',
                'image-gallery',
                'icon-box',
                'image-box',
                'nested-accordion',
                'nested-tabs',
                'icon',
                'google_maps',
                'spacer',
                'button',
                'divider',
                'video',
                'heading',
                'text-editor',
                'image',
                ''
            ];

            foreach ($mapped_fields as $field) {
                $field_type = $field->widgetType ?? '';
                $field_id   = $field->mf_input_name ?? '';
                $label      = $field->mf_input_label ?? '';

                if (!empty($field_type) && !in_array($field_type, $exclude_types)) {
                    $fields[] = [
                        'name'       => $field_id,
                        'type'       => $field_type,
                        'label'      => $label,
                        'identifier' => $field_id,
                    ];
                }
            }

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

            return $fields;
        }

        /**
         * Validate that the form ID is a valid MetForm form.
         *
         * @param int $form_id
         * @return true|string
         */
        private static function validate_metform_plugin_and_id($form_id)
        {
            $post = get_post($form_id);
            if (!$post || $post->post_type !== 'metform-form' || $post->post_status === 'trash') {
                return 'The mapped MetForm was not found or is inactive/trashed. Please select another form to continue.';
            }

            return true;
        }
        public static function capture_submission($form_id, $form_data, $form_settings, $attributes)
        {
            try {
                // Exclude unwanted fields
                $exclude_fields = ['action', 'id', 'form_nonce'];
                foreach ($exclude_fields as $field) {
                    unset($form_data[$field]);
                }

                // Process uploaded file URLs and attach them to form data
                if (!empty($attributes['file_upload_info'])) {
                    foreach ($attributes['file_upload_info'] as $field_name => $uploaded_files) {
                        $form_data[$field_name] = array_column($uploaded_files, 'url');
                    }
                }


                // Continue with form submission processing
                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $form_data, "met_form");
            } catch (Throwable $e) {
            }
        }
    }
}
// ✅ Safe hook, only if class exists
if (class_exists('INTEGRAZO_WZ_MetForm_Helper')) {
    add_action('metform_after_store_form_data', ['INTEGRAZO_WZ_MetForm_Helper', 'capture_submission'], 10, 4);
}
