<?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 - Cloudflare Turnstile
 *
 * Add a new "Cloudflare Turnstile" field to Elementor form widget.
 *
 * @since 1.0.0
 */
if (!class_exists('HelloPlus_Cloudflare_recaptcha')) {
    class HelloPlus_Cloudflare_recaptcha extends Field_Base
    {     

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

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

        const OPTION_NAME_SITE_KEY = 'cfefp_cloudflare_site_key';

        const OPTION_NAME_SECRET_KEY = 'cfefp_cloudflare_secret_key';

        protected static function get_recaptcha_name()
        {
            return 'cloudflare_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 reCAPTCHA, you need to add the API Key and complete the setup process in Dashboard > Elementor > Cool FormKit > Settings > Cloudflare Turnstile', '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 'cloudflare_recaptcha';
        }

        /**
         * Get field name.
         *
         * Retrieve Cloudflare Turnstile field label.
         *
         * @since 1.0.0
         * @return string
         */
        public function get_name()
        {
            return esc_html__('Cloudflare Turnstile', '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-cloudflare-recaptcha" 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['cloudflare_recaptcha_style'];
                $size = $item['cloudflare_recaptcha_size'];
                $language = $item['cloudflare_recaptcha_language'];
                $disable_submit_btn = $item['cloudflare_disable_submit_button'];
                $captcha_interaction = $item['captcha_interaction'];




                // Add attributes dynamically
                $widget->add_render_attribute($recaptcha_name . $item_index, [
                    'class' => 'cool-form-cloudflare-recaptcha'.esc_attr($item["_id"]),
                    'data-sitekey' => static::get_site_key(),
                    'data-theme' => esc_attr($theme),
                    'data-size' => esc_attr($size),
                    'data-language' => esc_attr($language),
                    'data-appearance' => esc_attr($captcha_interaction),
                    '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 Cloudflare Turnstile 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 = [

                'cloudflare_recaptcha_size' => [
                    'name' => 'cloudflare_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',
                ],

                'cloudflare_recaptcha_style' => [
                    'name' => 'cloudflare_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',
                ],

                'cloudflare_recaptcha_language' => [
                    'name' => 'cloudflare_recaptcha_language',
                    'label' => esc_html__('Language', 'cool-formkit'),
                    'type' => \Elementor\Controls_Manager::SELECT,
                    'default' => 'en',
                    'options' => [
                        'en' => esc_html__('English', 'cool-formkit'),
                        'hi' => esc_html__('Hindi', 'cool-formkit'),
                        'ja' => esc_html__('Japanese ', 'cool-formkit'),
                        'ko' => esc_html__('Korean ', 'cool-formkit'),
                        'ar' => esc_html__('Arabic', 'cool-formkit'),
                        'bg' => esc_html__('Bulgarian', 'cool-formkit'),
                        'zh' => esc_html__('Chinese', 'cool-formkit'),
                        'hr' => esc_html__('Croatian', 'cool-formkit'),
                        'cs' => esc_html__('Czech', 'cool-formkit'),
                        'da' => esc_html__('Denmark', 'cool-formkit'),
                        'nl' => esc_html__('Netherlands', 'cool-formkit'),
                        'fa' => esc_html__('Iran', 'cool-formkit'),
                        'fi' => esc_html__('Finland', 'cool-formkit'),


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

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

                'cloudflare_disable_submit_button' => [
                    'name' => 'cloudflare_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',
                ],

                'cloudflare_custom_messagge' => [
                    'name' => 'cloudflare_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',
                ],

                'captcha_interaction' => [
                    'name' => 'captcha_interaction',
                    'label' => esc_html__('Appearance Mode', 'cool-formkit'),
                    'type' => \Elementor\Controls_Manager::SELECT,
                    'default' => 'always',
                    'options' => [
                        'always' => esc_html__('Always', 'cool-formkit'),
                        'interaction-only' => esc_html__('Interaction Only', 'cool-formkit'),

                    ],
                    '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-cloudflare-recaptcha-api', 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit', [], null, true);


            wp_register_script('helloplus-cool-formkit-cloudflare-recaptcha-handler', CFKEF_PLUGIN_URL . 'assets/helloplus-addons/js/helloplus-cloudflare-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.cloudflare_recaptcha;
                            const srcURL = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';

                            // Check if reCAPTCHA is enabled
                            if (!config.enabled) {
                                return inputField + '<div class="elementor-alert elementor-alert-info">To use reCAPTCHA, you need to add the API Key and complete the setup process in Dashboard > Elementor > Cool FormKit > Settings >Cloudflare Turnstile.</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.cloudflare_recaptcha_style}" 
                                   data-size="${item.cloudflare_recaptcha_size}" 
                                   data-language="${item.cloudflare_recaptcha_language}"
                                   data-disableBtn="${item.cloudflare_disable_submit_button}"
                                   data-appearance="${item.captcha_interaction}"`;

                            const recaptchaFieldHTML = `<div class="cool-form-cloudflare-recaptcha cloudflare_recaptcha">
                                            <div class="cool-form-cloudflare-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(), // This should return something like 'turnstile'
                ]);

            
                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["cloudflare_custom_messagge"];
                        break;
                    }
                }

                
            
                // Get Turnstile response token
                $turnstile_response = Utils::_unstable_get_super_global_value($_POST, 'cf-turnstile-response'); // Cloudflare returns this in the POST


            
                if (empty($turnstile_response)) {

                    if(!empty($custom_message)){

                        $ajax_handler->add_error($field['id'], esc_html__($custom_message, 'cool-formkit'));
                        return;

                    }else{

                        $ajax_handler->add_error($field['id'], esc_html__(' The Captcha field cannot be blank.', 'cool-formkit'));
                        return;
                    }

                }
            
                $turnstile_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'),
                ];
            
                $secret_key = static::get_secret_key(); // Your Turnstile secret
                $client_ip = Utils::get_client_ip();
            
                $request = [
                    'body' => [
                        'secret' => $secret_key,
                        'response' => $turnstile_response,
                        'remoteip' => $client_ip,
                    ],
                ];
                
                // Turnstile verification endpoint
                $response = wp_remote_post('https://challenges.cloudflare.com/turnstile/v0/siteverify', $request);
            
                $response_code = wp_remote_retrieve_response_code($response);
            
                if (200 !== (int) $response_code) {

                    if(!empty($custom_message)){

                        $ajax_handler->add_error($field['id'], esc_html__($custom_message, 'cool-formkit'));
                        return;

                    }else{

                    $ajax_handler->add_error($field['id'], sprintf(esc_html__('Can not connect to the Turnstile server (%d).', 'cool-formkit'), $response_code));
                    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, Turnstile validation failed.', 'cool-formkit');
            
                    if (!empty($result['error-codes'])) {
                        $result_errors = array_flip($result['error-codes']);
            
                        foreach ($turnstile_errors as $error_key => $error_desc) {
                            if (isset($result_errors[$error_key])) {
                                $message = $turnstile_errors[$error_key];
                                break;
                            }
                        }
                    }

                    if(!empty($custom_message)){

                        $this->add_error($ajax_handler, $field, $custom_message);
                        return;

                    }else{
            
                    $this->add_error($ajax_handler, $field, $message);
                    return;
                    }
                }

                // On success, remove the field from further processing
                $record->remove_field($field['id']);

            }
            
        }
    }
}
