<?php
defined('ABSPATH') or die("You can't access this file directly.");


add_action( 'add_meta_boxes', 'qcld_seohelp_add_keyword_box' );
if ( ! function_exists( 'qcld_seohelp_add_keyword_box' ) ) {
    function qcld_seohelp_add_keyword_box() {
        $screens = array( 'post', 'page' );

        $image_url = '<img src="'.esc_url(qcld_seohelp_img_url."/seo-help-mini.png").'" alt="Seo Help"> ';

        foreach ( $screens as $screen ) {
            add_meta_box(
                'qcld_seohelp_keyword_id',
                $image_url. ' '. esc_html('SEO Help', 'seo-help' ),   
                'qcld_seohelp_keywordbox_html',  
                $screen,                           
                'side',
                'high'
            );
        }

    }
}

if ( ! function_exists( 'qcld_seohelp_keywordbox_html' ) ) {
    function qcld_seohelp_keywordbox_html( $post ) {
        ?>
<div class="qcld-seohelp">
    <label for="qcld_keyword_suggestion" class="form-label"><?php esc_html_e('Keyword suggestion', 'seo-help'); ?></label><br>
            <input type="text" id="qcld_keyword_suggestion_text" class="form-control" /><br>
            <label for="qcld-seo-language" class="form-label"><?php esc_html_e('Country // Language', 'seo-help'); ?></label><br>
            <select value="" name="country" id="qcld-seo-language" class="form-select">
                    <optgroup label="North america">
                        <option value="us-en"><?php esc_html_e('United States', 'seo-help'); ?></option>
                        <option value="ca-en"><?php esc_html_e('Canada', 'seo-help'); ?></option>
                    </optgroup>
                    <optgroup label="Europe">
                        <option value="uk-en"><?php esc_html_e('United Kingdom', 'seo-help'); ?></option>
                        <option value="nl-nl"><?php esc_html_e('Netherlands', 'seo-help'); ?></option>
                        <option value="be-fr"><?php esc_html_e('Belgium (FR)', 'seo-help'); ?></option>
                        <option value="be-nl"><?php esc_html_e('Belgium (NL)', 'seo-help'); ?></option>
                        <option value="de-de"><?php esc_html_e('Germany', 'seo-help'); ?></option>
                        <option value="fr-fr"><?php esc_html_e('France', 'seo-help'); ?></option>
                        <option value="dk-dk"><?php esc_html_e('Denmark', 'seo-help'); ?></option>
                        <option value="ie-ie"><?php esc_html_e('Ireland', 'seo-help'); ?></option>
                        <option value="it-it"><?php esc_html_e('Italy', 'seo-help'); ?></option>   
                        <option value="es-es"><?php esc_html_e('Spain', 'seo-help'); ?></option>
                        <option value="pt-pt"><?php esc_html_e('Portugal', 'seo-help'); ?></option>
                    </optgroup> 
                    <optgroup label="Other">
                        <option value="au-en"><?php esc_html_e('Australia', 'seo-help'); ?></option>
                        <option value="nz-en"><?php esc_html_e('New Zealand (EN)', 'seo-help'); ?></option>
                    </optgroup>
            </select>
            <br>
    
    <button id="qcld_keyword_search" class="btn btn-info"><?php esc_html_e('Search', 'seo-help'); ?></button>

    <div class="modal fade" id="keywords_resultBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="keywords_resultLabel"><?php esc_html_e('keywords Result', 'seo-help'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" class="postid" value="<?php echo esc_attr($post->ID); ?>"/>
            <div id="keywords_result">
             </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php esc_html_e('Close', 'seo-help'); ?></button>
                <a id="seo_help_createtag" class="btn btn-primary"><?php esc_html_e('Create tag', 'seo-help'); ?></a>
            </div>
            </div>
        </div>
    </div>
</div>
<?php 
    }
}

add_action( 'add_meta_boxes', 'qcld_seohelp_add_suggest_box' );
if ( ! function_exists( 'qcld_seohelp_add_suggest_box' ) ) {
    function qcld_seohelp_add_suggest_box() {
        $screens = array( 'post', 'page' );

        $image_url = '<img src="'.esc_url(qcld_seohelp_img_url."/seo-help-mini.png").'" alt="Seo Help"> ';

        foreach ( $screens as $screen ) {
            add_meta_box(
                'qcld_seohelp_suggest_id',
                $image_url. ' '. esc_html('SEO Help', 'seo-help' ),   
                'qcld_seohelp_suggest_html',  
                $screen,                           
                'side',
                'high'
            );
        }

    }
}

