<?php

namespace Cool_FormKit_Pro\Widgets\HelloPlusAddons;

use HelloPlus\Modules\Forms\Fields\Field_Base;
use Cool_FormKit_Pro\Includes\Utils;



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

/**
 * Elementor Form Field - hCAPTCHA
 *
 * Add a new "hCAPTCHA" field to Elementor form widget.
 *
 * @since 1.0.0
 */
if (!class_exists('HelloPlus_h_recaptcha')) {
    class HelloPlus_h_recaptcha extends Field_Base
    {     

        public $depended_scripts = array(
            'helloplus-cool-formkit-h-recaptcha-handler',
            'helloplus-cool-formkit-h-recaptcha-api'
        );

        /**
         * Get field type.
         *
         * Retrieve hCAPTCHA field unique ID.
         *
         * @since 1.0.0
         * @return string
         */

        const OPTION_NAME_SITE_KEY = 'cfefp_h_site_key';

        const OPTION_NAME_SECRET_KEY = 'cfefp_h_secret_key';

        protected static function get_recaptcha_name()
        {
            return 'h_recaptcha';
        }

        public static function get_site_key()
        {
            return get_option(self::OPTION_NAME_SITE_KEY);
        }

        public static function get_secret_key()
        {
            return get_option(self::OPTION_NAME_SECRET_KEY);
        }

        public static function is_enabled()
        {
            return static::get_site_key() && static::get_secret_key();
        }

        public static function get_setup_message()
        {
            return esc_html__('To use hCAPTCHA, you need to add the API Key and complete the setup process in Dashboard > Elementor > Cool FormKit > Settings > hCAPTCHA', 'cool-formkit');
        }

        protected static function get_script_render_param()
        {
            return 'explicit';
        }

        protected static function get_script_name()
        {
            return 'elementor-' . static::get_recaptcha_name() . '-api';
        }


        public function enqueue_scripts()
        {
            if (\Elementor\Plugin::$instance->preview->is_preview_mode()) {
                return;
            }
            $script_name = static::get_script_name();
            wp_enqueue_script($script_name);
        }

        public function get_type()
        {
            return 'h_recaptcha';
        }

        /**
         * Get field name.
         *
         * Retrieve hCAPTCHA field label.
         *
         * @since 1.0.0
         * @return string
         */
        public function get_name()
        {
            return esc_html__('hCAPTCHA', 'cool-formkit');
        }

        /**
         * Render field output on the frontend.
         *
         * @since 1.0.0
         * @param mixed $item
         * @param mixed $item_index
         * @param mixed $form
         * @return void
         */
        public function render($item, $item_index, $widget)
        {

            $recaptcha_html = '<div class="cool-form-h-recaptcha-con" id="form-field-' . $item['custom_id'] . '" >';

            if (static::is_enabled()) {
                $this->enqueue_scripts();

                $recaptcha_name = static::get_recaptcha_name();

                // Get the widget settings for theme & size
                $theme = $item['h_recaptcha_style'];
                $size = $item['h_recaptcha_size'];
                $disable_submit_btn = $item['h_disable_submit_button'];




                // Add attributes dynamically
                $widget->add_render_attribute($recaptcha_name . $item_index, [
                    'id' => 'cool-form-h-recaptcha'.esc_attr($item["_id"]),
                    'class' => 'cool-form-h-recaptcha'.esc_attr($item["_id"]),
                    'data-sitekey' => static::get_site_key(),
                    'data-theme' => esc_attr($theme),
                    'data-size' => esc_attr($size),
                    'data-disableBtn' => esc_attr($disable_submit_btn),

                ]);

                $recaptcha_html .= '<div ' . $widget->get_render_attribute_string($recaptcha_name . $item_index) . '></div>';
            } else {
                $recaptcha_html .= '<div class="elementor-alert elementor-alert-info">';
                $recaptcha_html .= static::get_setup_message();
                $recaptcha_html .= '</div>';
            }

            $recaptcha_html .= '</div>';


            echo $recaptcha_html;
        }


        /**
         * Update form widget controls.
         *
         * Add input fields to allow the user to customize the hCAPTCHA field.
         *
         * @since 1.0.0
         * @param \Elementor\Widget_Base $widget The form widget instance.
         * @return void
         */
        public function update_controls($widget)
        {
            $elementor = Utils::elementor();

            $control_data = $elementor->controls_manager->get_control_from_stack($widget->get_unique_name(), 'form_fields');

            if (is_wp_error($control_data)) {
                return;
            }





            $control_data['fields']['field_label']['conditions'] = [
                'terms' => [
                    [
                        'name' => 'field_type',
                        'operator' => '!in',
                        'value' => [
                            'cloudflare_recaptcha',
                            'h_recaptcha',
                        ],
                    ],
                ],
            ];

            $control_data['fields']['required']['conditions'] = [
                'terms' => [
                    [
                        'name' => 'field_type',
                        'operator' => '!in',
                        'value' => [
                            'cloudflare_recaptcha',
                            'h_recaptcha',
                        ],
                    ],
                ],
            ];

            $control_data['fields']['width']['conditions'] = [
                'terms' => [
                    [
                        'name' => 'field_type',
                        'operator' => '!in',
                        'value' => [
                            'cloudflare_recaptcha',
                            'h_recaptcha',
                        ],
                    ],
                ],
            ];


            $field_controls = [

                'h_recaptcha_size' => [
                    'name' => 'h_recaptcha_size',
                    'label' => esc_html__('Size', 'cool-formkit'),
                    'type' => \Elementor\Controls_Manager::SELECT,
                    'default' => 'normal',
                    'options' => [
                        'normal' => esc_html__( 'Normal', 'cool-formkit' ),
                        'compact' => esc_html__( 'Compact', 'cool-formkit' ),

				    ],
                    'condition' => [
                        'field_type' => $this->get_type(),
                    ],

                    'tab' => 'content',
                    'inner_tab' => 'form_fields_content_tab',
                    'tabs_wrapper' => 'form_fields_tabs',
                ],

                'h_recaptcha_style' => [
                    'name' => 'h_recaptcha_style',
                    'label' => esc_html__('Style', 'cool-formkit'),
                    'type' => \Elementor\Controls_Manager::SELECT,
                    'default' => 'light',
                    'options' => [
                        'light' => esc_html__('Light', 'cool-formkit'),
                        'dark' => esc_html__('Dark', 'cool-formkit'),
                    ],
                    'condition' => [
                        'field_type' => $this->get_type(),
                    ],

                    'tab' => 'content',
                    'inner_tab' => 'form_fields_content_tab',
                    'tabs_wrapper' => 'form_fields_tabs',
                ],


                'h_disable_submit_button' => [
                    'name' => 'h_disable_submit_button',
                    'label' => esc_html__('Disable Submit button', 'cool-formkit'),
                    'type' => \Elementor\Controls_Manager::SWITCHER,
                    'label_on' => esc_html__('Yes', 'cool-formkit'),
                    'label_off' => esc_html__('No', 'cool-formkit'),
                    'default' => 'no',
                    'condition' => [
                        'field_type' => $this->get_type(),
                    ],
                    'tab' => 'content',
                    'inner_tab' => 'form_fields_content_tab',
                    'tabs_wrapper' => 'form_fields_tabs',
                ],

                'h_custom_messagge' => [
                    'name' => 'h_custom_messagge',
                    'label' => esc_html__('Custom Message', 'cool-formkit'),
                    'type' => \Elementor\Controls_Manager::TEXT,
                    'placeholder' => esc_html__('Custom Message', 'cool-formkit'),
                    'default' => '',
                    'condition' => [
                        'field_type' => $this->get_type(),
                    ],
                    'tab' => 'content',
                    'inner_tab' => 'form_fields_content_tab',
                    'tabs_wrapper' => 'form_fields_tabs',
                ],


            ];


            $control_data['fields'] = $this->inject_field_controls($control_data['fields'], $field_controls);

            $widget->update_control('form_fields', $control_data);
        }

        /**
         * Field constructor.
         *
         * @since 1.0.0
         */
        public function __construct()
        {
            parent::__construct();
            add_action('elementor/preview/init', [$this, 'editor_preview_footer']);
            add_action('wp_enqueue_scripts', array($this, 'add_assets_files'));
            add_filter('elementor/editor/localize_settings', [$this, 'localize_settings']);

            add_action( 'elementor/element/ehp-form/section_form_fields/before_section_end', [ $this, 'update_controls' ] );
        }

        public function localize_settings($settings)
        {

            $settings = array_replace_recursive($settings, [
                'forms' => [
                    static::get_recaptcha_name() => [
                        'enabled' => static::is_enabled(),
                        'sitekey' => static::get_site_key(),
                        'setup_message' => '',
                    ],
                ],
            ]);

            return $settings;
        }


        public function add_assets_files()
        {
            $js_common_dep = array('jquery', 'elementor-frontend');
            if (! \Elementor\Plugin::$instance->preview->is_preview_mode() && is_user_logged_in()) {
                $js_common_dep = array_merge(array('elementor-common'), $js_common_dep);
            }

            wp_register_script('helloplus-cool-formkit-h-recaptcha-api', 'https://hcaptcha.com/1/api.js?render=explicit', [], null, true);


            wp_register_script('helloplus-cool-formkit-h-recaptcha-handler', CFKEF_PLUGIN_URL . 'assets/helloplus-addons/js/helloplus-h-recpatcha-handler.js', $js_common_dep, CFKEF_PLUGIN_VERSION, true);
        }

        protected function add_error($ajax_handler, $field, $message)
	    {
		    $ajax_handler->add_error($field['id'], $message);
	    }

        protected function validate_result($result, $field)
        {
            if (! $result['success']) {
                return false;
            }

            return true;
        }


        /**
         * Get script dependencies for this field.
         *
         * @return array
         */
        public function get_script_depends(): array
        {
            return $this->depended_scripts;
        }

        /**
         * Elementor editor preview.
         *
         * @since 1.0.0
         * @return void
         */
        public function editor_preview_footer()
        {
            add_action('wp_footer', [$this, 'content_template_script']);
        }

        /**
         * Content template script.
         *
         * @since 1.0.0
         * @return void
         */
        public function content_template_script()
        {
        ?>
            <script>
                jQuery(document).ready(function() {
                    elementor.hooks.addFilter(
                        'cool_formkit/forms/content_template/field/<?php echo $this->get_type(); ?>',
                        function(inputField, item, i, settings) {


                            const config = elementor.config.forms.h_recaptcha;
                            const srcURL = 'https://hcaptcha.com/1/api.js?render=explicit';

                            // Check if reCAPTCHA is enabled
                            if (!config.enabled) {
                                return inputField + '<div class="elementor-alert elementor-alert-info">To use hCAPTCHA, you need to add the API Key and complete the setup process in Dashboard > Elementor > Cool FormKit > Settings >hCAPTCHA.</div>';
                            }

                            // Enqueue reCAPTCHA script if not already loaded
                            if (!elementorFrontend.elements.$body.find('[src="' + srcURL + '"]').length) {
                                elementorFrontend.elements.$body.append('<scr' + 'ipt src="' + srcURL + '"></scri' + 'pt>');
                            }

                            // Remove label for recaptcha
                            item.field_label = false;


                            const recaptchaData = `data-sitekey="${config.sitekey}" 
                                   data-theme="${item.h_recaptcha_style}" 
                                   data-size="${item.h_recaptcha_size}" 
                                   data-disableBtn="${item.h_disable_submit_button}"`;

                            const recaptchaFieldHTML = `<div class="cool-form-h-recaptcha-con h_recaptcha">
                                            <div id="cool-form-h-recaptcha${item._id}" class="cool-form-h-recaptcha${item._id}" ${recaptchaData}></div>
                                        </div>`;

                            return inputField + recaptchaFieldHTML;
                        },
                        10,
                        4
                    );
                });
            </script>
        <?php
        }

        /**
         *
         *
         * @since 1.0.0
         * @access public
         * @param \ElementorPro\Modules\Forms\Classes\Field_Base   $field
         * @param \ElementorPro\Modules\Forms\Classes\Form_Record  $record
         * @param \ElementorPro\Modules\Forms\Classes\Ajax_Handler $ajax_handler
         * @return void
         */

         public function validation($field, $record, $ajax_handler)
         {

            if($this->is_enabled()){


                $fields = $record->get_field([
                 'type' => static::get_recaptcha_name(), // Should return something like 'hcaptcha'
             ]);
         
             if (empty($fields)) {
                 return;
             }
         
             $field = current($fields);
         
             $form_settings = $record->get('form_settings');
             $custom_message = null;
         
             foreach ($form_settings['form_fields'] as $form_field) {
                 if ($form_field["custom_id"] == $field["id"]) {
                     $custom_message = $form_field["h_custom_messagge"] ?? null;
                     break;
                 }
             }
         
             // Get hCaptcha response token
             $hcaptcha_response = Utils::_unstable_get_super_global_value($_POST, 'h-captcha-response');

         
             if (empty($hcaptcha_response)) {
                 $message = $custom_message ?: esc_html__('The Captcha field cannot be blank.', 'cool-formkit');
                 $ajax_handler->add_error($field['id'], esc_html__($message, 'cool-formkit'));
                 return;
             }
         
             $hcaptcha_errors = [
                 'missing-input-secret' => esc_html__('The secret parameter is missing.', 'cool-formkit'),
                 'invalid-input-secret' => esc_html__('The secret parameter is invalid or malformed.', 'cool-formkit'),
                 'missing-input-response' => esc_html__('The response parameter is missing.', 'cool-formkit'),
                 'invalid-input-response' => esc_html__('The response parameter is invalid or malformed.', 'cool-formkit'),
                 'bad-request' => esc_html__('The request is invalid or malformed.', 'cool-formkit'),
             ];
         
             $secret_key = static::get_secret_key(); // Your hCaptcha secret
             $client_ip = Utils::get_client_ip();
         
             $request = [
                 'body' => [
                     'secret' => $secret_key,
                     'response' => $hcaptcha_response,
                     'remoteip' => $client_ip,
                 ],
             ];
         
             // hCaptcha verification endpoint
             $response = wp_remote_post('https://hcaptcha.com/siteverify', $request);
             $response_code = wp_remote_retrieve_response_code($response);
         
             if (200 !== (int) $response_code) {
                 $message = $custom_message ?: sprintf(
                     esc_html__('Cannot connect to the hCaptcha server (%d).', 'cool-formkit'),
                     $response_code
                 );
                 $ajax_handler->add_error($field['id'], esc_html__($message, 'cool-formkit'));
                 return;
             }
         
             $body = wp_remote_retrieve_body($response);
             $result = json_decode($body, true);

         
             if (empty($result['success']) || !$this->validate_result($result, $field)) {
                 $message = esc_html__('Invalid form, hCaptcha validation failed.', 'cool-formkit');
         
                 if (!empty($result['error-codes'])) {
                     foreach ($result['error-codes'] as $error_key) {
                         if (isset($hcaptcha_errors[$error_key])) {
                             $message = $hcaptcha_errors[$error_key];
                             break;
                         }
                     }
                 }
         
                 $final_message = $custom_message ?: $message;
                 $this->add_error($ajax_handler, $field, $final_message);
                 return;
             }
         
             // On success, remove the field from further processing
             $record->remove_field($field['id']);


            }
         }
         
    }
}
