<?php 

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

if ( ! function_exists( 'qcld_render_linkbait_seo_tips' ) ) {
	function qcld_render_linkbait_seo_tips() { //Function For Content Writting Tips //

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

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

		$title = isset($_POST["linkbait_seo_id"]) ? trim(sanitize_text_field(wp_unslash($_POST['linkbait_seo_id']))) : '';
		
		?>

		<div id="sm-modal" class="modal">

			<!-- Modal content -->
			<div class="modal-content" style="width: 60%;">
				<span class="close"><?php esc_html_e( "×", 'seo-help' ); ?></span>
				<h3><?php esc_html_e( "SEO Content Writing Tips", 'seo-help' ); ?></h3>
				<hr/>
				<div class="sm_shortcode_list">
					<h2><span style="color:red"><?php esc_html_e( "Coming Soon", 'seo-help' ); ?></span></h2>
				</div>
			</div>

		</div>
		<?php
		wp_die();
	}
}
add_action( 'wp_ajax_qcld_seohelp_seo_tips', 'qcld_render_linkbait_seo_tips');
add_action( 'wp_ajax_nopriv_qcld_seohelp_seo_tips',  'qcld_render_linkbait_seo_tips' );

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

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

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

		$keyword 		= isset($_POST["keyword"]) ? sanitize_text_field(wp_unslash($_POST['keyword'])) : '';
		$toolLanguage 	= isset($_POST["selectedlanguage"]) ? sanitize_text_field(wp_unslash($_POST['selectedlanguage'])) : '';
		$toolCountry 	= isset($_POST["selectedCountry"]) ? sanitize_text_field(wp_unslash($_POST['selectedCountry'])) : '';

		$args = array(
			'user-agent'  => ''
		);
		$srt_engine = 'google';
		$srt_service_option = 'complete';
		$srt_service = 'suggestqueries';
		$srt_browser_option = 'firefox';
		$srt_option = 'search';

		$dataresponse = wp_remote_request( 'http://'.$srt_service.'.'.$srt_engine.'.com/'.$srt_service_option.'/'.$srt_option.'?output='.$srt_browser_option.'&client=psy-ab&gs_rn=64o&hl='.$toolLanguage.'&gl='.$toolCountry.'&q='.urlencode($keyword), $args );
		$data = $dataresponse['body'];	
		
		$responseCode = $dataresponse['response']['code'];
		if (!empty($responseCode) and $responseCode !== 200){
			print_r(wp_json_encode(''));	
			wp_die();
		} 
		
		
		$data = htmlentities($data, ENT_NOQUOTES, "ISO-8859-1");
		
		
		if (($data = json_decode($data, true)) !== null) {
			$keywords = $data[1];
			$keywordsArray = [];
			
			foreach ($keywords as $key => $keywordResults){
				if($key != 0){
					$keywordsArray[$key] = sanitize_text_field($keywordResults[0]);
				}
			}
			$keywords = $keywordsArray;
			
		} else {
			$keywords = '';	
		}
		
		wp_send_json(['status'=> 'success','keywords'=> $keywords]);
		wp_die();

	}
}
add_action( 'wp_ajax_qcldseohelp_keyword_suggestion', 'qcldseohelp_keyword_suggestion');
add_action( 'wp_ajax_nopriv_qcldseohelp_keyword_suggestion',  'qcldseohelp_keyword_suggestion' );

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

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

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

		$keyword 		= isset($_POST["suggesstions"]) ? sanitize_text_field(wp_unslash($_POST["suggesstions"])) : '';
		$OPENAI_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;
		$ppenalty 		= get_option('qcld_seohelp_ai_ppenalty');
		$fpenalty 		= get_option('qcld_seohelp_ai_fpenalty');
		$prompt 		= "Create an outline for an about ". $keyword[0];



            $qcld_ai_settings_open_ai = get_option('qcld_ai_settings_open_ai');

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

                $gemini_api_key     = get_option('qcld_gemini_api_key');
                $gemini_model       = get_option('qcld_gemini_model');
                $gemini_version     = get_option('qcld_gemini_api_version');

                $url = "https://generativelanguage.googleapis.com/{$gemini_version}/models/{$gemini_model}:generateContent?key={$gemini_api_key}";

                $generation_config = array();

                if( null !== get_option('qcld_gemini_ai_temperature') && get_option('qcld_gemini_ai_temperature') != "" ){
                    $generation_config["temperature"] = (float) esc_attr( get_option( 'qcld_gemini_ai_temperature' ) );
                }

                if( null !== get_option('qcld_gemini_ai_top_p') && get_option('qcld_gemini_ai_top_p') != "" ){
                    $generation_config["top_p"] = (float) esc_attr( get_option( 'qcld_gemini_ai_top_p' ) );
                }

                if( null !== get_option('qcld_gemini_ai_top_k') && get_option('qcld_gemini_ai_top_k') != "" ){
                    $generation_config["top_k"] = (float) esc_attr( get_option( 'qcld_gemini_ai_top_k' ) );
                }

                //return $generation_config;

                //Build the input array to feed as Gemini API input
               $request_body = array(
                    "contents" => array(
                        array(
                            "role" => "user",
                            "parts" => array(
                                array(
                                    "text" => $prompt // Assuming $myprompt is defined
                                )
                            )
                        )
                    ),
                    "generation_config" => $generation_config, // Assuming $generation_config is defined
                );

                // Configure the arguments for the wp_remote_post request
                $args = array(
                    'body'    => json_encode( $request_body ), // The data payload encoded as JSON
                    'headers' => array(
                        'Content-Type' => 'application/json',
                        // If your API uses a different auth method (e.g., Bearer token in header), add it here
                        // 'Authorization' => 'Bearer ' . $API_KEY, 
                    ),
                    'method'  => 'POST',
                    'timeout' => 45, // Set a reasonable timeout
                );

                // Execute the request using the WordPress HTTP API
                $response = wp_remote_post( $url, $args );

                // Initialize the result variable
                $result_data = '';

                // Check for a transport error (network issue, cURL failure)
                if ( is_wp_error( $response ) ) {
                    $error_message = $response->get_error_message();
                    error_log( "Gemini API Request Transport Error: $error_message" ); 
                    
                    return esc_html( 'A network error occurred: ' . $error_message );
                    wp_die();
                } else {
                    // Request was made successfully. Decode the JSON body.
                    $body = wp_remote_retrieve_body( $response );
                    $returnedData = json_decode( $body );

                    // Check the decoded response for API-specific errors (e.g., invalid input, rate limits)
                    if ( isset( $returnedData->error ) && !empty( $returnedData->error ) ) {
                        $api_error_message = isset( $returnedData->error->message ) ? $returnedData->error->message : 'Unknown API Error';
                        
                        // Output the error message safely
                        return esc_html( $api_error_message );
                        wp_die();
                    }
                    
                    // Extract the final text result if everything is successful
                    $result_data = isset( $returnedData->candidates[0]->content->parts[0]->text ) ? $returnedData->candidates[0]->content->parts[0]->text : '';
                    
                }
            
                $complete = preg_replace('/[\*]+/', '', $result_data);
                

            }else if( !empty($qcld_ai_settings_open_ai) && $qcld_ai_settings_open_ai == 'openrouter' ) {
                $openrouter_api_key = get_option('qcld_seohelp_openrouter_api_key');
                $openrouter_model = get_option('qcld_seohelp_openrouter_model', 'google/gemini-2.5-flash');
                $openrouter_temperature = get_option('qcld_seohelp_openrouter_temperature') ? get_option('qcld_seohelp_openrouter_temperature') : 1;

                $post_fields = array(
                    "model"         => $openrouter_model,
                    "messages"      => array(
                        array(
                            "role" => "user",
                            "content" => $prompt 
                        )
                    ),
                    "temperature"   => ( float )$openrouter_temperature
                );

                $url = 'https://openrouter.ai/api/v1/chat/completions';
                $args = array(
                    'method'  => 'POST', 
                    'headers' => array(
                        'Content-Type'  => 'application/json',
                        'Authorization' => 'Bearer ' . $openrouter_api_key,
                        'HTTP-Referer'  => home_url(),
                        'X-Title'       => get_bloginfo('name'),
                    ),
                    'body'    => json_encode($post_fields),
                    'timeout' => 45 // Adjust timeout as needed
                );

                $response = wp_remote_post( $url, $args );

                if ( is_wp_error( $response ) ) {
                    $error_message = $response->get_error_message();
                    
                    printf(
                        esc_html( 'Something went wrong: %s', 'seo-help' ),
                        esc_html( $error_message )
                    );
                } else {
                    $body = wp_remote_retrieve_body( $response );
                    $data = json_decode( $body );
                }

                $complete = isset($data->choices[0]->message->content) ? esc_attr($data->choices[0]->message->content) : '';

            }else if( $ai_engines == 'gpt-3.5-turbo' || $ai_engines == 'gpt-4' || $ai_engines == 'gpt-4o' || $ai_engines == 'gpt-4o-mini' || $ai_engines == 'gpt-4.1' || $ai_engines == 'gpt-4.1-mini' || $ai_engines == 'gpt-4.1-nano' || ( substr( $ai_engines, 0, 5 ) == 'gpt-4' ) || ( substr( $ai_engines, 0, 5 ) == 'gpt-5' ) || ( substr( $ai_engines, 0, 5 ) == 'gpt-6' ) || ( substr( $ai_engines, 0, 2 ) == 'o1' ) || ( substr( $ai_engines, 0, 2 ) == 'o3' ) || $ai_engines == 'chatgpt-4o-latest' || $ai_engines == 'gpt-4.5-preview' ){
                $gptkeyword = [];
                $gptkeyword = array(
                    array(
                        "role" => "user",
                        "content" => $prompt 
                    )
                );

                $post_fields = array(
                    "model"         => $ai_engines,
                    "messages"      => $gptkeyword,
                    "temperature"   => ( float )$temperature
                );

                $url = 'https://api.openai.com/v1/chat/completions';
                $args = array(
                    'method'  => 'POST', 
                    'headers' => array(
                        'Content-Type'  => 'application/json',
                        'Authorization' => 'Bearer ' . $OPENAI_API_KEY
                    ),
                    'body'    => json_encode($post_fields),
                    'timeout' => 45 // Adjust timeout as needed
                );

                $response = wp_remote_post( $url, $args );

                if ( is_wp_error( $response ) ) {
                    $error_message = $response->get_error_message();
                    printf(
                        esc_html( 'Something went wrong: %s', 'seo-help' ),
                        esc_html( $error_message )
                    );
                } else {
                    $body = wp_remote_retrieve_body( $response );
                    $data = json_decode( $body );
                }

                $complete = isset($data->choices[0]->message->content) ? esc_attr($data->choices[0]->message->content) : '';

            }else{

                $request_body = [
                    "prompt"     => $prompt,
                    "model"      => $ai_engines,
                    "temperature"=> (float) $temperature,
                    "presence_penalty" => (float) $ppenalty, 
                    "frequency_penalty" => (float) $fpenalty, 
                    "top_p"      => 1,
                    "best_of"    => 1,
                ];

                $url = "https://api.openai.com/v1/completions";
                $args = array(
                    'body'    => json_encode( $request_body ),
                    'headers' => array(
                        'Content-Type'  => 'application/json',
                        'Authorization' => 'Bearer ' . $OPENAI_API_KEY, 
                    ),
                    'method'  => 'POST',
                    'timeout' => 45,
                );

                $response = wp_remote_post( $url, $args );

                $complete = '';

                if ( is_wp_error( $response ) ) {
                    $error_message = $response->get_error_message();
                    error_log( "OpenAI API Request Failed: $error_message" ); 
                    return esc_html( 'An API error occurred. Please try again later.', 'seo-help' );
                    wp_die();
                } else {

                    $body_json = wp_remote_retrieve_body( $response );
                    $api_data  = json_decode( $body_json );

                    if ( isset( $api_data->error ) && !empty( $api_data->error ) ) {
                        $error_message = isset( $api_data->error->message ) ? $api_data->error->message : 'Unknown API Error';
                        return esc_html( $error_message ); 
                        wp_die();
                    }
                    
                    $complete = isset( $api_data->choices[0]->text ) ? $api_data->choices[0]->text : '';
                    
                }

            }

            $result = '';
            if(!empty($complete)){
               $suggesstions = explode("\n", $complete );

                foreach ($suggesstions as $key => $suggesstion) {

                    if( !empty( $suggesstion ) ){

                        $result .= '<div class="toast-container position-relative start-0" width="750"><div class="position-absolute"><div id="toster'.esc_attr($key).'" class="toast" role="alert" aria-live="assertive" aria-atomic="true"><div class="toast-body hide-toast-body" id="toster-data-'.esc_attr($key).'"><ul class="list-group list-group-horizontal"><li class="list-group-item"> <a href="#" class="item-para" data-outline="'.esc_html($suggesstion).'" data-outlineresultid="outline-data-'.esc_attr($key).'">Paragraph</a></li><li class="list-group-item" data-classes="rewrite_content" data-id="rewrite_con'.esc_attr($key).'">Rewrite</li><li data-classes="edit_outline" data-id="outline'.esc_attr($key).'" class="list-group-item">Edit outline</li></ul><button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button></div></div></div></div><div class="accordion-item"><h2 class="accordion-header" id="panelsStayOpen-heading'.esc_attr($key).'"><div class="accordion-button"  data-id="toster'.esc_attr($key).'" data-classes="toster_accordion" data-toster="toster-data-'.esc_attr($key).'" id="outline'.esc_attr($key).'">'.esc_html($suggesstion).'</div></h2><div><textarea id="outline-data-'.esc_attr($key).'" class="result-outline form-control" rows="3" style="display: none"></textarea></div></div>';
                    }
                   
                }

                
                    

            }

            //var_dump( $result );
            //wp_die();

		wp_send_json(['status'=> 'success','results'=> $result]);
		wp_die();
	}			
}
add_action( 'wp_ajax_qcld_seohelp_outline_data', 'qcld_seohelp_outline_data');
add_action( 'wp_ajax_nopriv_qcld_seohelp_outline_data',  'qcld_seohelp_outline_data' );

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

        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"]) 			? sanitize_text_field(wp_unslash($_POST["api_key"])) 			: '';
		$opeai_engines 		= isset($_POST["opeai_engines"]) 	? sanitize_text_field(wp_unslash($_POST["opeai_engines"])) 	: '';
		$manual_models 		= isset($_POST["manual_models"]) 	? sanitize_text_field(wp_unslash($_POST["manual_models"])) 	: '';
		$temperature 		= isset($_POST["temperature"]) 		? sanitize_text_field(wp_unslash($_POST["temperature"])) 		: '';
		$presence_penalty 	= isset($_POST["presence_penalty"]) ? sanitize_text_field(wp_unslash($_POST["presence_penalty"])) : '';
		$frequency_penalty 	= isset($_POST["frequency_penalty"])? sanitize_text_field(wp_unslash($_POST["frequency_penalty"])): '';



		update_option('qcld_seohelp_api_key', $api_key);
		update_option('qcld_seohelp_ai_engines', $opeai_engines);
		update_option('qcld_seohelp_openai_manual_models', $manual_models);
		update_option('qcld_seohelp_ai_temperature', $temperature);
		update_option('qcld_seohelp_ai_ppenalty', $presence_penalty);
		update_option('qcld_seohelp_ai_fpenalty', $frequency_penalty);


        $frequency_penalty  = isset($_POST["frequency_penalty"])? sanitize_text_field(wp_unslash($_POST["frequency_penalty"])): '';
        update_option('qcld_seohelp_ai_fpenalty', $frequency_penalty);


		$qcld_seohelp_api_key = get_option('qcld_seohelp_api_key');

        $ai_settings_open_ai        = isset($_POST["ai_settings_open_ai"]) ? sanitize_text_field(wp_unslash($_POST["ai_settings_open_ai"])) : '';
        update_option('qcld_ai_settings_open_ai', $ai_settings_open_ai );

		$results = esc_html('Data Updated Successfully', 'seo-help');

		wp_send_json(['status'=> 'success','results'=> $results]);
		wp_die();
	}
}
add_action( 'wp_ajax_qcld_seohelp_open_save_settings', 'qcld_seohelp_open_save_settings');
add_action( 'wp_ajax_nopriv_qcld_seohelp_open_save_settings',  'qcld_seohelp_open_save_settings' );

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

        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"]) ? sanitize_text_field(wp_unslash($_POST["api_key"])) : '';

		if (empty($api_key)) {
			wp_send_json(array(
				'status' => 'error',
				'message' => esc_html('API Key cannot be empty.', 'seo-help')
			));
			wp_die();
		}

		$url = "https://api.openai.com/v1/models";

		if (function_exists('curl_init')) {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_TIMEOUT, 30);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				'Authorization: Bearer ' . $api_key,
				'Content-Type: application/json'
			));
			$body = curl_exec($ch);
			$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			curl_close($ch);
			$data = json_decode($body);
		} else {
			$args = array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $api_key,
				),
				'timeout' => 30,
			);
			$response = wp_remote_get($url, $args);
			$http_code = wp_remote_retrieve_response_code($response);
			$body = wp_remote_retrieve_body($response);
			$data = json_decode($body);
		}

		if ($http_code === 200 && isset($data->data) && !empty($data->data)) {
			$models = array();
			$allowed_patterns = array('gpt-5', 'gpt-4o', 'gpt-4', 'gpt-3.5', 'gpt-4.1', 'o1', 'o3');
			foreach ($data->data as $model) {
				$model_id = isset($model->id) ? $model->id : '';
				$matched = false;
				foreach ($allowed_patterns as $pattern) {
					if (strpos($model_id, $pattern) !== false) {
						$matched = true;
						break;
					}
				}
				if ($matched) {
					$exclude_patterns = array('embedding', 'moderation', 'edit', 'similarity', 'whisper', 'tts', 'dall-e');
					$exclude = false;
					foreach ($exclude_patterns as $ex) {
						if (strpos($model_id, $ex) !== false) {
							$exclude = true;
							break;
						}
					}
					if (!$exclude) {
						$models[] = $model_id;
					}
				}
			}
			usort($models, function($a, $b) {
				return strcasecmp($b, $a);
			});

			$manual_models = get_option('qcld_seohelp_openai_manual_models');
			if (!empty($manual_models)) {
				$manual_models_arr = explode(',', $manual_models);
				foreach($manual_models_arr as $manual_model) {
					$m = trim($manual_model);
					if (!empty($m) && !in_array($m, $models)) {
						array_unshift($models, $m);
					}
				}
			}

			wp_send_json(array(
				'status' => 'success',
				'message' => esc_html('Connection Successful! Models updated.', 'seo-help'),
				'models' => $models,
				'selected' => get_option('qcld_seohelp_ai_engines', 'gpt-4o')
			));
		} else {
			$err_msg = esc_html('Connection failed. Please check your API key.', 'seo-help');
			if (isset($data->error->message)) {
				$err_msg = esc_html($data->error->message);
			}
			wp_send_json(array(
				'status' => 'error',
				'message' => $err_msg
			));
		}
		wp_die();
	}
}
add_action( 'wp_ajax_qcld_seohelp_check_openai_connection', 'qcld_seohelp_check_openai_connection');
add_action( 'wp_ajax_nopriv_qcld_seohelp_check_openai_connection', 'qcld_seohelp_check_openai_connection');

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

        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"]) ? sanitize_text_field(wp_unslash($_POST["api_key"])) : '';

		if (empty($api_key)) {
			wp_send_json(array(
				'status' => 'error',
				'message' => esc_html('Gemini API Key cannot be empty.', 'seo-help')
			));
			wp_die();
		}

		$url = "https://generativelanguage.googleapis.com/v1beta/models?key=" . urlencode($api_key);

		if (function_exists('curl_init')) {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_TIMEOUT, 30);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			$body = curl_exec($ch);
			$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			curl_close($ch);
			$data = json_decode($body);
		} else {
			$args = array('timeout' => 30);
			$response = wp_remote_get($url, $args);
			$http_code = wp_remote_retrieve_response_code($response);
			$body = wp_remote_retrieve_body($response);
			$data = json_decode($body);
		}

		if ($http_code === 200 && isset($data->models) && !empty($data->models)) {
			$models = array();
			foreach ($data->models as $model) {
				$is_gen_method = false;
				if (isset($model->supportedGenerationMethods) && is_array($model->supportedGenerationMethods)) {
					if (in_array('generateContent', $model->supportedGenerationMethods)) {
						$is_gen_method = true;
					}
				} else {
					if (strpos($model->name, 'gemini') !== false && strpos($model->name, 'embedding') === false) {
						$is_gen_method = true;
					}
				}
				if ($is_gen_method) {
					$model_name = str_replace("models/", "", $model->name);
					$models[] = array(
						'id' => $model_name,
						'displayName' => isset($model->displayName) ? $model->displayName : $model_name
					);
				}
			}

			// Sort models by displayName alphabetically
			usort($models, function($a, $b) {
				return strcmp($a['displayName'], $b['displayName']);
			});

			$manual_models = get_option('qcld_seohelp_gemini_manual_models');
			if (!empty($manual_models)) {
				$manual_models_arr = explode(',', $manual_models);
				foreach($manual_models_arr as $manual_model) {
					$m = trim($manual_model);
					if (!empty($m)) {
						$exists = false;
						foreach($models as $existing) {
							if ($existing['id'] === $m) {
								$exists = true;
								break;
							}
						}
						if (!$exists) {
							array_unshift($models, array(
								'id' => $m,
								'displayName' => $m
							));
						}
					}
				}
			}

			wp_send_json(array(
				'status' => 'success',
				'message' => esc_html('Connection Successful! Gemini models updated.', 'seo-help'),
				'models' => $models,
				'selected' => get_option('qcld_gemini_model', true)
			));
		} else {
			$err_msg = esc_html('Connection failed. Please check your Gemini API key.', 'seo-help');
			if (isset($data->error->message)) {
				$err_msg = esc_html($data->error->message);
			}
			wp_send_json(array(
				'status' => 'error',
				'message' => $err_msg
			));
		}
		wp_die();
	}
}
add_action( 'wp_ajax_qcld_seohelp_check_gemini_connection', 'qcld_seohelp_check_gemini_connection');
add_action( 'wp_ajax_nopriv_qcld_seohelp_check_gemini_connection', 'qcld_seohelp_check_gemini_connection');

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

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

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

        $qcld_gemini_api_key            = isset($_POST["qcld_gemini_api_key"])          ? sanitize_text_field(wp_unslash($_POST["qcld_gemini_api_key"]))          : '';
        $qcld_gemini_model              = isset($_POST["qcld_gemini_model"])            ? sanitize_text_field(wp_unslash($_POST["qcld_gemini_model"]))            : '';
        $manual_models                  = isset($_POST["manual_models"])                ? sanitize_text_field(wp_unslash($_POST["manual_models"]))                : '';
        $qcld_gemini_api_version        = isset($_POST["qcld_gemini_api_version"])      ? sanitize_text_field(wp_unslash($_POST["qcld_gemini_api_version"]))      : '';
        $qcld_gemini_ai_temperature     = isset($_POST["qcld_gemini_ai_temperature"])   ? sanitize_text_field(wp_unslash($_POST["qcld_gemini_ai_temperature"]))   : '';
        $qcld_gemini_ai_top_p           = isset($_POST["qcld_gemini_ai_top_p"])         ? sanitize_text_field(wp_unslash($_POST["qcld_gemini_ai_top_p"]))         : '';
        $qcld_gemini_ai_top_k           = isset($_POST["qcld_gemini_ai_top_k"])         ? sanitize_text_field(wp_unslash($_POST["qcld_gemini_ai_top_k"]))         : '';

        $qcld_ai_settings_open_ai       = isset($_POST["qcld_ai_settings_open_ai"])     ? sanitize_text_field(wp_unslash($_POST["qcld_ai_settings_open_ai"]))     : '';



        update_option('qcld_gemini_api_key', $qcld_gemini_api_key );
        update_option('qcld_gemini_model', $qcld_gemini_model );
        update_option('qcld_seohelp_gemini_manual_models', $manual_models );
        update_option('qcld_gemini_api_version', $qcld_gemini_api_version );
        update_option('qcld_gemini_ai_temperature', $qcld_gemini_ai_temperature );
        update_option('qcld_gemini_ai_top_p', $qcld_gemini_ai_top_p );
        update_option('qcld_gemini_ai_top_k', $qcld_gemini_ai_top_k );

        update_option('qcld_ai_settings_open_ai', $qcld_ai_settings_open_ai );


        $results = esc_html('Data Updated Successfully', 'seo-help');

        wp_send_json(['status'=> 'success','results'=> $results]);
        wp_die();
    }
}
add_action( 'wp_ajax_qcld_seohelp_gemini_save_settings', 'qcld_seohelp_gemini_save_settings');
add_action( 'wp_ajax_nopriv_qcld_seohelp_gemini_save_settings',  'qcld_seohelp_gemini_save_settings' );