if ( ! function_exists( 'qcld_seohelp_suggest_html' ) ) {
    function qcld_seohelp_suggest_html( $post ) {
        ?>
<div class="qcld-seohelp">
    <label for="qcld_keyword_suggestion" class="form-label"><?php esc_html_e('Suggest:', 'seo-help'); ?></label><br>

    <button id="qcld_suggest_title" class="button button-primary" data-post_id="<?php echo esc_attr($post->ID); ?>"><img src="<?php echo esc_url(qcld_seohelp_img_url.'/magic-wand-1.png'); ?>" alt="Titles"> <?php esc_html_e('Titles', 'seo-help'); ?></button>
    <button id="qcld_suggest_excerpt" class="button button-primary" data-post_id="<?php echo esc_attr($post->ID); ?>"><img src="<?php echo esc_url(qcld_seohelp_img_url.'/magic-wand-1.png'); ?>" alt="Excerpts"> <?php esc_html_e('Excerpts', 'seo-help'); ?></button>

   <!--  <button id="qcld_translate_test" class="button button-primary button-large" data-post_id="<?php echo esc_attr($post->ID); ?>"><img src="<?php echo esc_url(qcld_seohelp_img_url.'/magic-wand-1.png'); ?>" alt="Translate Text" > <?php esc_html_e('Translate Text', 'seo-help'); ?></button>

    <button id="qcld_grammar_checker_post" class="button button-primary button-large" data-post_id="<?php echo esc_attr($post->ID); ?>"><img src="<?php echo esc_url(qcld_seohelp_img_url.'/magic-wand-1.png'); ?>" alt="Translate Post" > <?php esc_html_e('Grammer Checker', 'seo-help'); ?></button> -->

    <div class="modal fade" id="qcld_suggest_title_modal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="suggest_resultLabel"><?php esc_html_e('Suggested Titles', 'seo-help'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="qcld_suggest_result">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php esc_html_e('Close', 'seo-help'); ?></button>
            </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="qcld_suggest_excerpt_modal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="suggest_resultLabel"><?php esc_html_e('Suggested Excerpt', 'seo-help'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="qcld_suggest_excerpt_result">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php esc_html_e('Close', 'seo-help'); ?></button>
            </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="qcld_translate_test_modal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="suggest_resultLabel"><?php esc_html_e('Translate Text', 'seo-help'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="qcld_translate_test_result">
                </div>
                <div id="qcld_translate_test_result_data" style="display: none">
                    <?php
                        wp_editor('','qcld_translate_test_result_msg', array('media_buttons' => false, 'textarea_name' => 'qcld_translate_test_result_msg', 'editor_height' => 600 ) );
                      ?>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php esc_html_e('Close', 'seo-help'); ?></button>
            </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="qcld_grammar_checker_modal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="suggest_resultLabel"><?php esc_html_e('Grammer Checker', 'seo-help'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="qcld_grammar_checker_result">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php esc_html_e('Close', 'seo-help'); ?></button>
            </div>
            </div>
        </div>
    </div>
</div>
<?php 
    }
}


add_action( 'wp_ajax_qcld_seohelp_suggestion_title', 'qcld_seohelp_suggestion_title_callback' );
add_action( 'wp_ajax_nopriv_qcld_seohelp_suggestion_title', 'qcld_seohelp_suggestion_title_callback' );

