<?php 


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


    if(isset($_POST['qcld_seohelp_confirmed_cron'])){
        update_option('_qcld_seohelp_crojob_bulk_confirm','true');
    }
    $qcld_seohelp_track_id              = isset($_GET['qcld_seohelp_track']) && !empty($_GET['qcld_seohelp_track']) ? sanitize_text_field(wp_unslash($_GET['qcld_seohelp_track'])) : false;
    $qcld_seohelp_bulk_action           = isset($_GET['qcld_seohelp_action']) && !empty($_GET['qcld_seohelp_action']) ? sanitize_text_field(wp_unslash($_GET['qcld_seohelp_action'])) : false;
    $qcld_seohelp_track                 = false;
    if($qcld_seohelp_track_id){
        $qcld_seohelp_track             = get_post($qcld_seohelp_track_id);
    }
    $qcld_seohelp_cron_job_last_time    = get_option('_qcld_seohelp_crojob_bulk_last_time','');
    $qcld_seohelp_cron_job_confirm      = get_option('_qcld_seohelp_crojob_bulk_confirm','');
    $qcld_seohelp_number_title          = 5;
    $qcld_seohelp_cron_added            = get_option('_qcld_seohelp_cron_added','');


    ?>
    <div class="wrap fs-section">
        <?php $seo_help_url = esc_url(admin_url('admin.php?page=qcld-seo-other-features')); ?>
        <div style="margin: 15px 0 25px 0;">
            <a href="<?php echo esc_url($seo_help_url); ?>" class="button button-secondary">
                <span class="dashicons dashicons-arrow-left-alt"></span>
                <?php esc_html_e('Back to SEO Help Page', 'seo-help'); ?>
            </a>
        </div>
       
        <div id="poststuff">
            

            <div id="qcld_seo-bulk-generator">
                <div class="qcld_seo-row">
                    <div class="qcld_seo-col">
                           
                           
                            <div class="qcld_seohelp_ai_single_contents">

                                <div class="qcld_form_wrap qcld_tab_container">
                                    <div class="qcld_form_body">
             
                                        <div id="qcld_tab_area">
                                          <div class="qcld_tab_content">
                                            <div class="qcld_form_tab_pan qcld_tab_active">

                                                <?php 

                                                $pro_url        = esc_url("https://www.dna88.com/product/seo-help-pro/");

                                                // 1. Correct the translation and escaping syntax using esc_html_e() / __() equivalents
                                                $data_msg = '<div class="qcld_seohelp_msg qcld_error">' . 
                                                    sprintf(
                                                        esc_html('You have already generated 10 Blog Posts. Please upgrade to %s to generate unlimited Blog posts.', 'seo-help'),
                                                        '<a href="' . esc_url( $pro_url ) . '" target="_blank">' . esc_html( 'SEO Help Pro', 'seo-help' ) . '</a>'
                                                    ) . 
                                                '</div>'; 

                                                
                     
                                                if( get_option('update_openai_crawler_alert') == 'on' ){
                                                ?>
                                               
                                                <div class="qcld-seohelp-input_wrap">
                                                    <h3 class="choose_topic_head"><?php esc_html_e('Turbo Content Generator Wizard', 'seo-help'); ?></h3>
                                                    
                                                    <?php //echo $data_msg; 
                                                    // 2. Late escape the output using wp_kses to allow the specific container HTML
                                                    echo wp_kses( $data_msg, array(
                                                        'div' => array(
                                                            'class' => array(),
                                                        ),
                                                        'a'   => array(
                                                            'href'   => array(),
                                                            'target' => array(),
                                                        ),
                                                    ) );

                                                    ?>
                                                </div>  
                                               <?php }else { ?>

                                               
                                                <div class="qcld-seohelp-input_wrap">
                                                    <h3 class="choose_topic_head"><?php esc_html_e('Turbo Content Generator Wizard', 'seo-help'); ?></h3>
                                                    <p><?php esc_html_e('Use this Wizard if you have a brand new website and want to start with some SEO friendly contents quickly until the website is ready to go live with actual contents.', 'seo-help'); ?></p>
                                                    <p><?php esc_html_e('We will use OpenAI to generate SEO friendly contents for your new website.', 'seo-help'); ?></p>
                                                    <p><?php esc_html_e('Make sure that you have added a ', 'seo-help'); ?> <a href="<?php echo esc_url('https://platform.openai.com/account/billing/payment-methods'); ?>" target="_blank"><?php esc_html_e('Credit card', 'seo-help'); ?></a> <?php esc_html_e('to your OpenAI API account.', 'seo-help'); ?></p>
                                                    
                                                </div>  
                                              
                                                <?php 

                                                    $OPENAI_API_KEY = get_option('qcld_seohelp_api_key');
                                                    $newstring      = substr( $OPENAI_API_KEY, -5 );
                                                    $api_key_val    = ( isset( $OPENAI_API_KEY ) && !empty( $OPENAI_API_KEY ) ) ? '***************************'.$newstring : '';

                                                if( empty( $OPENAI_API_KEY ) ) {
                                                ?>
                                                <div class="qcld-seohelp-input">
                                                    <div class="qcld-seohelp-input-field">
                                                        <label for="qcld_seohelp_api_key" class="choose_topic_head"><?php esc_html_e('API key', 'seo-help'); ?></label>
                                                        <input type="text" id="qcld_seohelp_api_key" class="form-control" placeholder="Write API key" value="<?php echo esc_attr($api_key_val); ?>"><br>
                                                    </div>
                                                </div>  
                                                <?php } ?>

                                                <?php } ?>

                                            </div>
                           
                                            <div class="qcld_form_tab_pan"> 
                                                <h3 class="choose_topic_head"><?php esc_html_e('Choose Topic','seo-help') ?></h3>
                                                <div class="qcld_form_tab_topic_wrap">
                                       
                                                    <label class="radio-inline qcld_form_check_label">
                                                        <input id="qcld_seohelp_topic" type="radio" name="qcld_seohelp_topic" checked="checked" value="Stocks" >
                                                        <span><?php esc_html_e('Stocks','seo-help') ?></span> 
                                                    </label>
                                                    <label class="radio-inline qcld_form_check_label">
                                                        <input id="qcld_seohelp_topic" type="radio" name="qcld_seohelp_topic" value="Comics" >
                                                        <span><?php esc_html_e('Comics','seo-help') ?></span> 
                                                    </label>
                                                    <label class="radio-inline qcld_form_check_label">
                                                        <input id="qcld_seohelp_topic" type="radio" name="qcld_seohelp_topic" value="Global News" >
                                                        <span><?php esc_html_e('Global News','seo-help') ?></span> 
                                                    </label>
                                                    <label class="radio-inline qcld_form_check_label">
                                                        <input id="qcld_seohelp_topic" type="radio" name="qcld_seohelp_topic" value="Sports" >
                                                        <span><?php esc_html_e('Sports','seo-help') ?></span> 
                                                    </label>
                                                    <label class="radio-inline qcld_form_check_label">
                                                        <input id="qcld_seohelp_topic" type="radio" name="qcld_seohelp_topic" value="Students Science" >
                                                        <span><?php esc_html_e('Students Science','seo-help') ?></span> 
                                                    </label>
                                                    <label class="radio-inline qcld_form_check_label">
                                                        <input id="qcld_seohelp_topic" type="radio" name="qcld_seohelp_topic" value="Cryptocurrency" >
                                                        <span><?php esc_html_e('Cryptocurrency','seo-help') ?></span> 
                                                    </label>
                                                    <label class="radio-inline qcld_form_check_label">
                                                        <input id="qcld_seohelp_topic" type="radio" name="qcld_seohelp_topic" value="Children Book" >
                                                        <span><?php esc_html_e('Children Book','seo-help') ?></span> 
                                                    </label>
                                                    <label class="radio-inline qcld_form_check_label">
                                                        <input id="qcld_seohelp_topic" type="radio" name="qcld_seohelp_topic" value="Startup" >
                                                        <span><?php esc_html_e('Startup','seo-help') ?></span> 
                                                    </label>
                                                    <label class="radio-inline qcld_form_check_label">
                                                        <input id="qcld_seohelp_topic" type="radio" name="qcld_seohelp_topic" value="Technology" >
                                                        <span><?php esc_html_e('Technology','seo-help') ?></span> 
                                                    </label>
                                                    <label class="radio-inline qcld_form_check_label">
                                                        <input id="qcld_seohelp_topic" type="radio" name="qcld_seohelp_topic" value="Finance" >
                                                        <span><?php esc_html_e('Finance','seo-help') ?></span> 
                                                    </label>
                                                    <label class="radio-inline qcld_form_check_label">
                                                        <input id="qcld_seohelp_topic" type="radio" name="qcld_seohelp_topic" value="English" >
                                                        <span><?php esc_html_e('English','seo-help') ?></span> 
                                                    </label>

                                                </div>

                                            </div>
                                          </div>
                                          <?php if( get_option('update_openai_crawler_alert') !== 'on' ){ ?>
                                          <div class="qcld_form_tab_nav">
                                            <span class="qcld_form_tab_prev qcld_form_tab_hide"><?php esc_html_e('Prev', 'seo-help'); ?></span>
                                            <span class="qcld_form_tab_next"><?php esc_html_e('Next', 'seo-help'); ?></span>
                                            <button class="qcld_form_submit qcld_form_tab_hide"><?php esc_html_e('Generate SEO Friendly Contents', 'seo-help'); ?></button>
                                          </div>
                                            <?php } ?>
                                        </div>
                                                
                                    </div>
                                </div>
                                
                            </div>
                    </div>
                </div>
            </div>



        </div>
    </div>