if ( ! function_exists( 'qcld_seohelp_check_openrouter_connection' ) ) {
    function qcld_seohelp_check_openrouter_connection() {
        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']) ? sanitize_text_field($_POST['api_key']) : '';

        if (empty($api_key)) {
            wp_send_json_error('API Key is empty.');
            wp_die();
        }

        $models_url = 'https://openrouter.ai/api/v1/models';
        $args = array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'HTTP-Referer'  => home_url(),
                'X-Title'       => get_bloginfo('name'),
            ),
            'timeout' => 30,
            'sslverify' => false,
        );

        $response = wp_remote_get($models_url, $args);

        if (is_wp_error($response)) {
            wp_send_json_error('Connection Error: ' . $response->get_error_message());
            wp_die();
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (empty($data['data'])) {
            wp_send_json_error('Invalid API Key or no models found.');
            wp_die();
        }

        $transient_models = array();
        foreach ($data['data'] as $model) {
            $transient_models[$model['id']] = $model['name'] ? $model['name'] : $model['id'];
        }

        set_transient('seo_help_openrouter_models_list', $transient_models, DAY_IN_SECONDS);

        $manual_models = get_option('qcld_seohelp_openrouter_manual_models');
        if (!empty($manual_models)) {
            $manual_models_arr = explode(',', $manual_models);
            $prepended_models = array();
            foreach($manual_models_arr as $manual_model) {
                $m = trim($manual_model);
                if (!empty($m) && !array_key_exists($m, $transient_models)) {
                    $prepended_models[$m] = $m;
                }
            }
            $transient_models = array_merge($prepended_models, $transient_models);
        }

        wp_send_json_success(array(
            'message' => 'Connection Successful! Models updated.',
            'models'  => $transient_models
        ));
        wp_die();
    }
}
add_action( 'wp_ajax_qcld_seohelp_check_openrouter_connection', 'qcld_seohelp_check_openrouter_connection');
add_action( 'wp_ajax_nopriv_qcld_seohelp_check_openrouter_connection', 'qcld_seohelp_check_openrouter_connection');