if ( ! function_exists( 'qcld_seohelp_suggestion_title_callback' ) ) {
    function qcld_seohelp_suggestion_title_callback(){

        check_ajax_referer( 'seo-help', 'security');

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( esc_html( 'Unauthorized', 'seo-help' ) );
            wp_die();
        }

        $post_id        = isset($_POST['post_id'])          ? intval(sanitize_text_field(wp_unslash($_POST['post_id']))) : '';

        if(!empty($post_id)){
            $post = get_post( $post_id );
            if ( !$post ) {
                return false;
            }
            $text = apply_filters( 'qcld_pre_post_content', $post->post_content, $post_id );
            $pattern = '/\[mwai_.*?\]/';
            $text = preg_replace( $pattern, '', $text );
         
            $text = apply_filters( 'the_content', $text );
          
            //$text = $this->clean_text( $text );
            $text = html_entity_decode( $text );
            $text = wp_strip_all_tags( $text );
            $text = preg_replace( '/[\r\n]+/', "\n", $text );
            $text = preg_replace( '/\n+/', "\n", $text );
            $text = preg_replace( '/\t+/', "\t", $text );
            $text =  $text . " ";

            //$text = $this->clean_sentences( $text );
            // Step 1: Identify URLs and replace them with a placeholder.
            $urlPattern = '/\bhttps?:\/\/[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/))/';
            preg_match_all($urlPattern, $text, $urls);
            $urlPlaceholders = array();
            foreach ($urls[0] as $index => $url) {
                $placeholder = "{urlPlaceholder" . $index . "}";
                $text = str_replace($url, $placeholder, $text);
                $urlPlaceholders[$placeholder] = $url;
            }
        
            $maxLength = (int)(isset($maxLength) ? $maxLength : 4096);
            $sentences = preg_split('/(?<=[.?!。．！？])\s+/u', $text, -1, PREG_SPLIT_NO_EMPTY);
            $hashes = array();
            $uniqueSentences = array();
            $total = 0;
        
            foreach ( $sentences as $sentence ) {
                $sentence = preg_replace( '/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $sentence );
                $hash = md5( $sentence );
                if ( !in_array( $hash, $hashes ) ) {
                    $length = mb_strlen( $sentence, 'UTF-8' );
                    if ( $total + $length > $maxLength ) {
                        continue;
                    }
                    $hashes[] = $hash;
                    $uniqueSentences[] = $sentence;
                    $total += $length;
                }
            }
        
            $freshText = implode( " ", $uniqueSentences );
        
            // Step 3: Restore URLs in the final text.
            foreach ($urlPlaceholders as $placeholder => $url) {
                $freshText = str_replace($placeholder, $url, $freshText);
            }
        
            $freshText = preg_replace( '/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $freshText );
            $text =  $freshText;

            $text = apply_filters( 'qcld_post_content', $text, $post_id );
            //return $text;

            $prompt = apply_filters( 'qcld_prompt_suggest_titles', "Give me up to 10 SEO-optimized, descriptive titles for the following text. Separate the titles by new line but do not use Lists. Do not add any additional text. Focus on clarity and relevance to the content. Here is the text:\n\n", $post_id );

            $qcld_prompt_suggest_title = $prompt . $text;

            $results  = apply_filters('qcld_seohelp_ai_content_settings_processing_data_function', $qcld_prompt_suggest_title );

            $results_data = '';
            if(!empty($results)){
                $results = explode("\n",$results);
                $results_data .= '<p>Pick a new title by clicking on it.</p>';
                foreach ($results as $key => $keywordResultss){
                    if(isset( $keywordResultss ) && !empty( $keywordResultss )){
                        $results_data.= '<div class="qcld_seohelp_suggest_title">'.trim($keywordResultss).'</div>';
                    
                    }
                }

            }
        
        }

        wp_send_json([ 'status'=> 'success', 'keywords'=> $results_data, 'results'=> $results ]);
        wp_die();

    }
}

add_action( 'wp_ajax_qcld_seohelp_suggestion_excerpt', 'qcld_seohelp_suggestion_excerpt_callback' );
add_action( 'wp_ajax_nopriv_qcld_seohelp_suggestion_excerpt', 'qcld_seohelp_suggestion_excerpt_callback' );

if ( ! function_exists( 'qcld_seohelp_suggestion_excerpt_callback' ) ) {
    function qcld_seohelp_suggestion_excerpt_callback(){

        check_ajax_referer( 'seo-help', 'security');

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( esc_html( 'Unauthorized', 'seo-help' ) );
            wp_die();
        }

        $post_id        = isset($_POST['post_id'])          ? intval(sanitize_text_field(wp_unslash($_POST['post_id']))) : '';

        if(!empty($post_id)){
            $post = get_post( $post_id );
            if ( !$post ) {
                return false;
            }
            $text = apply_filters( 'qcld_pre_post_content', $post->post_content, $post_id );
            $pattern = '/\[mwai_.*?\]/';
            $text = preg_replace( $pattern, '', $text );
         
            $text = apply_filters( 'the_content', $text );
          
            //$text = $this->clean_text( $text );
            $text = html_entity_decode( $text );
            $text = wp_strip_all_tags( $text );
            $text = preg_replace( '/[\r\n]+/', "\n", $text );
            $text = preg_replace( '/\n+/', "\n", $text );
            $text = preg_replace( '/\t+/', "\t", $text );
            $text =  $text . " ";

            //$text = $this->clean_sentences( $text );
            // Step 1: Identify URLs and replace them with a placeholder.
            $urlPattern = '/\bhttps?:\/\/[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/))/';
            preg_match_all($urlPattern, $text, $urls);
            $urlPlaceholders = array();
            foreach ($urls[0] as $index => $url) {
                $placeholder = "{urlPlaceholder" . $index . "}";
                $text = str_replace($url, $placeholder, $text);
                $urlPlaceholders[$placeholder] = $url;
            }
        
            $maxLength = (int)(isset($maxLength) ? $maxLength : 4096);
            $sentences = preg_split('/(?<=[.?!。．！？])\s+/u', $text, -1, PREG_SPLIT_NO_EMPTY);
            $hashes = array();
            $uniqueSentences = array();
            $total = 0;
        
            foreach ( $sentences as $sentence ) {
                $sentence = preg_replace( '/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $sentence );
                $hash = md5( $sentence );
                if ( !in_array( $hash, $hashes ) ) {
                    $length = mb_strlen( $sentence, 'UTF-8' );
                    if ( $total + $length > $maxLength ) {
                        continue;
                    }
                    $hashes[] = $hash;
                    $uniqueSentences[] = $sentence;
                    $total += $length;
                }
            }
        
            $freshText = implode( " ", $uniqueSentences );
        
            // Step 3: Restore URLs in the final text.
            foreach ($urlPlaceholders as $placeholder => $url) {
                $freshText = str_replace($placeholder, $url, $freshText);
            }
        
            $freshText = preg_replace( '/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $freshText );
            $text =  $freshText;

            $text = apply_filters( 'qcld_post_content', $text, $post_id );
            //return $text;

           // $prompt = apply_filters( 'qcld_prompt_suggest_excerpts', "Give me up to 10 SEO-optimized, descriptive introduction for the following text, using 120 to 170 characters. Separate the introduction by new line but do not use Lists. Do not add any additional text. Focus on clarity and relevance to the content. Here is the text:\n\n", $post_id );

            $prompt = apply_filters( 'qcld_prompt_suggest_excerpts', "Give me up to 10 SEO-optimized, captivating excerpts for the following text, between 50-60 words. Separate the excerpts by new line but do not use Lists or numbers. Do not add any additional text. Focus on clarity and relevance to the content. Here is the text:\n\n", $post_id );

            $qcld_prompt_suggest_title = $prompt . $text;

            $results  = apply_filters('qcld_seohelp_ai_content_settings_processing_data_function', $qcld_prompt_suggest_title );

            $results_data = '';
            if(!empty($results)){
                $results = explode("\n",$results);
                $results_data .= '<p>Pick a new Excerpt by clicking on it.</p>';
                foreach ($results as $key => $keywordResultss){
                    if(isset( $keywordResultss ) && !empty( $keywordResultss )){
                        $results_data.= '<div class="qcld_seohelp_suggest_excerpt" data-post_id='.esc_attr($post_id).'>'.trim($keywordResultss).'</div>';
                    }
                    
                }

            }
        
        }

        wp_send_json([ 'status'=> 'success', 'keywords'=> $results_data, 'results'=> $results ]);
        wp_die();

    }
}


add_action( 'wp_ajax_qcld_seohelp_suggestion_excerpt_save', 'qcld_seohelp_suggestion_excerpt_save_callback' );
add_action( 'wp_ajax_nopriv_qcld_seohelp_suggestion_excerpt_save', 'qcld_seohelp_suggestion_excerpt_save_callback' );

if ( ! function_exists( 'qcld_seohelp_suggestion_excerpt_save_callback' ) ) {
    function qcld_seohelp_suggestion_excerpt_save_callback(){

        check_ajax_referer( 'seo-help', 'security');

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( esc_html( 'Unauthorized', 'seo-help' ) );
            wp_die();
        }

        $post_id            = isset($_POST['post_id'])          ? intval(sanitize_text_field(wp_unslash($_POST['post_id']))) : '';
        $suggest_excerpt    = isset($_POST['suggest_excerpt'])          ? sanitize_text_field(wp_unslash($_POST['suggest_excerpt'])) : '';

        $results = 'Somethig Went worng!';

        if(!empty($post_id)){
            $post = get_post( $post_id );
            if ( !$post ) {
                wp_send_json([ 'status'=> 'success', 'keywords'=> $results ]);
                wp_die();
            }
            $suggest_excerpt = apply_filters( 'the_excerpt', $suggest_excerpt );

            $the_post = array(
                  'ID'           => $post_id,
                  'post_excerpt' => $suggest_excerpt,
              );
            wp_update_post( $the_post );
        
            $results = 'Excerpt Successfully Updated';
        }


        wp_send_json([ 'status'=> 'success', 'results'=> $results ]);
        wp_die();

    }
}

// qcld_seohelp_translate_post

add_action( 'wp_ajax_qcld_seohelp_translate_post', 'qcld_seohelp_translate_post_callback' );
add_action( 'wp_ajax_nopriv_qcld_seohelp_translate_post', 'qcld_seohelp_translate_post_callback' );

if ( ! function_exists( 'qcld_seohelp_translate_post_callback' ) ) {
    function qcld_seohelp_translate_post_callback(){

        check_ajax_referer( 'seo-help', 'security');

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( esc_html( 'Unauthorized', 'seo-help' ) );
            wp_die();
        }

        $post_id        = isset($_POST['post_id'])          ? intval(sanitize_text_field(wp_unslash($_POST['post_id']))) : '';

        if(!empty($post_id)){
            $post = get_post( $post_id );
            if ( !$post ) {
                return false;
            }
            $text = apply_filters( 'qcld_pre_post_content', $post->post_content, $post_id );
            $pattern = '/\[mwai_.*?\]/';
            $text = preg_replace( $pattern, '', $text );
         
            $text = apply_filters( 'the_content', $text );
          
            //$text = $this->clean_text( $text );
            $text = html_entity_decode( $text );
            $text = wp_strip_all_tags( $text );
            $text = preg_replace( '/[\r\n]+/', "\n", $text );
            $text = preg_replace( '/\n+/', "\n", $text );
            $text = preg_replace( '/\t+/', "\t", $text );
            $text =  $text . " ";

            //$text = $this->clean_sentences( $text );
            // Step 1: Identify URLs and replace them with a placeholder.
            $urlPattern = '/\bhttps?:\/\/[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/))/';
            preg_match_all($urlPattern, $text, $urls);
            $urlPlaceholders = array();
            foreach ($urls[0] as $index => $url) {
                $placeholder = "{urlPlaceholder" . $index . "}";
                $text = str_replace($url, $placeholder, $text);
                $urlPlaceholders[$placeholder] = $url;
            }
        
            $maxLength = (int)(isset($maxLength) ? $maxLength : 4096);
            $sentences = preg_split('/(?<=[.?!。．！？])\s+/u', $text, -1, PREG_SPLIT_NO_EMPTY);
            $hashes = array();
            $uniqueSentences = array();
            $total = 0;
        
            foreach ( $sentences as $sentence ) {
                $sentence = preg_replace( '/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $sentence );
                $hash = md5( $sentence );
                if ( !in_array( $hash, $hashes ) ) {
                    $length = mb_strlen( $sentence, 'UTF-8' );
                    if ( $total + $length > $maxLength ) {
                        continue;
                    }
                    $hashes[] = $hash;
                    $uniqueSentences[] = $sentence;
                    $total += $length;
                }
            }
        
            $freshText = implode( " ", $uniqueSentences );
        
            // Step 3: Restore URLs in the final text.
            foreach ($urlPlaceholders as $placeholder => $url) {
                $freshText = str_replace($placeholder, $url, $freshText);
            }
        
            $freshText = preg_replace( '/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $freshText );
            $text =  $freshText;

            $text = apply_filters( 'qcld_post_content', $text, $post_id );
            //return $text;

            $locale = get_locale();
            $code = strtolower( substr( $locale, 0, 2 ) );
            $humanLanguage = strtr( $code, MWAI_ALL_LANGUAGES );
            $lang = apply_filters( 'wpml_post_language_details', null, $post_id );
            if ( !empty( $lang ) ) {
                $locale = $lang['locale'];
                $humanLanguage = $lang['display_name'];
            }
            $language = strtolower( "$locale ($humanLanguage)" );


            $prompt = apply_filters( 'qcld_prompt_translate_text', "Translate the text into {$language}, preserving the tone, mood, and nuance, while staying as true as possible to the original meaning. Provide only the translated text, without any additional content.\n\n", $post_id );


            $qcld_prompt_grammar_title = $prompt . $text;

            $results  = apply_filters('qcld_seohelp_ai_content_settings_processing_data_function', $qcld_prompt_grammar_title );

            $results_data = '';
            
        
        }

        wp_send_json([ 'status'=> 'success', 'keywords'=> $results, 'results'=> $results ]);
        wp_die();

    }
}

// qcld_seohelp_grammer_checker

add_action( 'wp_ajax_qcld_seohelp_grammer_checker', 'qcld_seohelp_grammer_checker_callback' );
add_action( 'wp_ajax_nopriv_qcld_seohelp_grammer_checker', 'qcld_seohelp_grammer_checker_callback' );

if ( ! function_exists( 'qcld_seohelp_grammer_checker_callback' ) ) {
    function qcld_seohelp_grammer_checker_callback(){

        check_ajax_referer( 'seo-help', 'security');

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( esc_html( 'Unauthorized', 'seo-help' ) );
            wp_die();
        }

        $post_id        = isset($_POST['post_id'])          ? intval(sanitize_text_field(wp_unslash($_POST['post_id']))) : '';

        if(!empty($post_id)){
            $post = get_post( $post_id );
            if ( !$post ) {
                return false;
            }
            $text = apply_filters( 'qcld_pre_post_content', $post->post_content, $post_id );
            $pattern = '/\[mwai_.*?\]/';
            $text = preg_replace( $pattern, '', $text );
         
            $text = apply_filters( 'the_content', $text );
          
            //$text = $this->clean_text( $text );
            $text = html_entity_decode( $text );
            $text = wp_strip_all_tags( $text );
            $text = preg_replace( '/[\r\n]+/', "\n", $text );
            $text = preg_replace( '/\n+/', "\n", $text );
            $text = preg_replace( '/\t+/', "\t", $text );
            $text =  $text . " ";

            //$text = $this->clean_sentences( $text );
            // Step 1: Identify URLs and replace them with a placeholder.
            $urlPattern = '/\bhttps?:\/\/[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/))/';
            preg_match_all($urlPattern, $text, $urls);
            $urlPlaceholders = array();
            foreach ($urls[0] as $index => $url) {
                $placeholder = "{urlPlaceholder" . $index . "}";
                $text = str_replace($url, $placeholder, $text);
                $urlPlaceholders[$placeholder] = $url;
            }
        
            $maxLength = (int)(isset($maxLength) ? $maxLength : 4096);
            $sentences = preg_split('/(?<=[.?!。．！？])\s+/u', $text, -1, PREG_SPLIT_NO_EMPTY);
            $hashes = array();
            $uniqueSentences = array();
            $total = 0;
        
            foreach ( $sentences as $sentence ) {
                $sentence = preg_replace( '/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $sentence );
                $hash = md5( $sentence );
                if ( !in_array( $hash, $hashes ) ) {
                    $length = mb_strlen( $sentence, 'UTF-8' );
                    if ( $total + $length > $maxLength ) {
                        continue;
                    }
                    $hashes[] = $hash;
                    $uniqueSentences[] = $sentence;
                    $total += $length;
                }
            }
        
            $freshText = implode( " ", $uniqueSentences );
        
            // Step 3: Restore URLs in the final text.
            foreach ($urlPlaceholders as $placeholder => $url) {
                $freshText = str_replace($placeholder, $url, $freshText);
            }
        
            $freshText = preg_replace( '/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $freshText );
            $text =  $freshText;

            $text = apply_filters( 'qcld_post_content', $text, $post_id );
            //return $text;

            $prompt = apply_filters( 'qcld_prompt_grammar_checker', "Correct only the grammar, spellings, and punctuations in the following text. Take extra care to make minimal changes to the original text and preserve the tone, mood, and nuance and stay as true as possible to the original meaning. Here is the Text:\n\n", $post_id );

            $qcld_prompt_grammar_title = $prompt . $text;

            $results  = apply_filters('qcld_seohelp_ai_content_settings_processing_data_function', $qcld_prompt_grammar_title );

            $results_data = '';
            
        
        }

        wp_send_json([ 'status'=> 'success', 'keywords'=> $results, 'results'=> $results ]);
        wp_die();

    }
}