<?php 

    }
}



if ( ! function_exists( 'qcld_seohelp_content_generate' ) ) {
    add_action('wp_ajax_qcld_seohelp_content_generate', 'qcld_seohelp_content_generate' );
    add_action('wp_ajax_nopriv_qcld_seohelp_content_generate',  'qcld_seohelp_content_generate' );
    function qcld_seohelp_content_generate() { 

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

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

        $api_key    = isset( $_POST['api_key'] ) ? trim(sanitize_text_field(wp_unslash($_POST['api_key']))) : '';
        $title      = isset( $_POST['title'] ) ? trim(sanitize_text_field(wp_unslash($_POST['title']))) : '';
        $topic      = isset( $_POST['topic'] ) ? trim(sanitize_text_field(wp_unslash($_POST['topic']))) : $title;

        set_time_limit(6000);

        $step = isset( $_POST['step'] ) && !empty($_POST['step']) ? sanitize_text_field( $_POST['step'] ) : '';
        $content = isset( $_POST['content'] ) && !empty($_POST['content']) ? sanitize_text_field( $_POST['content'] ) : '';

        $result_data    = '';

        if( !get_option('update_openai_crawler') ) update_option('update_openai_crawler', 0 );
        if( !get_option('update_openai_crawler_alert') ) update_option('update_openai_crawler_alert', 'off' );

        if( get_option('update_openai_crawler_alert') == 'on' ){

            $status         = 'success';
            $pro_url        = esc_url("https://www.dna88.com/product/seo-help-pro/");
            $data_msg       = '<div class="qcld_seohelp_msg qcld_error">'.esc_html('You have already generated 10 Blog Posts. Please upgrade to ', 'seo-help'). '<a href="'. $pro_url .'" target="_blank">'. esc_html( 'SEO Help Pro', 'seo-help' ).'</a>'. esc_html(' to generate unlimited Blog posts', 'seo-help' ).'</div>'; 
            $response = array( 'html' => $data_msg, 'status' => $status );
            echo wp_send_json($response);

        }

        if($topic) {


            if($step == 'process'){

                $status     = 'pending';
                $data_msg   = '<div class="qcld_seohelp_msg">'. esc_html('Process completed. Working on more. Please stand by.', 'seo-help').'</div>';

                $response = array( 'html' => $data_msg, 'oldStep' => $step, 'status' => $status );
                echo wp_send_json($response);
                wp_die();

            }

            if($step == 'content'){

                $meta_topic_prompt = ( isset( $topic ) && !empty( $topic ) ) ? $topic  : $title;

                $meta_desc_prompt_title   = apply_filters( 'qcld_seohelp_get_prompt_title', $meta_topic_prompt, get_option('update_openai_crawler') );

                $meta_desc_prompt = sprintf( "You are a professional Blog article writer for a new website. Your writing style is friendly and informative. Write at least 1000-word SEO-optimized article about the broad topic '%s'. The sub topic can be anything relevant to the broad topic. Begin with a catchy, SEO-optimized level 1 heading (#) that captivates the reader. Follow with SEO optimized introductory paragraphs. Then organize the rest of the article into detailed heading tags (##) and lower-level heading tags (###, ####, etc.). Include detailed paragraphs under each heading and subheading that provide in-depth information about the topic. Use bullet points, unordered lists, bold text, underlined text, code blocks etc to enhance readability and engagement.", $meta_desc_prompt_title );

                $OPENAI_API_KEY = !empty($api_key) ? $api_key : get_option('qcld_seohelp_api_key');
                $ai_engines     = get_option('qcld_seohelp_ai_engines')     ? get_option('qcld_seohelp_ai_engines') : 'gpt-4o';
                $temperature    = get_option('qcld_seohelp_ai_temperature') ? get_option('qcld_seohelp_ai_temperature') : 0.3;
                $ppenalty       = get_option('qcld_seohelp_ai_ppenalty')    ? get_option('qcld_seohelp_ai_ppenalty') : 0;
                $fpenalty       = get_option('qcld_seohelp_ai_fpenalty')    ? get_option('qcld_seohelp_ai_fpenalty') : 0;


                $qcld_ai_settings_open_ai = get_option('qcld_ai_settings_open_ai');

                $complete  = apply_filters('qcld_seohelp_ai_content_settings_processing_data_function', $meta_desc_prompt );

                $result_data   = !empty( $complete ) ? trim( $complete ) : '';
                
                $Parsedown = new Parsedown();
                        
                $result_data = !empty( $result_data ) ? $Parsedown->text( $result_data ) : $result_data;


                $post_id   = isset( $postId ) ? absint( $postId ): '';

                if ( !empty($qcld_ai_settings_open_ai) && $qcld_ai_settings_open_ai == 'gemini' ) {

                    // Create post object $topic
                    $my_post = array(
                      'post_title'      => wp_strip_all_tags( $meta_desc_prompt_title ),
                      'post_content'    => $result_data,
                      'post_status'     => 'publish',
                      'post_author'     => get_current_user_id()
                    );

                    // Insert the post into the database
                    $postId     = wp_insert_post( $my_post );
                    $post_id    = isset( $postId ) ? absint( $postId ): '';

                }else {

                    // Create post object
                    $my_post = array(
                      'post_title'      => wp_strip_all_tags( $meta_desc_prompt_title ),
                      'post_content'    => $result_data,
                      'post_status'     => 'publish',
                      'post_author'     => get_current_user_id()
                    );

                    // Insert the post into the database
                    $postId = wp_insert_post( $my_post );

                    $post_id          = isset( $postId ) ? absint( $postId ): '';

                    // Get the prompt from the form
                    $img_size       = '1024x1024';
                    $imageurl  = apply_filters('qcld_seohelp_ai_article_heading_img_url',  $meta_desc_prompt_title, $img_size );

                    $qcld_seohelp_openai_images_attribution = $meta_desc_prompt_title;

                    if( !empty( $imageurl ) ){

                        $array              = explode('/', getimagesize($imageurl)['mime']);
                        $imagetype          = end($array);

                        $uniq_name          = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $meta_desc_prompt_title );
                        $uniq_name          = str_replace( ' ', '-',  $uniq_name );
                        $uniq_name          = strtolower( $uniq_name );
                        $uniq_name          = preg_replace('/[^a-zA-Z0-9_ -]/s', '',$uniq_name);
                        $filename           = $uniq_name .'-'. uniqid() . '.' . $imagetype;

                        $uploaddir          = wp_upload_dir();
                        $target_file_name   = $uploaddir['path'] . '/' . $filename;

                        $arrContextOptions=array(
                            "ssl"   =>array(
                                "verify_peer"       => false,
                                "verify_peer_name"  => false,
                            ),
                        );  
                  
                        $contents = file_get_contents($imageurl, false, stream_context_create($arrContextOptions));

                        $savefile           = fopen($target_file_name, 'w');
                        fwrite($savefile, $contents);
                        fclose($savefile);

                        /* add the image title */
                        $image_title        = ucwords( $uniq_name );

                        $qcld_seohelp_openai_images_attribution = $meta_desc_prompt_title;

                        /* add the caption */
                        $attachment_caption = '';
                        if (! isset($qcld_seohelp_openai_images_attribution['attribution']) | isset($qcld_seohelp_openai_images_attribution['attribution']) == 'true')
                            $attachment_caption = esc_attr( $image_title );

                        unset($imageurl);

                        /* insert the attachment */
                        $wp_filetype = wp_check_filetype(basename($target_file_name), null);
                        $attachment  = array(
                            'guid'              => $uploaddir['url'] . '/' . basename($target_file_name),
                            'post_mime_type'    => $wp_filetype['type'],
                            'post_title'        => $image_title,
                            'post_status'       => 'inherit'
                        );

                        $attach_id   = wp_insert_attachment($attachment, $target_file_name, $post_id);
                        if ($attach_id == 0)
                            die('Error: File attachment error');

                        $attach_data = wp_generate_attachment_metadata($attach_id, $target_file_name);
                        $result      = wp_update_attachment_metadata($attach_id, $attach_data);

                        $image_data                 = array();
                        $image_data['ID']           = $attach_id;
                        wp_update_post($image_data);

                        $size           = 'large';
                        $attachment_id  = $attach_id;

                        set_post_thumbnail( $post_id, $attach_id );
                    }


                }

                add_post_meta( $post_id, 'qcld_openai_post', 1 );
                update_option('update_openai_crawler', get_option('update_openai_crawler') + 1 );
                
                $status = 'pending';
                $data_msg   = '<div class="qcld_seohelp_msg">'. get_option('update_openai_crawler') . esc_html(' Blog Posts Created. Working on more. Please stand by.', 'seo-help').'</div>';


                if( get_option('update_openai_crawler') > 9 ){

                    update_option('update_openai_crawler_alert', 'on');

                    $status         = 'success';
                    $data_msg       = '<div class="qcld_seohelp_msg">'.esc_html('We have generated 10 Blog Posts!', 'seo-help').'</div>';

                }
                
                $response = array( 'html' => $data_msg, 'oldStep' => $step, 'status' => $status );
                echo wp_send_json($response);
                wp_die();

            }


        }

        add_post_meta( $post_id, 'qcld_openai_post', 1 );
        update_option('update_openai_crawler', get_option('update_openai_crawler') + 1 );
        
        $status = 'pending';
        $data_msg   = '<div class="qcld_seohelp_msg">'. get_option('update_openai_crawler') . esc_html(' Blog Posts Created. Working on more. Please stand by.', 'seo-help').'</div>';



        if( get_option('update_openai_crawler') > 9 ){

            update_option('update_openai_crawler_alert', 'on');

            $status         = 'success';
            $data_msg       = '<div class="qcld_seohelp_msg">'.esc_html('We have generated 10 Blog Posts!', 'seo-help').'</div>';

        }
        
        $response = array( 'html' => $data_msg, 'status' => $status );
        echo wp_send_json($response);

        // echo wp_send_json($data);
        wp_die();
    }
}