if ( ! function_exists( 'qcld_seohelp_openrouter_save_settings' ) ) {
    function qcld_seohelp_openrouter_save_settings() {
        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["qcld_seohelp_openrouter_api_key"]) ? sanitize_text_field(wp_unslash($_POST["qcld_seohelp_openrouter_api_key"])) : '';
        $model       = isset($_POST["qcld_seohelp_openrouter_model"])   ? sanitize_text_field(wp_unslash($_POST["qcld_seohelp_openrouter_model"]))   : '';
        $manual_models= isset($_POST["manual_models"]) ? sanitize_text_field(wp_unslash($_POST["manual_models"])) : '';
        $temperature = isset($_POST["qcld_seohelp_openrouter_temperature"]) ? sanitize_text_field(wp_unslash($_POST["qcld_seohelp_openrouter_temperature"])) : '';
        $ai_setting  = isset($_POST["qcld_ai_settings_open_ai"]) ? sanitize_text_field(wp_unslash($_POST["qcld_ai_settings_open_ai"])) : '';

        update_option('qcld_seohelp_openrouter_api_key', $api_key);
        update_option('qcld_seohelp_openrouter_model', $model);
        update_option('qcld_seohelp_openrouter_manual_models', $manual_models);
        update_option('qcld_seohelp_openrouter_temperature', $temperature);
        update_option('qcld_ai_settings_open_ai', $ai_setting);

        wp_send_json(['status'=> 'success','results'=> esc_html('Data Updated Successfully', 'seo-help')]);
        wp_die();
    }
}
add_action( 'wp_ajax_qcld_seohelp_openrouter_save_settings', 'qcld_seohelp_openrouter_save_settings');
add_action( 'wp_ajax_nopriv_qcld_seohelp_openrouter_save_settings', 'qcld_seohelp_openrouter_save_settings');

