<?php
// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit; // Prevent direct access to the file.
}

// Check if the class already exists to avoid redeclaration.
if (!class_exists('IAFWZCAI_Form_Name')) {
    class IAFWZCAI_Form_Name
    {
        // Constructor for loading required dependencies, if any
        public function __construct()
        {
            // Add any necessary initialization here
        }

        /**
         * Retrieves the name of a Contact Form 7 form by form ID.
         */
        public function getContactForm7Name($form_id)
        {
            // Fetch the post object using the form ID
            $form = get_post($form_id);

            // Check if the post exists and its post type is 'wpcf7_contact_form'
            if ($form && $form->post_type === 'wpcf7_contact_form') {
                return $form->post_title; // Return the form title if valid
            }

            // Return 'Unknown Form' if the form is invalid or not a Contact Form 7 form
            return __('Unknown Form', 'integrate-with-zoho-campaigns');
        }


        /**
         * Retrieves the name of a WPForms form by form ID.
         */
        public function getWPFormsName($form_id)
        {
            // Check if WPForms is active
            if (function_exists('wpforms')) {
                $form = wpforms()->form->get($form_id);
                return $form ? $form->post_title : __('Unknown Form', 'integrate-with-zoho-campaigns');
            }

            // WPForms is not active
            return __('Unknown Form', 'integrate-with-zoho-campaigns');
        }


        /**
         * Retrieves the name of a Gravity Forms form by form ID.
         */
        public function getGravityFormsName($form_id)
        {
            if (class_exists('GFAPI')) {
                $form = \GFAPI::get_form($form_id);
                return $form ? $form['title'] : __('Unknown Form', 'integrate-with-zoho-campaigns');
            }
            return __('Gravity Forms not found', 'integrate-with-zoho-campaigns');
        }

        /**
         * Retrieves the name of a Ninja Forms form by form ID.
         */
        public function getNinjaFormsName($form_id)
        {
            // if (function_exists('Ninja_Forms')) {
            //     $form = Ninja_Forms()->form($form_id);
            //     return $form ? $form->get_setting('title') : __('Unknown Form', 'integrate-with-zoho-campaigns');
            // }
            return __('Ninja Forms not found', 'integrate-with-zoho-campaigns');
        }

        /**
         * Retrieves the name of a Formidable Forms form by form ID.
         */
        public function getFormidableFormsName($form_id)
        {
            if (class_exists('FrmForm')) {
                $form = \FrmForm::getOne($form_id);
                return $form ? $form->name : __('Unknown Form', 'integrate-with-zoho-campaigns');
            }
            return __('Formidable Forms not found', 'integrate-with-zoho-campaigns');
        }

        /**
         * Retrieves the name of an Everest Forms form by form ID.
         */
        public function getEverestFormsName($form_id)
        {
            // Query for the specific Everest Form post
            $args = [
                'p'              => $form_id, // The specific post ID to retrieve
                'post_type'      => 'everest_form',
                'post_status'    => 'publish', // Ensure it's a published form
            ];

            $forms_query = new WP_Query($args);

            // Check if the form exists
            if ($forms_query->have_posts()) {
                $forms_query->the_post(); // Set up post data for the form
                $form_name = get_the_title();
                wp_reset_postdata(); // Reset post data
                return $form_name;
            }

            // Return default message if no form is found
            return __('Unknown Form', 'integrate-with-zoho-campaigns');
        }


        /**
         * Retrieves the name of an Elementor Form by form ID.
         */
        public function getElementorFormName($combined_id)
        {
            $empty = '';

            // Elementor core + Pro required
            if (! did_action('elementor/loaded') || ! defined('ELEMENTOR_PRO_VERSION')) {
                return $empty;
            }

            try {
                // Expect "{post_id}_{form_widget_id}" (widget id may contain underscores → limit=2)
                $parts = explode('_', (string) $combined_id, 2);
                if (count($parts) < 2) return $empty;

                $post_id        = (int) $parts[0];
                $form_widget_id = trim((string) $parts[1]);
                if ($post_id <= 0 || $form_widget_id === '') return $empty;

                // Prefer _elementor_data; fallback to post_content
                $raw = get_post_meta($post_id, '_elementor_data', true);
                if (! is_string($raw) || $raw === '') {
                    $raw = (string) get_post_field('post_content', $post_id);
                    if ($raw === '') return $empty;
                }

                // Tolerant decode (no pre-unslash)
                $data = $this->decode_elementor_json($raw);
                if (! is_array($data)) return $empty;

                // Traverse to find the exact form widget
                $iterator = new RecursiveIteratorIterator(
                    new RecursiveArrayIterator($data),
                    RecursiveIteratorIterator::SELF_FIRST
                );

                foreach ($iterator as $node) {
                    if (
                        is_array($node)
                        && ($node['elType'] ?? null) === 'widget'
                        && ($node['widgetType'] ?? null) === 'form'
                        && ($node['id'] ?? null) === $form_widget_id
                    ) {
                        $name = (string) ($node['settings']['form_name'] ?? '');
                        $name = trim($name);
                        if ($name === '') $name = 'Untitled Form';

                        // Cap extreme lengths safely (multibyte-aware)
                        if (function_exists('mb_strlen') && mb_strlen($name) > 120) {
                            $name = mb_substr($name, 0, 117) . '...';
                        }

                        return $name;
                    }
                }

                return $empty;
            } catch (Throwable $e) {
                return $empty;
            }
        }
        /**
         * Tolerant decoder for Elementor JSON: as-is → unslash → encoding normalize.
         */
        private function decode_elementor_json($raw)
        {
            // 1) Try as-is
            $data = json_decode($raw, true);
            if (is_array($data)) return $data;

            // 2) Try unslash (if meta stored with added slashes)
            if (function_exists('wp_unslash')) {
                $data = json_decode(wp_unslash($raw), true);
                if (is_array($data)) return $data;
            }

            // 3) Normalize encoding (rare but safe)
            if (function_exists('mb_convert_encoding')) {
                $fixed = mb_convert_encoding($raw, 'UTF-8', 'UTF-8');
                $data  = json_decode($fixed, true);
                if (is_array($data)) return $data;
            }

            return null;
        }


        /**
         * Retrieves the form name based on the form type ID and form ID.
         */
        public function getFormName($form_type, $form_id)
        {
            switch ($form_type) {
                case 1:
                    return $this->getContactForm7Name($form_id);
                case 2:
                    return $this->getWPFormsName($form_id);
                case 3:
                    return $this->getGravityFormsName($form_id);
                case 5:
                    return $this->getFormidableFormsName($form_id);
                case 7:
                    return $this->getElementorFormName($form_id);
                default:
                    return __('Unknown Form Type', 'integrate-with-zoho-campaigns');
            }
        }
    }
    $IAFWZCAI_Form_NameInstance = new IAFWZCAI_Form_Name();
}