if(!function_exists('qcld_seohelp_get_prompt_title')){
    add_filter('qcld_seohelp_get_prompt_title', 'qcld_seohelp_get_prompt_title', 10, 2);
    function qcld_seohelp_get_prompt_title( $title, $length ) {

        if( isset( $title ) && $title == 'Stocks' ){

            $qcld_title_array_value = array( 
                                    "Understanding stock markets", 
                                    "Fundamental analysis of Stocks", 
                                    "Common stocks vs. preferred stocks", 
                                    "Buy and hold Stocks", 
                                    "Diversification of Stocks", 
                                    "Exchange-Traded Funds (ETFs)", 
                                    "Historical stock market crashes", 
                                    "Securities and Exchange Commission (SEC)", 
                                    "Individual Retirement Accounts (IRAs)", 
                                    "International stock exchanges", 
                                    "Investor psychology", 
                                    "Financial news outlets for stocks",
                                    "ESG criteria (Environmental, Social, Governance) for stocks", 
                                    "Stock options", 
                                    "Online brokerage platforms" 
                                );

            
            $title = ( isset( $qcld_title_array_value[$length] ) && !empty( $qcld_title_array_value[$length] ) ) ? $qcld_title_array_value[$length] : $title;

            return $title;

        }else if( isset( $title ) && $title == 'Comics' ){

            $qcld_title_array_value = array( 
                                    "Comic Book History", 
                                    "Comic Book Genres", 
                                    "Iconic superheroes (e.g., Superman, Spider-Man, Batman)", 
                                    "Antiheroes (e.g., Wolverine, Deadpool)", 
                                    "Graphic Novels", 
                                    "Pioneers in the Comic industry", 
                                    "Marvel Comics", 
                                    "DC Comics", 
                                    "Comic Book Crossovers", 
                                    "Comic Book Adaptations", 
                                    "Fandom and conventions for comic", 
                                    "Diversity in Comics",
                                    "Japanese manga", 
                                    "Stock options", 
                                    "Comic book conventions" 
                                );

            
            $title = ( isset( $qcld_title_array_value[$length] ) && !empty( $qcld_title_array_value[$length] ) ) ? $qcld_title_array_value[$length] : $title;

            return $title;

        }else if( isset( $title ) && $title == 'Global News' ){

            $qcld_title_array_value = array( 
                                    "Geopolitical Events", 
                                    "International conflicts and crises", 
                                    "Diplomatic relations between countries", 
                                    "Peace negotiations and treaties", 
                                    "Regions of ongoing conflict (e.g., Middle East, Ukraine)", 
                                    "Political instability (e.g., Venezuela, Hong Kong)", 
                                    "International Organizations", 
                                    "United Nations (UN)", 
                                    "World Health Organization (WHO)", 
                                    "International Monetary Fund (IMF)", 
                                    "Global stock markets", 
                                    "Trade agreements and disputes",
                                    "Currency exchange rates", 
                                    "Climate and Environmental Issues", 
                                    "Climate change and global warming",
                                    "Natural disasters and their impact",
                                    "Environmental policy and agreements",
                                    "Elections and political transitions",
                                    "International leaders and their policies",
                                    "Political movements and activism",
                                    "Human Rights and Social Issues",
                                    "Human rights violations",
                                    "Social justice movements",
                                    "Refugee and migration crises",
                                );

            
            $title = ( isset( $qcld_title_array_value[$length] ) && !empty( $qcld_title_array_value[$length] ) ) ? $qcld_title_array_value[$length] : $title;

            return $title;

        }else if( isset( $title ) && $title == 'Sports' ){

            $qcld_title_array_value = array( 
                                    "Sports by Type", 
                                    "Olympic Games", 
                                    "Major sporting events (e.g., Super Bowl, World Cup)", 
                                    "Sports and Health", 
                                    "Sports injuries and prevention", 
                                    "Sports Training and Techniques", 
                                    "Sports History", 
                                    "Sports Culture", 
                                    "Sports and Media", 
                                    "Sports Business and Economics", 
                                    "Sports organizations (e.g., FIFA, IOC)", 
                                    "Youth sports leagues and programs",
                                    "Sports and Social Issues", 
                                    "Sports Technology", 
                                    "Competitive video gaming",
                                    "Sports tourism destinations",
                                    "Sports and Politics"
                                );

            
            $title = ( isset( $qcld_title_array_value[$length] ) && !empty( $qcld_title_array_value[$length] ) ) ? $qcld_title_array_value[$length] : $title;

            return $title;

        }else if( isset( $title ) && $title == 'Students Science' ){

            $qcld_title_array_value = array( 
                                    "Elementary school science", 
                                    "College and university science", 
                                    "Science, Technology, Engineering, and Mathematics (STEM) programs", 
                                    "Ideas for science fair projects", 
                                    "Involving students in citizen science projects", 
                                    "Environmental monitoring and data collection", 
                                    "School science clubs", 
                                    "Extracurricular science organizations", 
                                    "National and international science competitions", 
                                    "Simple and fun science experiments", 
                                    "Hands-on science activities for students", 
                                    "Science demonstrations and shows",
                                    "Science outreach programs", 
                                    "Engaging students in science communication", 
                                    "Internships and research opportunities", 
                                    "Tools for data analysis and visualization", 
                                    "Online learning in science", 
                                    "Student involvement in environmental projects", 
                                    "Student interest in space exploration",
                                    "Astronomy clubs and activities" 
                                );

            
            $title = ( isset( $qcld_title_array_value[$length] ) && !empty( $qcld_title_array_value[$length] ) ) ? $qcld_title_array_value[$length] : $title;

            return $title;

        }else if( isset( $title ) && $title == 'Cryptocurrency' ){

            $qcld_title_array_value = array( 
                                    "Blockchain Technology", 
                                    "Popular Cryptocurrencies", 
                                    "Cryptocurrency Exchanges", 
                                    "Cryptocurrency Wallets", 
                                    "Cryptocurrency Investment", 
                                    "Cryptocurrency ICO", 
                                    "Blockchain Development", 
                                    "Legal status of cryptocurrencies in different countries", 
                                    "Cryptocurrency and the Economy", 
                                    "Cryptocurrency theft and hacking incidents", 
                                    "Privacy Coins and Anonymity", 
                                    "Blockchain Scalability",
                                    "Cryptocurrency Use Cases", 
                                    "Crypto Mining"
                                );

            
            $title = ( isset( $qcld_title_array_value[$length] ) && !empty( $qcld_title_array_value[$length] ) ) ? $qcld_title_array_value[$length] : $title;

            return $title;

        }else if( isset( $title ) && $title == 'Children Book' ){

            $qcld_title_array_value = array( 
                                    "Children Picture Books", 
                                    "Children Book Genres", 
                                    "Early Reader Books", 
                                    "Coming-of-age novels", 
                                    "Young Adult (YA) Novels", 
                                    "Diverse and Inclusive Children's Books", 
                                    "Classic Children's Literature", 
                                    "Non-Fiction Children's Books", 
                                    "Children Book Illustrators and Artists", 
                                    "Award-Winning Children's Books", 
                                    "Interactive and Pop-up Books", 
                                    "Encouraging children to read",
                                    "Children's books adapted into movies or TV shows", 
                                    "Using children's books in the classroom",
                                    "Interactive eBooks for kids",
                                    "Digital storytelling and augmented reality books"
                                );

            
            $title = ( isset( $qcld_title_array_value[$length] ) && !empty( $qcld_title_array_value[$length] ) ) ? $qcld_title_array_value[$length] : $title;

            return $title;

        }else if( isset( $title ) && $title == 'Startup' ){

            $qcld_title_array_value = array( 
                                    "Startup Business Idea Generation", 
                                    "Startup Market Research and Validation", 
                                    "Startup  Business Models", 
                                    "Startup Funding", 
                                    "Startup Business Planning", 
                                    "Writing a Startup  business plan", 
                                    "Startup Legal and Regulatory Considerations", 
                                    "Startup Product Development", 
                                    "Startup Marketing and Branding", 
                                    "Startup Sales and Customer Acquisition", 
                                    "Startup Scaling and Growth", 
                                    "Startup Culture and Team Building",
                                    "Startup Failure and Pivot", 
                                    "Social Entrepreneurship and Impact Startups",
                                    "Startup Ecosystems and Hubs",
                                    "Startup Exit Strategies"
                                );

            
            $title = ( isset( $qcld_title_array_value[$length] ) && !empty( $qcld_title_array_value[$length] ) ) ? $qcld_title_array_value[$length] : $title;

            return $title;

        }else if( isset( $title ) && $title == 'Technology' ){


            $qcld_title_array_value = array( 
                                    "Emerging Technologies", 
                                    "Cybersecurity", 
                                    "Information Technology", 
                                    "Software Development", 
                                    "Hardware and Devices", 
                                    "Artificial Intelligence and Machine Learning", 
                                    "Robotics and Automation", 
                                    "Virtual Reality (VR) and Augmented Reality (AR)", 
                                    "Big Data and Data Analytics", 
                                    "E-commerce and Online Business", 
                                    "Internet and Web Technologies", 
                                    "Green Technology and Sustainability",
                                    "Space Technology", 
                                    "Healthcare Technology",
                                    "Educational Technology (EdTech)",
                                    "Tech Policy and Ethics"
                                );

            
            $title = ( isset( $qcld_title_array_value[$length] ) && !empty( $qcld_title_array_value[$length] ) ) ? $qcld_title_array_value[$length] : $title;

            return $title;

        }else if( isset( $title ) && $title == 'Finance' ){


            $qcld_title_array_value = array( 
                                    "Personal Finance", 
                                    "Investments", 
                                    "Financial Markets", 
                                    "Banking and Financial Services", 
                                    "Corporate Finance", 
                                    "Financial Planning and Advising", 
                                    "Financial Risk Management", 
                                    "Financial Literacy", 
                                    "Financial Economic Concepts", 
                                    "Financial Regulation and Compliance", 
                                    "Financial Investment Strategies", 
                                    "Real Estate and Property Finance",
                                    "International Finance", 
                                    "Financial Technology (Fintech)",
                                    "Sustainable Finance",
                                    "Investor psychology and biases"
                                );

            
            $title = ( isset( $qcld_title_array_value[$length] ) && !empty( $qcld_title_array_value[$length] ) ) ? $qcld_title_array_value[$length] : $title;

            return $title;

        }else if( isset( $title ) && $title == 'English' ){

            $qcld_title_array_value = array( 
                                    "English Language Skills", 
                                    "English Grammar and Syntax", 
                                    "English Language Proficiency Levels", 
                                    "English Language Courses", 
                                    "English Language Teaching", 
                                    "English Accent Reduction and Pronunciation", 
                                    "English Idioms and Expressions", 
                                    "English Literature", 
                                    "Business English", 
                                    "Cultural immersion and language acquisition", 
                                    "English Language Learning Strategies", 
                                    "Multilingualism",
                                    "Language Assessment and Proficiency Testing", 
                                    "English Learning Resources",
                                    "English Language Challenges"
                                );

            
            $title = ( isset( $qcld_title_array_value[$length] ) && !empty( $qcld_title_array_value[$length] ) ) ? $qcld_title_array_value[$length] : $title;

            return $title;

        }

        return $title;

    }

}