add_action( 'wp_ajax_qcld_seohelp_image_generate', 'qcld_seohelp_image_generate' );
add_action( 'wp_ajax_nopriv_qcld_seohelp_image_generate',  'qcld_seohelp_image_generate' );

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

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

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

        $qcld_seohelp_result = array(
            'status' => 'error',
            'msg'    => 'Something went wrong',
        );

        $OPENAI_API_KEY = get_option('qcld_seohelp_api_key');
        
        $qcld_seohelp_prompt = isset( $_POST['qcld_seohelp_prompt'] ) ? sanitize_text_field( $_POST['qcld_seohelp_prompt'] )              : '';
        $artist                = isset( $_POST['artist'] )                ? sanitize_text_field( $_POST['artist'] )              : 'Painter';
        $art_style             = isset( $_POST['art_style'] )             ? sanitize_text_field( $_POST['art_style'] )           : 'Style';
        $photography_style     = isset( $_POST['photography_style'] )     ? sanitize_text_field( $_POST['photography_style'] )   : 'Photography Style';
        $lighting              = isset( $_POST['lighting'] )              ? sanitize_text_field( $_POST['lighting'] )            : 'Lighting';
        $subject               = isset( $_POST['subject'] )               ? sanitize_text_field( $_POST['subject'] )             : 'Subject';
        $camera_settings       = isset( $_POST['camera_settings'] )       ? sanitize_text_field( $_POST['camera_settings'] )     : 'Camera Settings';
        $composition           = isset( $_POST['composition'] )           ? sanitize_text_field( $_POST['composition'] )         : 'Composition';
        $resolution            = isset( $_POST['resolution'] )            ? sanitize_text_field( $_POST['resolution'] )          : 'Resolution';
        $color                 = isset( $_POST['color'] )                 ? sanitize_text_field( $_POST['color'] )               : 'Color';
        $special_effects       = isset( $_POST['special_effects'] )       ? sanitize_text_field( $_POST['special_effects'] )     : 'Special Effects';
        $qcld_seohelp_img_size              = isset( $_POST['qcld_seohelp_img_size'] )              ? sanitize_text_field( $_POST['qcld_seohelp_img_size'] )            : '1024x1024';
        $qcld_seohelp_num_images            = isset( $_POST['qcld_seohelp_num_images'] )            ? sanitize_text_field( $_POST['qcld_seohelp_num_images'] )          : 1;
        $qcld_seohelp_num_images            = isset( $qcld_seohelp_num_images )                     ? (int) $qcld_seohelp_num_images                                    : 6;
        $step = isset( $_POST['step'] ) && !empty($_POST['step']) ? sanitize_text_field( $_POST['step'] ) : '';

        if(!session_start()){
          session_start();
        }

        if (!empty($qcld_seohelp_prompt)) {
            // Get the prompt from the form
            $prompt         = $qcld_seohelp_prompt;
            $img_size       = $qcld_seohelp_img_size;
            $num_images     = $qcld_seohelp_num_images;
            // convert num_images to an integer
            $num_images     = (int) $num_images;

            if($step == 'process'){

                $prompt_elements = array(
                    'artist'            => $artist,
                    'art_style'         => $art_style,
                    'photography_style' => $photography_style,
                    'composition'       => $composition,
                    'resolution'        => $resolution,
                    'color'             => $color,
                    'special_effects'   => $special_effects,
                    'lighting'          => $lighting,
                    'subject'           => $subject,
                    'camera_settings'   => $camera_settings,
                );

                $result = array();
                foreach($prompt_elements as $key => $value ){
                    if(isset($_POST[$key]) && !empty($_POST[$key])){
                        $result[$key] = sanitize_text_field($_POST[$key]);
                    }
                }

                $prompt_data = '';
                foreach ($prompt_elements as $key => $value) {
                    if ( isset( $_POST[$key] ) && ( $_POST[$key] != "None" ) ) {
                        ///$prompt_data .= $prompt . ". " . $value . ": " . $_POST[$key];
                        $prompt_data .=  $value . ": " . $_POST[$key];
                    }
                }


                if(isset($_SESSION['prompt_data']) && !empty($_SESSION['prompt_data'])){
                    unset($_SESSION['prompt_data']);
                }
                $_SESSION['prompt_data']     = $prompt_data;


                wp_send_json( [ 'status' => 'success', 'oldStep' => $step, 'html' => '' ] );
                wp_die();

            }


            if($step == 'image'){

                $prompt_data       = isset($_SESSION['prompt_data']) ? $_SESSION['prompt_data'] : '';

                $prompt_text = $prompt . ". " . $prompt_data;

                $image_grid   = apply_filters( 'qcld_seohelp_get_prompt_image_url', $prompt, $img_size );

                wp_send_json( [ 'status' => 'success', 'oldStep' => $step, 'html' => $image_grid ] );
                wp_die();

            }

        }
        
        wp_send_json( $qcld_seohelp_result );
    }
}


if(!function_exists('qcld_seohelp_get_prompt_image_url')){
    add_filter('qcld_seohelp_get_prompt_image_url', 'qcld_seohelp_get_prompt_image_url', 10, 2);
    function qcld_seohelp_get_prompt_image_url( $prompt, $img_size ) {


        if( isset( $prompt ) && !empty($prompt) ){
            $provider = get_option('qcld_ai_settings_open_ai');

            //var_dump( $provider );
            //wp_die();

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

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

                $request_body = [
                    "prompt"            => $prompt,
                    "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
                    $image_url = 'data:image/png;base64,' . $base64_image_data;
                } else {
                    // Fallback for older legacy endpoints
                    $image_url = 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');
                if (empty($api_key)) {
                    $blueprint['error'] = 'OpenRouter API key is missing.';
                    return $blueprint;
                }

                // Use a known image generation model on OpenRouter instead of the text model from settings
                $model = 'google/gemini-2.5-flash-image'; 
                
                $image_prompt = "Generate an illustration or image representing the following text: " . $prompt;

                $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)) {
                    $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);

                if (isset($data['choices'][0]['message']['images'][0]['image_url']['url'])) {
                    $image_url = $data['choices'][0]['message']['images'][0]['image_url']['url'];
                } elseif (isset($data['choices'][0]['message']['content'])) {
                    $content = $data['choices'][0]['message']['content'];
                    
                    // Extract the URL from Markdown (can be http/https or a base64 data URI)
                    if (preg_match('/(https?:\/\/[^\s\)]+)/', $content, $matches) && !empty($matches[1])) {
                        $image_url = $matches[1];
                    } elseif (preg_match('/(data:image\/[^"\')\s>]+)/', $content, $matches) && !empty($matches[1])) {
                        $image_url = $matches[1];
                    } else {
                        $blueprint['error'] = 'OpenRouter generated text but no valid image data or URL was found. Raw content: ' . wp_trim_words($content, 30);
                        return $blueprint;
                    }
                } else {
                    $api_err = isset($data['error']['message']) ? $data['error']['message'] : 'Failed to retrieve response from OpenRouter.';
                    $blueprint['error'] = $api_err . ' (HTTP ' . $response_code . ')';
                    return $blueprint;
                }

                


            } elseif ($provider == 'gemini') {
                $api_key = get_option('qcld_gemini_api_key');
                if (empty($api_key)) {
                    $blueprint['error'] = 'Gemini API key is missing.';
                    return $blueprint;
                }

                $request_body = array(
                    "contents" => array(
                        array(
                            "parts" => array(
                                array("text" => $prompt)
                            )
                        )
                    ),
                    "generationConfig" => array(
                        "responseModalities" => array("IMAGE")
                    )
                );
                
                $url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent?key=' . $api_key;

                // Configure the arguments for the wp_remote_post request
                $args = array(
                    'body'    => json_encode( $request_body ), // The data payload encoded as JSON
                    'headers' => array(
                        'Content-Type' => 'application/json',
                    ),
                    'method'  => 'POST',
                    'timeout' => 45, // Set a reasonable timeout
                );

                // 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);

                //return $data;

                if ($response_code !== 200) {
                    $blueprint['error'] = isset($data['error']['message']) ? $data['error']['message'] : 'Failed to retrieve response from Gemini. Response code: ' . $response_code;
                    return $blueprint;
                }

                if (isset($data['candidates'][0]['content']['parts'][0]['inlineData']['data'])) {
                    $base64_image = $data['candidates'][0]['content']['parts'][0]['inlineData']['data'];
                    $image_data = base64_decode($base64_image);
                    if (empty($image_data)) {
                        $blueprint['error'] = 'Decoded Gemini image data is empty.';
                        return $blueprint;
                    }
                } else {
                    $blueprint['error'] = isset($data['error']['message']) ? $data['error']['message'] : 'Failed to retrieve image bytes from Gemini.';
                    return $blueprint;
                }

               

            } else {
                $blueprint['error'] = 'Unsupported AI provider for image generation.';
                return $blueprint;
            }

            

            if(!empty($image_url)){
                if (strpos($image_url, 'data:image') === 0) {
                    $base64_parts = explode(',', $image_url);
                    if (isset($base64_parts[1])) {
                        $image_data = base64_decode(trim($base64_parts[1]));
                    }
                    $image_url = '';
                } else {
                    $img_response = wp_remote_get($image_url, array('timeout' => 60));
                    if (is_wp_error($img_response)) {
                        $blueprint['error'] = 'Failed to download generated image: ' . $img_response->get_error_message() . ' | URL: ' . $image_url;
                        return $blueprint;
                    }

                    $image_data = wp_remote_retrieve_body($img_response);
                    if (empty($image_data)) {
                        $blueprint['error'] = 'Downloaded image data is empty.';
                        return $blueprint;
                    }
                }
            }

            $image_grid = '';
            if( !empty( $image_data )){

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

                $inline_src = 'data:image/jpeg;base64,' . base64_encode($image_data);

                $image_grid .= '<div class="qcld_qcld_seohelp_image-box_wrap generate_image_download"> ';
                $image_grid .= '<img class="qcld_qcld_seohelp_image-list" src="' . ( $inline_src ) . '" alt="' . esc_attr( $uniq_name ) . '">';

                $image_grid .= '<div class="qcld_seohelp_download" data-img="' . ( $inline_src ) . '"><img src="'.esc_url( qcld_seohelp_img_url ).'/download.svg"></div>';
                $image_grid .= '</div>';

            }

            return $image_grid;

        }

    }

}