add_filter('qcld_seohelp_ai_article_heading_img_url', 'qcld_seohelp_ai_article_heading_img_url_callback', 10, 2 );
if ( ! function_exists( 'qcld_seohelp_ai_article_heading_img_url_callback' ) ) {
    function qcld_seohelp_ai_article_heading_img_url_callback( $qcld_article_text, $img_size ){

        $provider = get_option('qcld_ai_settings_open_ai');
        $imgresult = '';

        if ($provider == 'openai' || empty($provider)) {
            
                
            $api_key = get_option('qcld_seohelp_api_key');

            if (empty($api_key)) {
                $blueprint['error'] = 'OpenAI API key is missing.';
                return $blueprint;
            }

            $request_body = [
                "prompt"            => $qcld_article_text,
                "model"             => 'gpt-image-1',
                "n"                 => 1,
                "size"              => '1024x1024',
                "quality"           => 'medium' // Note: GPT Image accepts "low", "medium", or "high" instead of "hd"
            ];
            $url = "https://api.openai.com/v1/images/generations";

            // Configure the arguments for the wp_remote_post request
            $args = array(
                'body'    => json_encode( $request_body ),
                'headers' => array(
                    'Content-Type'  => 'application/json',
                    'Authorization' => 'Bearer ' . $api_key, 
                ),
                'method'  => 'POST',
                'timeout' => 60,
            );

            // Execute the request using the WordPress HTTP API
            $response = wp_remote_post( $url, $args );
            
            if (is_wp_error($response)) {
                $blueprint['error'] = $response->get_error_message();
                return $blueprint;
            }

            $response_code  = wp_remote_retrieve_response_code($response);
            $response_body  = wp_remote_retrieve_body($response);
            $data           = json_decode($response_body, true);


            // Fix 2: Handle OpenAI API Specific errors (e.g., bad API key, invalid size)
            if ( $response_code !== 200 ) {
                if ( isset( $data['error']['message'] ) ) {
                    $blueprint['error'] = 'OpenAI Error: ' . $data['error']['message'];
                } else {
                    $blueprint['error'] = 'API Request failed with status code: ' . $response_code;
                }
                return $blueprint;
            }

            // Fix 3: Handle native gpt-image base64 output
            if ( isset( $data['data'][0]['b64_json'] ) ) {
                $base64_image_data = $data['data'][0]['b64_json'];
                
                // Reconstruct a functional inline image URI for testing
                $imgresult = 'data:image/png;base64,' . $base64_image_data;
            } else {
                // Fallback for older legacy endpoints
                $imgresult = isset( $data['data'][0]['url'] ) ? $data['data'][0]['url'] : "not found";
                $api_error = isset($data['error']['message']) ? $data['error']['message'] : '';
                if (empty($api_error)) {
                    $api_error = 'HTTP ' . $response_code . ': ' . wp_trim_words($response_body, 30);
                }
                $blueprint['error'] = 'Failed to retrieve image URL from OpenAI. Details: ' . $api_error;
                return $blueprint;
            }
        } elseif ($provider == 'openrouter') {
            $api_key = get_option('qcld_seohelp_openrouter_api_key');
            $model = 'google/gemini-2.5-flash-image'; 
            $image_prompt = "Generate an illustration or image representing the following text: " . $qcld_article_text;
            $body = array(
                'model' => $model,
                'messages' => array(
                    array('role' => 'user', 'content' => $image_prompt)
                ),
                'modalities' => array('image')
            );
            $response = wp_remote_post('https://openrouter.ai/api/v1/chat/completions', array(
                'headers'   => array(
                    'Authorization' => 'Bearer ' . $api_key, 
                    'Content-Type' => 'application/json', 
                    'HTTP-Referer' => home_url(), 
                    'X-Title' => 'Simple Link Directory'
                ),
                'body'      => json_encode($body),
                'timeout'   => 60
            ));
            if (!is_wp_error($response)) {
                $response_body = wp_remote_retrieve_body($response);
                $data = json_decode($response_body, true);
                if (isset($data['choices'][0]['message']['images'][0]['image_url']['url'])) {
                    $imgresult = $data['choices'][0]['message']['images'][0]['image_url']['url'];
                } elseif (isset($data['choices'][0]['message']['content'])) {
                    $content = $data['choices'][0]['message']['content'];
                    if (preg_match('/(https?:\/\/[^\s\)]+)/', $content, $matches) && !empty($matches[1])) {
                        $imgresult = $matches[1];
                    } elseif (preg_match('/(data:image\/[^"\')\s>]+)/', $content, $matches) && !empty($matches[1])) {
                        $imgresult = $matches[1];
                    }
                }
            }
        } elseif ($provider == 'gemini') {
            $api_key = get_option('qcld_gemini_api_key');
            $request_body = array(
                "contents" => array(
                    array(
                        "parts" => array(
                            array("text" => $qcld_article_text)
                        )
                    )
                ),
                "generationConfig" => array(
                    "responseModalities" => array("IMAGE")
                )
            );
            $url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent?key=' . $api_key;
            $args = array(
                'body'    => json_encode( $request_body ),
                'headers' => array('Content-Type' => 'application/json'),
                'method'  => 'POST',
                'timeout' => 45,
            );
            $response = wp_remote_post( $url, $args );
            if (!is_wp_error($response)) {
                $response_code = wp_remote_retrieve_response_code($response);
                if ($response_code === 200) {
                    $response_body = wp_remote_retrieve_body($response);
                    $data = json_decode($response_body, true);
                    if (isset($data['candidates'][0]['content']['parts'][0]['inlineData']['data'])) {
                        $base64_image = $data['candidates'][0]['content']['parts'][0]['inlineData']['data'];
                        $imgresult = 'data:image/jpeg;base64,' . $base64_image;
                    }
                }
            }
        }

        
        if( !empty($imgresult) ) {
            $image_data = '';
            $imagetype  = 'jpeg';

            if (strpos($imgresult, 'data:image') === 0) {
                $base64_parts = explode(',', $imgresult);
                if (isset($base64_parts[1])) {
                    $image_data = base64_decode(trim($base64_parts[1]));
                }
                if (preg_match('/data:image\/([a-zA-Z0-9]+);/', $imgresult, $matches)) {
                    $imagetype = $matches[1];
                }
            } else {
                $img_response = wp_remote_get($imgresult, array('timeout' => 60));
                if (!is_wp_error($img_response)) {
                    $image_data = wp_remote_retrieve_body($img_response);
                    $content_type = wp_remote_retrieve_header($img_response, 'content-type');
                    if (!empty($content_type)) {
                        $array = explode('/', $content_type);
                        if (isset($array[1])) {
                            $imagetype = $array[1];
                        }
                    } else {
                        $img_info = @getimagesize($imgresult);
                        if ($img_info && isset($img_info['mime'])) {
                            $array = explode('/', $img_info['mime']);
                            $imagetype = end($array);
                        }
                    }
                }
            }

            if (!empty($image_data)) {
                $uniq_name          = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $qcld_article_text );
                $uniq_name          = str_replace( ' ', '-',  $uniq_name );
                $uniq_name          = strtolower( $uniq_name );
                $uniq_name          = preg_replace('/[^a-zA-Z0-9_ -]/s', '',$uniq_name);
                $filename           = $uniq_name .'-'. uniqid() . '.' . $imagetype;

                $uploaddir          = wp_upload_dir();
                $target_file_name   = $uploaddir['path'] . '/' . $filename;

                $savefile = fopen($target_file_name, 'w');
                fwrite($savefile, $image_data);
                fclose($savefile);

                $image_title   = ucwords( str_replace('-', ' ', $uniq_name) );

                $attachment_caption = esc_attr( $image_title );

                $wp_filetype = wp_check_filetype(basename($target_file_name), null);
                $attachment  = array(
                    'guid'              => $uploaddir['url'] . '/' . basename($target_file_name),
                    'post_mime_type'    => $wp_filetype['type'],
                    'post_title'        => $image_title,
                    'post_status'       => 'inherit'
                );
                $post_id     = isset($_REQUEST['post_id']) ? absint($_REQUEST['post_id']): '';
                $attach_id   = wp_insert_attachment($attachment, $target_file_name, $post_id);
                
                if ($attach_id != 0) {
                    if(!function_exists('wp_generate_attachment_metadata')){
                        require_once( ABSPATH . 'wp-admin/includes/image.php' );
                    }
                    $attach_data = wp_generate_attachment_metadata($attach_id, $target_file_name);
                    wp_update_attachment_metadata($attach_id, $attach_data);

                    $image_data_post                 = array();
                    $image_data_post['ID']           = $attach_id;
                    $image_data_post['post_excerpt'] = $attachment_caption;
                    wp_update_post($image_data_post);

                    $parsed = wp_get_attachment_image_src( $attach_id, 'full' )[0];

                    if(!empty($parsed)){
                        $attach_id = $parsed;
                    }
                    
                    $imgresult = "\n"."<img src='" . $attach_id . "' alt='" . $qcld_article_text . "' />"."\n";
                } else {
                    $imgresult = '';
                }
            } else {
                $imgresult = '';
            }
        } else {
            $imgresult = '';
        }

        return $imgresult;
        
    }
}