add_action( 'wp_ajax_qcld_seohelp_image_generate_url_functions', 'qcld_seohelp_image_generate_url_functions' );
add_action( 'wp_ajax_nopriv_qcld_seohelp_image_generate_url_functions',  'qcld_seohelp_image_generate_url_functions' );
if ( ! function_exists( 'qcld_seohelp_image_generate_url_functions' ) ) {
    function qcld_seohelp_image_generate_url_functions () {

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

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

        $qcld_seohelp_result = array(
            'status' => 'error',
            'msg'    => esc_html('Something went wrong'),
        );

        /* Download and upload the chosen image */
        if (isset($_POST['qcld_seohelp_openai_images_upload'])) {
            // "pluggable.php" is required for wp_verify_nonce() and other upload related helpers
            if (!function_exists('wp_verify_nonce'))
                require_once(ABSPATH . 'wp-includes/pluggable.php');

            if(!function_exists('wp_generate_attachment_metadata')){
                include_once( ABSPATH . 'wp-admin/includes/image.php' );
            }
            if(!function_exists('download_url')){
                include_once( ABSPATH . 'wp-admin/includes/file.php' );
            }
            if(!function_exists('media_handle_sideload')){
                include_once( ABSPATH . 'wp-admin/includes/media.php' );
            }

            $post_id                            = isset($_REQUEST['post_id']) ? absint($_REQUEST['post_id']): '';
            $imageurl                           = isset($_POST['image_url']) ? sanitize_text_field(wp_unslash( $_POST['image_url'] )) : '';
            $image_user                         = isset($_POST['image_user']) ? sanitize_text_field(wp_unslash( $_POST['image_user'] )) : '';
            $image_src_page                     = isset($_POST['image_src_page']) ? sanitize_text_field(wp_unslash( $_POST['image_src_page'] )) : '';
            $image_prompt                       = isset($_POST['image_prompt']) ? sanitize_text_field(wp_unslash( $_POST['image_prompt'] )) : 'gpt openai';
            $qcld_seohelp_openai_images_attribution = 'gpt openai';

            if( isset($imageurl) && !empty(sanitize_text_field($imageurl))){

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

                $uniq_name          = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $image_prompt );
                $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));

                //$contents           = file_get_contents( $imageurl );
                $savefile           = fopen($target_file_name, 'w');
                fwrite($savefile, $contents);
                fclose($savefile);
                unset($imageurl);

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

                /* 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 );

                /* 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;
                $image_data['post_excerpt'] = $attachment_caption;
                wp_update_post($image_data);

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

                if(!empty($parsed)){
                    $attach_id = $parsed;
                }

                $qcld_seohelp_result['status']  = 'success';
                $qcld_seohelp_result['html']    = esc_html('Image Successfully Added to  Media Library');


            }

          
        }
            
        wp_send_json( $qcld_seohelp_result );
        wp_die();

    }

}