<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

if ( ! class_exists( 'SftcyWordaiAjaxhandler' ) ) {
class SftcyWordaiAjaxhandler {	
	private static $initiated             	  = false;		
	public static $output					  = [];	
				
	public function __construct() {
		if ( ! self::$initiated ) {
			self::initiate_hooks();
		}								
	}
	
	private static function initiate_hooks() {		
		  // Enqueue scripts
		  add_action('admin_enqueue_scripts', array( __CLASS__, 'admin_required_scripts') );	
		  
			/**
			 * Disable output buffering early for streaming AJAX requests
			 * ------------------------------------------------------------
			 * Prevents WordPress / PHP from delaying streamed chunks.
			 */
			add_action( 'admin_init', function() {
				if ( isset( $_REQUEST['action'] ) && in_array( $_REQUEST['action'], [
					'sc_wordai_write_suggest_titles',
					'sc_wordai_write_content',
					'sc_wordai_write_excerpt',
					'sc_wordai_write_tags',
					'sc_wordai_write_seo_titles',
					'sc_wordai_write_seo_meta_description',
					'sc_wordai_write_seo_meta_focus_keyword',
					'sc_wordai_write_image_alt_text',
				], true ) ) {
					// End any active output buffer
					while ( ob_get_level() > 0 ) {
						@ob_end_clean();
					}

					// Disable implicit flush delay
					@ini_set( 'output_buffering', 'off' );
					@ini_set( 'zlib.output_compression', 0 );
					@ini_set( 'implicit_flush', 1 );
					ob_implicit_flush( true );
				}
			});
		  
		  // Settings Pages
		  add_action('wp_ajax_sc_wordai_api_test', [ __CLASS__, 'sc_wordai_api_test' ] );			  
		  add_action('wp_ajax_sc_wordai_ai_provider_save', [ __CLASS__, 'sc_wordai_ai_provider_save' ] );	
		  add_action('wp_ajax_wordai_api_key_show', [ __CLASS__, 'wordai_api_key_show' ] );	
		  add_action('wp_ajax_wordai_openai_api_key_data_save', [ __CLASS__, 'wordai_openai_api_key_data_save' ] );	

		  add_action('wp_ajax_sc_wordai_openai_apisettings_data', [ __CLASS__, 'sc_wordai_openai_apisettings_data' ] );			  		  
		  add_action('wp_ajax_sc_wordai_openai_apisettings_reset_data', [ __CLASS__, 'sc_wordai_openai_apisettings_reset_data' ] );	

		  add_action('wp_ajax_sc_wordai_openai_content_settings_data', [ __CLASS__, 'sc_wordai_openai_content_settings_data' ] );	 
		  add_action('wp_ajax_sc_wordai_openai_content_settings_reset_data', [ __CLASS__, 'sc_wordai_openai_content_settings_reset_data' ] );	 

		  add_action('wp_ajax_sc_wordai_openai_image_settings_data', [ __CLASS__, 'sc_wordai_openai_image_settings_data' ] );	
		  add_action('wp_ajax_sc_wordai_openai_image_settings_reset_data', [ __CLASS__, 'sc_wordai_openai_image_settings_reset_data' ] );	
		  add_action('wp_ajax_sc_wordai_get_provider_runtime_settings', [ __CLASS__, 'sc_wordai_get_provider_runtime_settings'] );
		  add_action('wp_ajax_sc_wordai_submit_support_request', [ __CLASS__, 'sc_wordai_submit_support_request' ] );
		  add_action('wp_ajax_sc_wordai_reply_support_request', [ __CLASS__, 'sc_wordai_reply_support_request' ] );
		

		  // Content Writing
		  add_action( 'wp_ajax_sc_wordai_write_titles', [ __CLASS__, 'sc_wordai_write_titles'] );		  						  
		  add_action( 'wp_ajax_sc_wordai_write_suggest_titles', [ __CLASS__, 'sc_wordai_write_suggest_titles'] );				  				  		  		  
		  add_action( 'wp_ajax_sc_wordai_update_suggest_title', [ __CLASS__, 'sc_wordai_update_suggest_title'] );			  				  		 				 
		  add_action( 'wp_ajax_sc_wordai_write_content', [ __CLASS__, 'sc_wordai_write_content'] );
		  add_action( 'wp_ajax_sc_wordai_write_excerpt', [ __CLASS__, 'sc_wordai_write_excerpt'] );
		  add_action( 'wp_ajax_sc_wordai_write_tags', [ __CLASS__, 'sc_wordai_write_tags'] ); 		  
		  add_action( 'wp_ajax_sc_wordai_save_tags', [ __CLASS__, 'sc_wordai_save_tags' ] );		  
		  add_action( 'wp_ajax_sc_wordai_write_seo_titles', [ __CLASS__, 'sc_wordai_write_seo_titles'] );		  				
		  add_action( 'wp_ajax_sc_wordai_write_seo_meta_description', [ __CLASS__, 'sc_wordai_write_seo_meta_description'] );	
		  add_action( 'wp_ajax_sc_wordai_write_seo_meta_focus_keyword', [ __CLASS__, 'sc_wordai_write_seo_meta_focus_keyword'] );	
		  add_action( 'wp_ajax_sc_wordai_write_image_alt_text', [ __CLASS__, 'sc_wordai_write_image_alt_text'] );
		  		  		  		  
		  					  
		  add_action( 'wp_ajax_sc_wordai_generate_image', [ __CLASS__, 'sc_wordai_generate_image'] );
		  add_action( 'wp_ajax_sc_wordai_upload_image_to_wp_media', [ __CLASS__, 'sc_wordai_upload_image_to_wp_media'] );		
		  add_action( 'wp_ajax_sc_wordai_set_featured_image', [ __CLASS__, 'sc_wordai_set_featured_image'] );
		  add_action( 'wp_ajax_sc_wordai_apply_image_alt_text', [ __CLASS__, 'sc_wordai_apply_image_alt_text'] );
		  add_action( 'wp_ajax_sc_wordai_suggested_title_number_save', [ __CLASS__, 'sc_wordai_suggested_title_number_save'] );		 		  		
		  add_filter( 'plupload_default_settings', array( __CLASS__, 'sc_wordai_image_upload_mime_type_issue'), 10 , 1 ); 		 		  
		 		    		
		  self::$initiated = true;
	}	
		
	/**
	 * Enqueue Scripts
	 * @since 1.0.0 
	 */
	public static function admin_required_scripts( $page_name_hook ) {				
		// get current admin screen
		global $pagenow;
		$screen 		= get_current_screen();
		if ( ! $screen ) {
			return;
		}
		// Loaded only on Plugin required admin pages
		$allowed_pages	=	[
			'toplevel_page_word-ai-topmenu',
			'wordai_page_sc-wordai-content-settings',
			'wordai_page_sc-wordai-image-settings',
			'wordai_page_sc-wordai-ai-agent-settings',
			'wordai_page_sc-wordai-support',
			'wordai_page_wordai-get-pro',
		];
		$screen_id              = isset( $screen->id ) ? $screen->id : '';
		$screen_base            = isset( $screen->base ) ? $screen->base : '';
		$current_post_type      = isset( $screen->post_type ) ? $screen->post_type : '';
		$is_plugin_page         = in_array( $screen_id, $allowed_pages, true );
		$is_supported_post_type = in_array( $current_post_type, array( 'post', 'page', 'product' ), true ) && in_array( $screen_base, array( 'post', 'edit' ), true );

		if ( $is_plugin_page || $is_supported_post_type ) {
				$is_support_page       = 'wordai_page_sc-wordai-support' === $screen_id;
				$is_ai_agent_page      = 'wordai_page_sc-wordai-ai-agent-settings' === $screen_id;
				$is_get_pro_page       = 'wordai_page_wordai-get-pro' === $screen_id;
				$is_generation_context = $is_supported_post_type;
				$is_settings_context   = $is_plugin_page && ! $is_support_page && ! $is_ai_agent_page && ! $is_get_pro_page;
			
				// Core deps
				if ( $is_ai_agent_page ) {
					wp_enqueue_style( 'wp-color-picker' );
					wp_enqueue_script( 'wp-color-picker' );
				}
				wp_enqueue_script( 'jquery-ui-core' );			
				
				wp_enqueue_style(
					'sftcy-wordai-google-fonts',
					'https://fonts.googleapis.com/css2?family=Poppins:wght@700;800&display=swap',
					array(),
					null
				);
				$sftcy_wordai_admin_style_path    = SFTCY_WORDAI_PLUGIN_DIR . 'admin/css/sc-wordai-misc-styles.css';
				$sftcy_wordai_admin_style_version = file_exists( $sftcy_wordai_admin_style_path ) ? (string) filemtime( $sftcy_wordai_admin_style_path ) : SFTCY_WORDAI_VERSION;
				wp_enqueue_style('sftcy-wordai-style', plugins_url( '../admin/css/sc-wordai-misc-styles.css', __FILE__ ) , array( 'sftcy-wordai-google-fonts' ), $sftcy_wordai_admin_style_version, 'all' );		
		        wp_enqueue_style('sftcy-wordai-jquery-ui-style', plugins_url('../admin/css/jquery-ui.css', __FILE__ ) , array(), SFTCY_WORDAI_VERSION, 'all' );
				wp_enqueue_style('sftcy-wordai-fontawesome', plugins_url('../admin/css/fontawesome6-all.min.css', __FILE__ ) , array(), SFTCY_WORDAI_VERSION, 'all' );	
				// AI Agent settings Page styles
				if ( $is_ai_agent_page ) {
					$sftcy_wordai_agent_admin_style_path    = SFTCY_WORDAI_PLUGIN_DIR . 'admin/css/wordai-agent-admin.css';
					$sftcy_wordai_agent_admin_style_version = file_exists( $sftcy_wordai_agent_admin_style_path ) ? (string) filemtime( $sftcy_wordai_agent_admin_style_path ) : SFTCY_WORDAI_VERSION;
					wp_enqueue_style('sftcy-wordai-agent-admin',plugins_url( '../admin/css/wordai-agent-admin.css', __FILE__ ),	[],	$sftcy_wordai_agent_admin_style_version, 'all');
				}
				if ( 'wordai_page_wordai-get-pro' === $screen->id ) {
					wp_enqueue_style( 'wordai-free-admin-style', plugins_url( '../admin/css/wordai-free-admin.css', __FILE__ ), array( 'sftcy-wordai-style' ), SFTCY_WORDAI_VERSION, 'all' );
				}

		
				if ( ! $is_support_page ) {
					$sftcy_wordai_misc_script_path    = SFTCY_WORDAI_PLUGIN_DIR . 'admin/js/sc-wordai-misc-script.js';
					$sftcy_wordai_misc_script_version = file_exists( $sftcy_wordai_misc_script_path ) ? (string) filemtime( $sftcy_wordai_misc_script_path ) : SFTCY_WORDAI_VERSION;
					wp_enqueue_script('sftcy-wordai-misc-script', plugins_url( '../admin/js/sc-wordai-misc-script.js', __FILE__ ) , array('jquery', 'jquery-ui-dialog', 'jquery-ui-core' ), $sftcy_wordai_misc_script_version, true);
				}
				if ( $is_plugin_page || $is_generation_context ) {
					$sftcy_wordai_provider_dialog_path    = SFTCY_WORDAI_PLUGIN_DIR . 'admin/js/sc-wordai-provider-dialog.js';
					$sftcy_wordai_provider_dialog_version = file_exists( $sftcy_wordai_provider_dialog_path ) ? (string) filemtime( $sftcy_wordai_provider_dialog_path ) : SFTCY_WORDAI_VERSION;
					wp_enqueue_script('sftcy-wordai-provider-dialog', plugins_url( '../admin/js/sc-wordai-provider-dialog.js', __FILE__ ), array('jquery', 'jquery-ui-dialog', 'jquery-ui-core'), $sftcy_wordai_provider_dialog_version, true);
					$sftcy_wordai_provider_script_path    = SFTCY_WORDAI_PLUGIN_DIR . 'admin/js/sc-wordai-google-gemini.js';
					$sftcy_wordai_provider_script_version = file_exists( $sftcy_wordai_provider_script_path ) ? (string) filemtime( $sftcy_wordai_provider_script_path ) : SFTCY_WORDAI_VERSION;
					wp_enqueue_script('sftcy-wordai-google-gemini', plugins_url( '../admin/js/sc-wordai-google-gemini.js', __FILE__ ) , array('jquery', 'jquery-ui-dialog', 'jquery-ui-core', 'sftcy-wordai-provider-dialog' ), $sftcy_wordai_provider_script_version, true);
				}
				if ( $is_generation_context ) {
					$sftcy_wordai_content_generate_script_path    = SFTCY_WORDAI_PLUGIN_DIR . 'admin/js/sc-wordai-content-generate-script.js';
					$sftcy_wordai_content_generate_script_version = file_exists( $sftcy_wordai_content_generate_script_path ) ? (string) filemtime( $sftcy_wordai_content_generate_script_path ) : SFTCY_WORDAI_VERSION;
					wp_enqueue_script('sftcy-wordai-content-generate-script', plugins_url( '../admin/js/sc-wordai-content-generate-script.js', __FILE__ ) , array('jquery', 'jquery-ui-dialog', 'jquery-ui-core' ), $sftcy_wordai_content_generate_script_version, true);
				}
				// wp_enqueue_script('sftcy-wordai-seo-metabox-script', plugins_url( '../admin/js/sc-wordai-seo-metabox.js', __FILE__ ) , array('jquery', 'jquery-ui-dialog', 'jquery-ui-core' ), SFTCY_WORDAI_VERSION, true);						        				
				if ( $is_support_page || $is_generation_context ) {
					$sftcy_wordai_admin_view_script_path    = SFTCY_WORDAI_PLUGIN_DIR . 'admin/js/wordai-admin-view-script.js';
					$sftcy_wordai_admin_view_script_version = file_exists( $sftcy_wordai_admin_view_script_path ) ? (string) filemtime( $sftcy_wordai_admin_view_script_path ) : SFTCY_WORDAI_VERSION;
					$admin_view_script_deps                 = $is_generation_context ? array( 'jquery', 'sftcy-wordai-misc-script', 'sftcy-wordai-content-generate-script' ) : array( 'jquery', 'jquery-ui-dialog', 'jquery-ui-core' );
					wp_enqueue_script('sftcy-wordai-admin-view-script', plugins_url( '../admin/js/wordai-admin-view-script.js', __FILE__ ), $admin_view_script_deps, $sftcy_wordai_admin_view_script_version, true);
				}
				// AI Agent Indexing settings Tab Page JS 
				if ( $is_ai_agent_page ) {
					wp_enqueue_script('sc-wordai-ai-agent-settings', plugins_url( '../admin/js/sc-wordai-ai-agent-settings.js', __FILE__ ),	[ 'jquery' ], SFTCY_WORDAI_VERSION, true );
				}
				// AI Agent Chat settings Tab Page JS
				if ( $is_ai_agent_page ) {
					wp_enqueue_script('sc-wordai-ai-chat-settings', plugins_url( '../admin/js/sc-wordai-ai-chat-settings.js', __FILE__ ), ['jquery','wp-color-picker'], SFTCY_WORDAI_VERSION, true );
				}


				
				// Nonce
		        $nonce = wp_create_nonce( 'scwordai_wpnonce' );

				// AI Provider
				$provider = SftcyWordaiBase::sc_wordai_get_current_ai_provider();

				//Detect current post ID dynamically
				$current_post_id = 0;
				if ( isset( $_GET['post'] ) ) {
					$current_post_id = absint( $_GET['post'] );
				} elseif ( isset( $_POST['post_ID'] ) ) {
					$current_post_id = absint( $_POST['post_ID'] );
				}				

				$data  = array(
						'adminajax_url'                  => admin_url('admin-ajax.php'),
						'nonce'                          => $nonce, 
						'current_screenid'               => $screen->id,
						'current_posttype'               => $screen->post_type,
						'current_pagenow'                => $pagenow,		
						'post_id'          				 => $current_post_id,	
						'base_url' 						 => home_url(),  // Proper WP base URL with trailing slash
						'active_provider'                => $provider,
						'provider_labels'                => array_map(
							static function( $meta ) {
								return $meta['label'] ?? '';
							},
							SftcyWordaiBase::sc_wordai_get_ai_providers()
						),
						'wordai_provider_settings'       => [ 
																'provider' => $provider, 
															],						
					
						'copy_title'         			 => __( 'Copy Title', 'wordai-pro'),
						'copy_seo_title'         		 => __( 'Copy SEO Title', 'wordai-pro'),
						'insert_title'          		 => __( 'Insert Title', 'wordai-pro'),
						'insert_seo_title'          	 => __( 'Insert SEO Title', 'wordai-pro'),
						'copy_content'         			 => __( 'Copy Content', 'wordai-pro'),
						'copy_meta_description'          => __( 'Copy Meta Description', 'wordai-pro'),
						'copy_meta_focus_keyword'        => __( 'Copy Meta Focus Keyword', 'wordai-pro'),
					    'copy_excerpt'         			 => __( 'Copy Excerpt', 'wordai-pro'),
					    'copy_tags'         			 => __( 'Copy Tags', 'wordai-pro'),
					    'insert_content'				 => __( 'Insert Content', 'wordai-pro'),
						'insert_meta_description'		 => __( 'Insert Meta Description', 'wordai-pro'),
						'insert_meta_focus_keyword'		 => __( 'Insert Meta Focus Keywords', 'wordai-pro'),
					    'insert_excerpt'				 => __( 'Insert Excerpt', 'wordai-pro'),
					    'insert_tags'				 	 => __( 'Insert Tags', 'wordai-pro'),
					    'copied'                		 => __( 'Copied', 'wordai-pro'),
					    'inserted'                		 => __( 'Inserted', 'wordai-pro'), 
					
					    'write_ur_prompt'               => __( 'Please write your prompt!', 'wordai-pro'),					 					
					    'generated_title_success'		=> __( 'Generated Title(s) Successfully!', 'wordai-pro'), 
						'generated_seo_title_success'	=> __( 'Generated SEO Title Successfully!', 'wordai-pro'), 
						'generated_seo_meta_des_success'=> __( 'Generated SEO Meta Description Successfully!', 'wordai-pro'), 
						'generated_seo_meta_focus_keyword_success'=> __( 'Generated SEO Meta Fcous Keyword Successfully!', 'wordai-pro'), 
						'generated_seo_meta_tags_success'=> __( 'Generated SEO Meta Tags Successfully!', 'wordai-pro'), 
						'removed_seo_meta_tags_success'  => __( 'Removed SEO Meta Tags Successfully!', 'wordai-pro'), 
						
					    'generated_content_success'		=> __( 'Generated Content Successfully!', 'wordai-pro'), 
					    'generated_excerpt_success'		=> __( 'Generated Excerpt Successfully!', 'wordai-pro'), 
					    'generated_tags_success'		=> __( 'Generated Tags Successfully!', 'wordai-pro'), 
					    'check_ur_generate_options'     => __( 'Check any option [ Title / Content / Images ] To Generate!', 'wordai-pro'), 
					
					    'something_went_wrong'			   => __( 'Something went wrong!','wordai-pro'),
					    'something_went_wrong_title'	   => __( 'Title Generation: Something went wrong!','wordai-pro'),
						'something_went_wrong_seo_title'   => __( 'SEO Title Generation: Something went wrong!','wordai-pro'),
						'something_went_wrong_seo_meta_des'=> __( 'SEO Meta Description Generation: Something went wrong!','wordai-pro'),
						'something_went_wrong_seo_meta_focus_keyword'=> __( 'SEO Meta Focus Keyword	Generation: Something went wrong!','wordai-pro'),
						'something_went_wrong_seo_meta_tags'=> __( 'SEO Meta Tags: Add / Remove: Something went wrong!','wordai-pro'),
					    'something_went_wrong_content'	   => __( 'Content Generation: Something went wrong!','wordai-pro'),
					    'something_went_wrong_images'	   => __( 'Image(s) Generation: Something went wrong!','wordai-pro'),
					    'something_went_wrong_images_save' => __( 'Image(s) Save: Something went wrong!','wordai-pro'),
					    'suggest_titles_btn_text'		   => __( 'Suggest Title(s)','wordai-pro'),
					    'cancel_btn_text'				   => __( 'Cancel','wordai-pro'), 
					
					    'updated_title_success'			=> __( 'Updated Title Successfully!','wordai-pro'),
					    'updated_title_not_selected'	=> __( 'Please select the Title first!','wordai-pro'),
					    'generated_image_success'		=> __( 'Generated Image(s) Successfully!','wordai-pro'),	
					    'images_saved_to_gallery'		=> __( 'Image(s) saved to Gallery Successfully!','wordai-pro'),
					    
					    'saved_apisetting_success'		=> __( 'Saved OpenAI API settings successfully!','wordai-pro'),
					    'saved_apikey_success'		    => __( 'Saved OpenAI API Key successfully!','wordai-pro'),
					    'nothing_changes'				=> __( 'Nothing changes!','wordai-pro'),
					    'failed_to_save'				=> __( 'Failed to save, try again!','wordai-pro'),
					
					    'saved_content_setting_success'	=> __( 'Saved OpenAI content settings successfully!','wordai-pro'),
					    'saved_image_setting_success'	=> __( 'Saved OpenAI image settings successfully!','wordai-pro'), 	
					
					    'popup_dialog_suggest_title'	=> __( 'WordAI Suggest Titles','wordai-pro'), 
					    'metabox_popup_dialog_title'	=> __( 'WordAI - AI Content Generator','wordai-pro'), 

						'google_gemini_free_tier_error' => __('Google Gemini free plan does not support this generation feature. Please upgrade your Google API plan or switch AI provider.','wordai-pro'),
						'support_sending_request'      => __( 'Sending support request...', 'wordai-pro' ),
						'support_request_failed'       => __( 'Support request could not be sent right now.', 'wordai-pro' ),
						'support_choose_channel'       => __( 'Select at least one support delivery channel before sending the request.', 'wordai-pro' ),
						'support_office_status_url'    => class_exists( 'SftcyWordaiSupport' ) ? SftcyWordaiSupport::get_support_office_status_endpoint() : trailingslashit( SFTCY_SOFTCOY_API_BASE ) . 'support/tickets/status',
						'support_softcoy_icon_url'     => 'https://www.softcoy.com/brand-assets/logos/softcoy-mark.png',
						'support_wordai_icon_url'      => 'https://softcoy.com/brand-assets/logos/wordai-pro.svg',
						
					
					    
					    //'sc_wordai_icon'				=> '<span class="sc-wordai-icon dashicons dashicons-welcome-write-blog"></span>',	
					    'sc_wordai_icon'				=> '<span class="sc-wordai-metabox-popup-window-title-icon"></span>',	
					    'wordai_success_icon'           => '<i class="fa-regular fa-circle-check"></i>',
					    'wordai_info_icon'              => '<i class="fa-solid fa-circle-info"></i>',
					    'wordai_error_icon'             => '<i class="fa-regular fa-circle-xmark"></i>',

						'openai_icon_url'               => plugin_dir_url(__DIR__) . 'admin/css/images/openai-logo.svg',
						'gemini_icon_url'               => plugin_dir_url(__DIR__) . 'admin/css/images/gemini-logo.svg',
					    
						'lazy_loadimage'    			=> ''
					);
				
				// Localize script				
				if ( wp_script_is( 'sftcy-wordai-misc-script', 'enqueued' ) ) {
					wp_localize_script( 'sftcy-wordai-misc-script', 'sftcy_wordai_metabox_script_obj', $data );
				}
				if ( wp_script_is( 'sftcy-wordai-content-generate-script', 'enqueued' ) ) {
					wp_localize_script( 'sftcy-wordai-content-generate-script', 'sftcy_wordai_content_generate_script_obj', $data );
				}
				if ( wp_script_is( 'sftcy-wordai-admin-view-script', 'enqueued' ) ) {
					wp_localize_script( 'sftcy-wordai-admin-view-script', 'sftcy_wordai_admin_view_script_obj', $data );
				}
				if ( wp_script_is( 'sc-wordai-ai-agent-settings', 'enqueued' ) ) {
					wp_localize_script( 'sc-wordai-ai-agent-settings', 'scwordai_agent', $data );
				}
				if ( wp_script_is( 'sc-wordai-ai-chat-settings', 'enqueued' ) ) {
					wp_localize_script( 'sc-wordai-ai-chat-settings', 'scwordai_agent_chat', $data );
				}
				if ( wp_script_is( 'sftcy-wordai-google-gemini', 'enqueued' ) ) {
					wp_localize_script( 'sftcy-wordai-google-gemini', 'sftcy_wordai_metabox_script_obj', $data );
					wp_localize_script( 'sftcy-wordai-google-gemini', 'sftcy_wordai_google_gemini', $data );
				}
		}
	}
				
	/**
	 * API test
	 */
	public static function sc_wordai_api_test() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );
		// echo 'Hello';
		// var_dump( SftcyWordaiOpenai::get_list_models() );		
		$response	=	 SftcyWordaiOpenai::create_content();
		var_dump( $response["choices"][0]["text"] );
		var_dump( $response );		
		// $response	=	 SftcyWordaiOpenai::create_image();		
	    // var_dump( $response );
		// var_dump( $response['data'][0] );		
		// foreach ( $response['data'] as $image ) {
		//	 var_dump( $image['url'] );
		// }
		wp_die();
	}

	/**
	 * Submit a support request from the Support admin page.
	 *
	 * @return void
	 */
	public static function sc_wordai_submit_support_request() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );
		self::$output = array();

		if ( ! current_user_can( 'manage_options' ) ) {
			self::$output['status']  = 'fail';
			self::$output['message'] = __( 'You do not have permission to send support requests.', 'wordai-pro' );
			echo wp_json_encode( self::$output );
			wp_die();
		}

		$request_data = array(
			'sender_email'        => isset( $_POST['sender_email'] ) ? sanitize_email( wp_unslash( $_POST['sender_email'] ) ) : '',
			'subject'             => isset( $_POST['subject'] ) ? sanitize_text_field( wp_unslash( $_POST['subject'] ) ) : '',
			'issue_type'          => isset( $_POST['issue_type'] ) ? sanitize_key( wp_unslash( $_POST['issue_type'] ) ) : 'general',
			'message'             => isset( $_POST['message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['message'] ) ) : '',
			'include_diagnostics' => isset( $_POST['include_diagnostics'] ) && 'yes' === sanitize_text_field( wp_unslash( $_POST['include_diagnostics'] ) ) ? 'yes' : 'no',
			'delivery_channels'   => isset( $_POST['delivery_channels'] ) && is_array( $_POST['delivery_channels'] )
				? array_map(
					static function( $channel ) {
						return sanitize_key( wp_unslash( $channel ) );
					},
					$_POST['delivery_channels']
				)
				: array(),
		);

		$attachment_result = SftcyWordaiSupport::handle_support_request_attachments( $_FILES['support_attachments'] ?? array() );
		if ( isset( $attachment_result['status'] ) && 'fail' === $attachment_result['status'] ) {
			self::$output['status']  = 'fail';
			self::$output['message'] = $attachment_result['message'] ?? __( 'Support attachment could not be uploaded.', 'wordai-pro' );
			echo wp_json_encode( self::$output );
			wp_die();
		}

		$request_data['attachments'] = $attachment_result['attachments'] ?? array();

		$result = SftcyWordaiSupport::create_support_request( $request_data );

		self::$output['status']      = $result['status'] ?? 'fail';
		self::$output['message']     = $result['message'] ?? __( 'Support request could not be sent.', 'wordai-pro' );
		self::$output['ticket_uuid'] = $result['ticket_uuid'] ?? '';
		self::$output['delivery_results'] = $result['delivery_results'] ?? array();
		self::$output['overall_status'] = $result['overall_status'] ?? 'received';

		echo wp_json_encode( self::$output );
		wp_die();
	}

	public static function sc_wordai_reply_support_request() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );
		self::$output = array();

		if ( ! current_user_can( 'manage_options' ) ) {
			self::$output['status']  = 'fail';
			self::$output['message'] = __( 'You do not have permission to reply to support requests.', 'wordai-pro' );
			echo wp_json_encode( self::$output );
			wp_die();
		}

		$ticket_uuid   = isset( $_POST['ticket_uuid'] ) ? sanitize_text_field( wp_unslash( $_POST['ticket_uuid'] ) ) : '';
		$sender_email  = isset( $_POST['sender_email'] ) ? sanitize_email( wp_unslash( $_POST['sender_email'] ) ) : '';
		$reply_message = isset( $_POST['reply_message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['reply_message'] ) ) : '';

		$result = SftcyWordaiSupport::reply_to_support_request( $ticket_uuid, $reply_message, $sender_email );

		self::$output['status']           = $result['status'] ?? 'fail';
		self::$output['message']          = $result['message'] ?? __( 'Reply could not be sent.', 'wordai-pro' );
		self::$output['ticket_uuid']      = $result['ticket_uuid'] ?? $ticket_uuid;
		self::$output['delivery_results'] = $result['delivery_results'] ?? array();
		self::$output['overall_status']   = $result['overall_status'] ?? 'received';

		echo wp_json_encode( self::$output );
		wp_die();
	}
	
	/**
	 * Add Tags
	 * return - Json
	 */
	public static function sc_wordai_save_tags() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );		
		self::$output				= [];		
		$tags_name_comma_separated	= isset( $_POST['params']['tags'] )? sanitize_text_field( $_POST['params']['tags'] ) : '';	
		$post_id					= isset( $_POST['params']['postID'] )? sanitize_text_field( $_POST['params']['postID'] ) : 0;			
		$update_tags_ids			= wp_set_post_tags( $post_id, $tags_name_comma_separated );		
		if ( $update_tags_ids ) {
			self::$output['status']	= 'success';
			self::$output['postID']	= $post_id;
			self::$output['tags']	= $tags_name_comma_separated;
			self::$output['tagIDs']	= $update_tags_ids;
		}
		else {
			self::$output['status']	= 'fail';
			self::$output['postID']	= $post_id;
		}
		echo wp_json_encode( self::$output );		
        wp_die();								
	}
	
	

	/**
	 * Ajax Request
	 * Save how many suggested titles to generate.
	 */
	// public static function sc_wordai_suggested_title_number_save() {
	// 	check_ajax_referer( 'scwordai_wpnonce', 'security' );

	// 	self::$output = [];
	// 	$params = [];
	// 	$params['wordai-suggested-title-number'] =
	// 		isset($_POST['suggestedTitle'])
	// 			? sanitize_text_field($_POST['suggestedTitle'])
	// 			: 2;

	// 	$current_options = get_option('sftcy-wordai-openai-content-settings-data');
	// 	$updated_options = $current_options
	// 		? array_merge(maybe_unserialize($current_options), $params)
	// 		: $params;

	// 	$updated = update_option(
	// 		'sftcy-wordai-openai-content-settings-data',
	// 		maybe_serialize($updated_options)
	// 	);

	// 	// ✅ Immediately clear WP option cache
	// 	wp_cache_delete('sftcy-wordai-openai-content-settings-data', 'options');

	// 	if ($updated) {
	// 		self::$output['status']  = 'success';
	// 		self::$output['comment'] = 'Updated Suggest Title Number To: ' . $params['wordai-suggested-title-number'];
	// 	} else {
	// 		self::$output['status']  = 'warning';
	// 		self::$output['comment'] = 'No change detected.';
	// 	}

	// 	echo wp_json_encode(self::$output);
	// 	wp_die();
	// }

	public static function sc_wordai_suggested_title_number_save() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );
		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json( array( 'status' => 'fail', 'message' => __( 'Permission denied.', 'wordai-pro' ) ) );
		}

		self::$output = [];
		$params = [];

		$params['wordai-suggested-title-number'] =
			isset($_POST['suggestedTitle'])
				? (int) sanitize_text_field($_POST['suggestedTitle'])
				: 2;

		// ✅ clamp to 1..10 (matches your UI)
		if ( $params['wordai-suggested-title-number'] < 1 )  $params['wordai-suggested-title-number'] = 1;
		if ( $params['wordai-suggested-title-number'] > 10 ) $params['wordai-suggested-title-number'] = 10;

		// Use the provider selected in the modal so a delayed request cannot save
		// this count into another provider's settings.
		$provider = isset( $_POST['provider'] )
			? sanitize_key( wp_unslash( $_POST['provider'] ) )
			: SftcyWordaiBase::sc_wordai_get_current_ai_provider();
		if ( ! SftcyWordaiBase::sc_wordai_is_valid_provider( $provider ) ) {
			wp_send_json( array( 'status' => 'fail', 'message' => __( 'Invalid AI provider.', 'wordai-pro' ) ) );
		}

		// ✅ choose correct option key
		$option_key = SftcyWordaiBase::sc_wordai_get_provider_option_key( 'content', $provider );

		$current_options = get_option( $option_key );
		$current_options = $current_options ? maybe_unserialize( $current_options ) : [];
		if ( ! is_array( $current_options ) ) $current_options = [];

		$updated_options = array_merge( $current_options, $params );

		$updated = update_option( $option_key, maybe_serialize( $updated_options ) );

		// ✅ clear option cache for the correct key
		wp_cache_delete( $option_key, 'options' );

		if ( $updated ) {
			self::$output['status']  = 'success';
			self::$output['comment'] = 'Updated Suggest Title Number To: ' . $params['wordai-suggested-title-number'];
			self::$output['provider'] = $provider;
			self::$output['option_key'] = $option_key;
		} else {
			self::$output['status']  = 'warning';
			self::$output['comment'] = 'No change detected.';
			self::$output['provider'] = $provider;
			self::$output['option_key'] = $option_key;
		}

		echo wp_json_encode( self::$output );
		wp_die();
	}


	/**
	 * Ajax: Save selected AI provider.
	 */
	// public static function sc_wordai_ai_provider_save() {
	// 	check_ajax_referer( 'scwordai_wpnonce', 'security' );

	// 	$provider = isset( $_POST['provider'] ) ? sanitize_text_field( wp_unslash( $_POST['provider'] ) ) : 'openai';

	// 	$allowed = array( 'openai', 'google' ); // later extend here.
	// 	if ( ! in_array( $provider, $allowed, true ) ) {
	// 		wp_send_json(
	// 			array(
	// 				'status'  => 'fail',
	// 				'message' => __( 'Invalid AI provider.', 'wordai-pro' ),
	// 			)
	// 		);
	// 	}

	// 	// NOTE: keep this option name in sync with base class
	// 	$updated_provider_status = update_option( 'sc-wordai-ai-provider', $provider );

	// 	wp_send_json(
	// 		array(
	// 			'status'   => 'success',
	// 			'provider' => $provider,
	// 			'updated'  => $updated_provider_status,
	// 			'message'  => __( 'AI provider updated.', 'wordai-pro' ),
	// 		)
	// 	);
	// }


	public static function sc_wordai_ai_provider_save() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json( array( 'status' => 'fail', 'message' => __( 'Permission denied.', 'wordai-pro' ) ) );
		}

		$provider = isset( $_POST['provider'] )
			? sanitize_key( wp_unslash( $_POST['provider'] ) )
			: 'openai';

		if ( ! SftcyWordaiBase::sc_wordai_is_valid_provider( $provider ) ) {
			if ( class_exists( 'SftcyWordaiSupport' ) ) {
				SftcyWordaiSupport::log_event( 'settings', 'error', 'invalid_provider_selection', 'Attempted to save an invalid AI provider.', array( 'provider' => $provider ), $provider, 'settings', 0 );
			}
			wp_send_json([
				'status'  => 'fail',
				'message' => __( 'Invalid AI provider.', 'wordai-pro' ),
			]);
		}

		$updated_provider_status = update_option( 'sc-wordai-ai-provider', $provider );

		wp_send_json([
			'status'   => 'success',
			'provider' => $provider,
			'label'    => SftcyWordaiBase::sc_wordai_get_provider_label( $provider ),
			'updated'  => (bool) $updated_provider_status,
			'message'  => __( 'AI provider updated.', 'wordai-pro' ),
		]);
	}



	/**
	 * Ajax Request - Post
	 * OpenAI API Key Show - Show Key Checkbox
	 * @return - json
	 */	
	public static function wordai_api_key_show() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );		
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json( array( 'status' => 'fail', 'feedbackMsg' => __( 'Permission denied.', 'wordai-pro' ) ) );
		}
		self::$output =	[];		
		$checked = isset( $_POST['postData'] ) ? sanitize_text_field( $_POST['postData']['checked'] ) : false;
		if ( $checked ) {
			$is_option_data_added = get_option('sftcy-wordai-openai-apisettings-data');						
			$options_data = $is_option_data_added ? maybe_unserialize( $is_option_data_added ) : '';			
			if ( isset( $options_data['wordai-openai-api-key-data'] ) && ! empty( $options_data['wordai-openai-api-key-data'] ) ) {
				self::$output['status']	= 'success';
				self::$output['apiKey'] = $options_data['wordai-openai-api-key-data'];
				self::$output['comment'] = 'API Key found.';
			}
			else {
				self::$output['status']	= 'fail';
				self::$output['feedbackMsg'] = __( 'API Key not set yet.', 'wordai-pro' );											
			}
		}
		else {
			self::$output['status']	= 'fail';
			self::$output['feedbackMsg'] = __( 'Something went wrong.', 'wordai-pro' );			
		}		
		echo wp_json_encode( self::$output );		
        wp_die();						
	}
	
	/**
	 * Ajax Request - Post
	 * AJAX: Save OpenAI API Key
	 * @return - json
	 */	
	public static function wordai_openai_api_key_data_save() {

		check_ajax_referer('scwordai_wpnonce', 'security');
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json( array( 'status' => 'fail', 'feedbackMsg' => __( 'Permission denied.', 'wordai-pro' ) ) );
		}

		$realKey = isset($_POST['realKey']) ? trim(sanitize_text_field($_POST['realKey'])) : '';

		$settings = SftcyWordaiBase::sc_wordai_get_current_api_settings();

		$current = $settings['wordai-openai-api-key-data'] ?? '';
		$mask    = SftcyWordaiBase::wordai_api_key_mask_format($current, 'openai');

		// Reject masked placeholder
		if ($realKey === '' || $realKey === $mask) {
			if ( class_exists( 'SftcyWordaiSupport' ) ) {
				SftcyWordaiSupport::log_event( 'settings', 'error', 'openai_api_key_invalid', 'OpenAI API key save failed because no real API key was provided.', array( 'page' => 'api_settings' ), 'openai', 'settings', 0 );
			}
			wp_send_json([
				'status'      => 'fail',
				'feedbackMsg' => __('Enter real OpenAI API key.', 'wordai-pro')
			]);
		}

		// If unchanged
		if ($realKey === $current) {
			wp_send_json([
				'status'      => 'warning',
				'feedbackMsg' => __('Nothing changes.', 'wordai-pro')
			]);
		}

		// Save new key
		$settings['wordai-openai-api-key-data'] = $realKey;
		$settings['wordai-openai-api-key-mask'] = SftcyWordaiBase::wordai_api_key_mask_format($realKey, 'openai');

		update_option('sftcy-wordai-openai-apisettings-data', $settings);

		wp_send_json([
			'status'      => 'success',
			'feedbackMsg' => __('API key saved successfully.', 'wordai-pro'),
			'savedKey'    => $realKey,
			'savedMask'   => $settings['wordai-openai-api-key-mask']
		]);
	}
	
	/**
	 * Ajax Request
	 * OpenAI API settings parameter
	 * API settings parameter - Form submit data
	 * return - json
	 */
	public static function sc_wordai_openai_apisettings_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );		
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json( array( 'status' => 'fail', 'feedbackMsg' => __( 'Permission denied.', 'wordai-pro' ) ) );
		}
		self::$output =	[];				
		$post_data = isset( $_POST['postData'] ) ? sanitize_text_field( $_POST['postData'] ) : '';		
		parse_str( $post_data, $params );						
		array_walk( $params, function( &$value, $key ) { $value	= sanitize_text_field( $value ); });
		$params['sc-wordai-streaming']	= ( isset( $params['sc-wordai-streaming'] ) && $params['sc-wordai-streaming'] == 'on' )? 1 : 0;															
		$is_option_data_added           = get_option('sftcy-wordai-openai-apisettings-data');
		$updated_options_data           = $is_option_data_added ? array_merge( maybe_unserialize( $is_option_data_added ), $params ) : $params;		
		$update_data					= update_option('sftcy-wordai-openai-apisettings-data', maybe_serialize( $updated_options_data ) );				
							
		if ( $update_data ) {
			self::$output['status']		= 'success';
			self::$output['feedbackMsg'] = __( 'API Settings Parameter saved successfully.', 'wordai-pro' );
		}
		else if ( ! $update_data ) {
			self::$output['status']		= 'warning';
			self::$output['feedbackMsg'] = __( 'Nothing Changes.', 'wordai-pro' );			
		}
		else {
			self::$output['status']		= 'fail';
			self::$output['feedbackMsg'] = __( 'Something went wrong, try again.', 'wordai-pro' );			
		}
		echo wp_json_encode( self::$output );		
        wp_die();				
	}
	
	/**
	 * Ajax Request
	 * OpenAI API settings parameter
	 * Reset settings parameter
	 * return - json
	 */
	public static function sc_wordai_openai_apisettings_reset_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );		
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json( array( 'status' => 'fail', 'feedbackMsg' => __( 'Permission denied.', 'wordai-pro' ) ) );
		}
		self::$output	= [];
		$params = SftcyWordaiOpenai::get_default_openai_settings();
		$is_option_data_added = get_option('sftcy-wordai-openai-apisettings-data');
		$updated_options_data = $is_option_data_added ? array_merge( maybe_unserialize( $is_option_data_added ), $params ) : $params;
		$update_data = update_option('sftcy-wordai-openai-apisettings-data', maybe_serialize( $updated_options_data ) );						
		if ( $update_data ) {
			self::$output['status']	= 'success';
			self::$output['feedbackMsg'] = __('Reset to default settings successfully.', 'wordai-pro');
		}
		else if ( ! $update_data ) {
			self::$output['status']	= 'warning';
			self::$output['feedbackMsg'] = __('Nothing Changes, API settings already in default.', 'wordai-pro');
		}		
		else {
			self::$output['status']	= 'fail';
			self::$output['feedbackMsg'] = __('Something went wrong, try again.', 'wordai-pro');
		}
		echo wp_json_encode( self::$output );		
        wp_die();				
	}
	
	
	/**
	 * ======================================================================
	 *  AJAX: Save WordAI Content Settings
	 *  ----------------------------------------------------------------------
	 *  Handles all form fields (writing prefs, structural prefs, SEO options)
	 *  and now includes Social Metadata defaults (Twitter / Pinterest).
	 * ======================================================================
	 */
	public static function sc_wordai_openai_content_settings_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );			
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json( array( 'status' => 'fail', 'feedbackMsg' => __( 'Permission denied.', 'wordai-pro' ) ) );
		}

		self::$output = [];		

		// Parse serialized form data
		$post_data = isset( $_POST['postData'] ) ? sanitize_text_field( $_POST['postData'] ) : '';
		parse_str( $post_data, $params );				
		array_walk( $params, function( &$value, $key ) {
			$value = sanitize_text_field( $value );
		});

		// Convert checkbox fields to 1/0 (on/off)
		$params['sc-wordai-insert-title']                    = isset( $params['sc-wordai-insert-title'] ) && $params['sc-wordai-insert-title'] === 'on' ? 1 : 0;
		$params['sc-wordai-insert-content']                  = isset( $params['sc-wordai-insert-content'] ) && $params['sc-wordai-insert-content'] === 'on' ? 1 : 0;
		$params['sc-wordai-insert-excerpt']                  = isset( $params['sc-wordai-insert-excerpt'] ) && $params['sc-wordai-insert-excerpt'] === 'on' ? 1 : 0;
		$params['sc-wordai-insert-tags']                     = isset( $params['sc-wordai-insert-tags'] ) && $params['sc-wordai-insert-tags'] === 'on' ? 1 : 0;
		$params['sc-wordai-insert-seo-title']                = isset( $params['sc-wordai-insert-seo-title'] ) && $params['sc-wordai-insert-seo-title'] === 'on' ? 1 : 0;
		$params['sc-wordai-insert-seo-meta-description']     = isset( $params['sc-wordai-insert-seo-meta-description'] ) && $params['sc-wordai-insert-seo-meta-description'] === 'on' ? 1 : 0;
		$params['sc-wordai-insert-seo-meta-focus-keyword']   = isset( $params['sc-wordai-insert-seo-meta-focus-keyword'] ) && $params['sc-wordai-insert-seo-meta-focus-keyword'] === 'on' ? 1 : 0;
		$params['sc-wordai-use-seo-content-structure']       = isset( $params['sc-wordai-use-seo-content-structure'] ) && $params['sc-wordai-use-seo-content-structure'] === 'on' ? 1 : 0;
		$params['sc-wordai-use-heading-structure']           = isset( $params['sc-wordai-use-heading-structure'] ) && $params['sc-wordai-use-heading-structure'] === 'on' ? 1 : 0;
		$params['sc-wordai-use-seo-content-depth']           = isset( $params['sc-wordai-use-seo-content-depth'] ) && $params['sc-wordai-use-seo-content-depth'] === 'on' ? 1 : 0;
		$params['sc-wordai-use-people-first-content']        = isset( $params['sc-wordai-use-people-first-content'] ) && $params['sc-wordai-use-people-first-content'] === 'on' ? 1 : 0;
		$params['sc-wordai-use-trust-signals']               = isset( $params['sc-wordai-use-trust-signals'] ) && $params['sc-wordai-use-trust-signals'] === 'on' ? 1 : 0;
		$params['sc-wordai-use-content-freshness']           = isset( $params['sc-wordai-use-content-freshness'] ) && $params['sc-wordai-use-content-freshness'] === 'on' ? 1 : 0;

		// ✅ NEW: Social Metadata Default Fields
		$params['sc-wordai-twitter-site']                    = ! empty( $params['sc-wordai-twitter-site'] ) ? sanitize_text_field( $params['sc-wordai-twitter-site'] ) : '@yourbrand';
		$params['sc-wordai-twitter-creator']                 = ! empty( $params['sc-wordai-twitter-creator'] ) ? sanitize_text_field( $params['sc-wordai-twitter-creator'] ) : '@creatorname';
		$params['sc-wordai-pinterest-verification']           = ! empty( $params['sc-wordai-pinterest-verification'] ) ? sanitize_text_field( $params['sc-wordai-pinterest-verification'] ) : '';
		$params['sc-wordai-enable-pinterest-richpins']        = isset( $params['sc-wordai-enable-pinterest-richpins'] ) && $params['sc-wordai-enable-pinterest-richpins'] === 'on' ? 1 : 0;

		if ( class_exists( 'SftcyWordaiSeoStandards' ) ) {
			$params = SftcyWordaiSeoStandards::sanitize_content_settings( $params );
		}

		if ( class_exists( 'SftcyWordaiFeatures' ) ) {
			$params = SftcyWordaiFeatures::wordai_apply_content_setting_limits( $params );
		}

		// Merge & Save
		$is_option_data_added = get_option( 'sftcy-wordai-openai-content-settings-data' );
		$updated_options = $is_option_data_added ? array_merge( maybe_unserialize( $is_option_data_added ), $params ) : $params;      		
		$update_data = update_option( 'sftcy-wordai-openai-content-settings-data', maybe_serialize( $updated_options ) );						

		if ( $update_data ) {
			self::$output['status'] = 'success';
			self::$output['feedbackMsg'] = __( 'Content settings saved successfully.', 'wordai-pro' );
		}
		elseif ( ! $update_data ) {
			self::$output['status'] = 'warning';
			self::$output['feedbackMsg'] = __( 'Nothing Changed.', 'wordai-pro' );			
		}
		else {
			self::$output['status'] = 'fail';
			self::$output['feedbackMsg'] = __( 'Something went wrong, try again.', 'wordai-pro' );
		}

		echo wp_json_encode( self::$output );		
		wp_die();						
	}

	
	/**
	 * OpenAI API - content settings
	 * Content settings parameter - Reset to default settings
	 * return - json
	 */
	public static function sc_wordai_openai_content_settings_reset_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );			
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json( array( 'status' => 'fail', 'feedbackMsg' => __( 'Permission denied.', 'wordai-pro' ) ) );
		}
		self::$output = [];
		$params = SftcyWordaiBase::sc_wordai_api_content_settings_default_parameters();
		if ( class_exists( 'SftcyWordaiFeatures' ) ) {
			$params = SftcyWordaiFeatures::wordai_apply_content_setting_limits( $params );
		}
		$update_data = update_option('sftcy-wordai-openai-content-settings-data', maybe_serialize( $params ) );
		if ( $update_data ) {
			self::$output['status']	= 'success';
			self::$output['feedbackMsg'] = __('Reset to default settings successfully.', 'wordai-pro');
		}
		elseif ( ! $update_data ) {
			self::$output['status']	= 'warning';
			self::$output['feedbackMsg'] = __('Nothing changes. No required to reset settings.', 'wordai-pro');
		}		
		else {
			self::$output['status']	= 'fail';
			self::$output['feedbackMsg'] = __('Something went wrong,try again.', 'wordai-pro');
		}
		echo wp_json_encode( self::$output );		
        wp_die();				
		
	}
	
	
	/**
	 * Ajax Request
	 * OpenAI API - image settings - Save
	 * Image settings parameter - form submit data
	 * @return - json
	 */
	// public static function sc_wordai_openai_image_settings_data() {
	// 	check_ajax_referer( 'scwordai_wpnonce', 'security' );			
	// 	self::$output = [];		
	// 	$post_data = isset( $_POST['postData'] ) ? sanitize_text_field( $_POST['postData'] ) : '';
	// 	parse_str( $post_data, $params );	
	// 	array_walk( $params, function( &$value, $key ) { $value = sanitize_text_field( $value ); });

	// 	$params['sc-wordai-imagesave-togallery'] = ( isset( $params['sc-wordai-imagesave-togallery'] ) && $params['sc-wordai-imagesave-togallery'] == 'on' )? 1 : 0;
	// 	$params['sc-wordai-dalle3-image-hd-quality'] = ( isset( $params['sc-wordai-dalle3-image-hd-quality'] ) && $params['sc-wordai-dalle3-image-hd-quality'] == 'on' )? 1 : 0;		
	// 	$params['sc-wordai-set-feature-image'] = ( isset( $params['sc-wordai-set-feature-image'] ) && $params['sc-wordai-set-feature-image'] == 'on' )? 1 : 0;		
	// 	$update_data = update_option('sftcy-wordai-openai-image-settings-data', maybe_serialize( $params ) );		
	// 	if ( $update_data ) {
	// 		self::$output['status']	= 'success';
	// 		self::$output['feedbackMsg'] = __( 'Image settings saved successfully.', 'wordai-pro' );
	// 	}
	// 	elseif ( ! $update_data ) {
	// 		self::$output['status']	= 'warning';
	// 		self::$output['feedbackMsg'] = __( 'Nothing Changes.', 'wordai-pro' );
	// 	}		
	// 	else {
	// 		self::$output['status']	= 'fail';
	// 		self::$output['feedbackMsg'] = __( 'Something went wrong,try again.', 'wordai-pro' );
	// 	}
	// 	echo wp_json_encode( self::$output );		
    //     wp_die();						
	// }

	public static function sc_wordai_openai_image_settings_data() {
		check_ajax_referer('scwordai_wpnonce', 'security');
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json( array( 'status' => 'fail', 'feedbackMsg' => __( 'Permission denied.', 'wordai-pro' ) ) );
		}

		self::$output = [];

		$post_data = isset($_POST['postData']) ? sanitize_text_field($_POST['postData']) : '';
		parse_str($post_data, $params);

		array_walk($params, function (&$v) { $v = sanitize_text_field($v); });

		// Checkboxes
		$params['sc-wordai-imagesave-togallery']         = isset($params['sc-wordai-imagesave-togallery']) ? 1 : 0;
		$params['sc-wordai-dalle3-image-hd-quality']      = isset($params['sc-wordai-dalle3-image-hd-quality']) ? 1 : 0;
		$params['sc-wordai-set-feature-image']            = isset($params['sc-wordai-set-feature-image']) ? 1 : 0;

		if ( class_exists( 'SftcyWordaiFeatures' ) ) {
			$params = SftcyWordaiFeatures::wordai_apply_image_setting_limits( $params );
		}

		$updated = update_option('sftcy-wordai-openai-image-settings-data', maybe_serialize($params));

		self::$output['status']      = $updated ? 'success' : 'warning';
		self::$output['feedbackMsg'] = $updated ? __('Image settings saved successfully.', 'wordai-pro')
												: __('Nothing changed.', 'wordai-pro');

		echo wp_json_encode(self::$output);
		wp_die();
	}

	
	/**
	 * OpenAI API - image settings - Reset
	 * Image settings parameter - Reset to default settings
	 * return - json
	 */
	// public static function sc_wordai_openai_image_settings_reset_data() {
	// 	check_ajax_referer( 'scwordai_wpnonce', 'security' );			
	// 	self::$output = [];
	// 	$params	= SftcyWordaiBase::sc_wordai_openai_image_settings_default_parameters();					
	// 	$update_data = update_option('sftcy-wordai-openai-image-settings-data', maybe_serialize( $params ) );		
	// 	if ( $update_data ) {
	// 		self::$output['status']	= 'success';
	// 		self::$output['feedbackMsg'] = __('Reset to default settings successfully.', 'wordai-pro');
	// 	}
	// 	else if ( ! $update_data ) {
	// 		self::$output['status']	= 'warning';
	// 		self::$output['feedbackMsg'] = __('Nothing changes. No required to reset settings', 'wordai-pro');
	// 	}		
	// 	else {
	// 		self::$output['status']	= 'fail';
	// 		self::$output['feedbackMsg'] = __('Something went wrong,try again.', 'wordai-pro');
	// 	}		
	// 	echo wp_json_encode( self::$output );		
    //     wp_die();						
	// }

	public static function sc_wordai_openai_image_settings_reset_data() {
		check_ajax_referer('scwordai_wpnonce', 'security');
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json( array( 'status' => 'fail', 'feedbackMsg' => __( 'Permission denied.', 'wordai-pro' ) ) );
		}

		self::$output = [];

		$defaults = SftcyWordaiBase::sc_wordai_openai_image_settings_default_parameters();
		if ( class_exists( 'SftcyWordaiFeatures' ) ) {
			$defaults = SftcyWordaiFeatures::wordai_apply_image_setting_limits( $defaults );
		}

		$updated = update_option('sftcy-wordai-openai-image-settings-data', maybe_serialize($defaults));

		self::$output['status']      = $updated ? 'success' : 'warning';
		self::$output['feedbackMsg'] = $updated
			? __('Reset to default settings successfully.', 'wordai-pro')
			: __('Nothing changed.', 'wordai-pro');

		echo wp_json_encode(self::$output);
		wp_die();
	}

	
	/**
	 * Ajax: Return current provider-aware runtime settings (used by popups to avoid reload).
	 */
	// public static function sc_wordai_get_provider_runtime_settings() {
	// 	check_ajax_referer( 'scwordai_wpnonce', 'security' );

	// 	if ( ! current_user_can( 'edit_posts' ) ) {
	// 		wp_send_json([
	// 			'status'  => 'fail',
	// 			'message' => __( 'Permission denied.', 'wordai-pro' ),
	// 		]);
	// 	}

	// 	$provider   = SftcyWordaiBase::sc_wordai_get_current_ai_provider();
	// 	$image_data = SftcyWordaiBase::sc_wordai_get_current_image_settings();

	// 	wp_send_json([
	// 		'status'   => 'success',
	// 		'provider' => $provider,
	// 		'image'    => [
	// 			'save_to_gallery' => isset($image_data['sc-wordai-imagesave-togallery']) ? (int) $image_data['sc-wordai-imagesave-togallery'] : 0,
	// 			'set_featured'    => isset($image_data['sc-wordai-set-feature-image']) ? (int) $image_data['sc-wordai-set-feature-image'] : 0,
	// 			'image_number'    => isset($image_data['sc-wordai-image-number']) ? (int) $image_data['sc-wordai-image-number'] : 1,
	// 		],
	// 	]);
	// }

	/**
	 * Ajax: Return current provider-aware runtime settings (used by popups to avoid reload).
	 */
	public static function sc_wordai_get_provider_runtime_settings() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json([
				'status'  => 'fail',
				'message' => __( 'Permission denied.', 'wordai-pro' ),
			]);
		}

		$provider = isset( $_POST['provider'] )
			? sanitize_key( wp_unslash( $_POST['provider'] ) )
			: SftcyWordaiBase::sc_wordai_get_current_ai_provider();
		if ( ! SftcyWordaiBase::sc_wordai_is_valid_provider( $provider ) ) {
			wp_send_json( array( 'status' => 'fail', 'message' => __( 'Invalid AI provider.', 'wordai-pro' ) ) );
		}

		$image_data    = SftcyWordaiBase::sc_wordai_get_current_image_settings();
		$content_key   = SftcyWordaiBase::sc_wordai_get_provider_option_key( 'content', $provider );
		$content_saved = $content_key ? maybe_unserialize( get_option( $content_key, array() ) ) : array();
		$content_saved = is_array( $content_saved ) ? $content_saved : array();
		$content_data  = array_merge(
			SftcyWordaiBase::sc_wordai_get_provider_default_settings( 'content', $provider ),
			$content_saved
		);

		wp_send_json([
			'status'   => 'success',
			'provider' => $provider,

			// ✅ IMAGE FLAGS
			'image'    => [
				'save_to_gallery' => isset($image_data['sc-wordai-imagesave-togallery']) ? (int) $image_data['sc-wordai-imagesave-togallery'] : 0,
				'set_featured'    => isset($image_data['sc-wordai-set-feature-image']) ? (int) $image_data['sc-wordai-set-feature-image'] : 0,
				'image_number'    => isset($image_data['sc-wordai-image-number']) ? (int) $image_data['sc-wordai-image-number'] : 1,
			],

			// ✅ CONTENT FLAGS
			'content'  => [
				'suggested_title_number' => isset($content_data['wordai-suggested-title-number'])
					? (int) $content_data['wordai-suggested-title-number']
					: 2,
			],
		]);
	}


	/**
	 * ======================================================================
	 * AJAX: Generate Title (OpenAI + Gemini via Router)
	 * ======================================================================
	 */
	public static function sc_wordai_write_titles() {

		check_ajax_referer('scwordai_wpnonce', 'security');

		// 1. Read Prompt
		$prompt_raw = isset($_POST['params']['prompt'])
			? sanitize_text_field($_POST['params']['prompt'])
			: '';

		if (empty(trim($prompt_raw))) {
			wp_send_json([
				'status'      => 'fail',
				'feedbackMsg' => __('Prompt is empty.', 'wordai-pro'),
			]);
		}

		// 2. Generate unified formatted prompt
		$prompt = SftcyWordaiOpenai::generate_prompt(trim($prompt_raw), 'title');

		// 3. Build provider-aware params
		$api_params = SftcyWordaiAiProviderRouter::build_content_params($prompt);

		// 4. Generate title via router
		$response = SftcyWordaiAiProviderRouter::generate_content($api_params);

		// WP_Error → normalize
		if (is_wp_error($response)) {
			wp_send_json([
				'status'      => 'fail',
				'errorMessage'=> $response->get_error_message(),
			]);
		}

		// 5. SUCCESS → CLEAN & FORMAT
		if (isset($response['status']) && $response['status'] === 'success') {

			// Remove markdown (bold, italic, list markers etc.)
			$response['responseText'] = SftcyWordaiBase::sc_wordai_strip_markdown(
				$response['responseText']
			);

			// Titles normally come as multiple quoted `"Title"`
			// Remove leftover quotes
			$response['responseText'] = trim(
				preg_replace('/^["\']+|["\']+$/', '', $response['responseText'])
			);

			// UI expects <br/> version
			$response['responseTextWithBR'] = preg_replace(
				"/\n\n/",
				"<br/><br/>",
				$response['responseText']
			);
		}

		wp_send_json($response);
	}

		
	
	/**
	 * Suggest titles Button Click - SUggest Titles Modal Window
	 * Older version
	 * return - json
	 */
	// public static function sc_wordai_write_suggest_titles() {
	// 	check_ajax_referer( 'scwordai_wpnonce', 'security' );						
	// 	$prompt_hints			= isset( $_POST['params']['prompt'] )? sanitize_text_field( $_POST['params']['prompt'] ) : '';				
	// 	$prompt					= SftcyWordaiOpenai::generate_prompt( trim( $prompt_hints ), 'suggest-title' );		
	// 	$api_params				= SftcyWordaiOpenai::set_openai_params();	
	// 	//$api_params['prompt']	= $prompt;				
	// 	$api_params['messages']	= [ array('role' => 'user', 'content' => $prompt ) ];				
	// 	$response				= SftcyWordaiOpenai::create_content( $api_params);				
		
	// 	if ( isset( SftcyWordaiOpenai::$output['status'] ) && SftcyWordaiOpenai::$output['status'] == 'success' ) {
	// 		// var_dump( SftcyWordaiOpenai::$output['responseText'] );
	// 		// pick the text between double quotes			
	// 		// preg_match_all('/"([^"]+)"/', SftcyWordaiOpenai::$output['responseText'], $matches );

	// 		// Step 1: Remove leading numbering (digit(s) + dot + space) from each line
	// 		$sanitized_partial_data = preg_replace('/^\d+\.\s*/m', '', SftcyWordaiOpenai::$output['responseText'] );
	// 		// Step 2: Extract text inside matching quotes
	// 		preg_match_all('/([\'"])(.*?)\1/', $sanitized_partial_data, $matches );												
	// 		SftcyWordaiOpenai::$output['listOfTitles'] =	'';
	// 		$i = 1;
	// 		if ( isset ( $matches[2] ) && array_filter( $matches[2] ) ) {				
	// 			foreach ( $matches[2] as $title ) {					
	// 				$radio_input_id = 'WordAISuggesTitleRadioBox-' . $i;
	// 				$title = preg_replace("/[\n\n\"]+/","", $title );					
	// 				SftcyWordaiOpenai::$output['listOfTitles']	.= '<li><label for="' . $radio_input_id . '"><input type="radio" id="' . $radio_input_id . '" class="suggested-title-radio" name="suggested-title-radio" /> '. $title .'</label></li>';
	// 				$i++;
	// 			}				
	// 		}
	// 		else {
	// 			$radio_input_id = 'WordAISuggesTitleRadioBox-' . $i;
	// 			$single_sanitized_title_name = preg_replace("/[\n\n\"]+/","", SftcyWordaiOpenai::$output['responseText'] );				
	// 			SftcyWordaiOpenai::$output['listOfTitles'] .= '<li><label for="' . $radio_input_id . '"><input type="radio" id="' . $radio_input_id . '" class="suggested-title-radio" name="suggested-title-radio" /> '. $single_sanitized_title_name .'</label></li>';
	// 		}
	// 	}		
		
	// 	echo wp_json_encode( SftcyWordaiOpenai::$output );		
	// 	wp_die();
	// }


	/**
	 * ============================================================================
	 * Suggest Titles (OpenAI + Gemini compatible)
	 * ============================================================================
	 * - Uses unified prompt builder (OpenAI style)
	 * - Uses central router param builder (Gemini + OpenAI aware)
	 * - Calls provider-agnostic router::generate_content()
	 * - Always returns:
	 *      status
	 *      responseText
	 *      responseTextWithBR
	 *      listOfTitles  (<li> HTML)
	 * ============================================================================
	 */
	public static function sc_wordai_write_suggest_titles() {

		check_ajax_referer('scwordai_wpnonce', 'security');

		/*--------------------------------------------------------------
		| 1. Read raw prompt from request
		--------------------------------------------------------------*/
		$prompt_hints = isset($_POST['params']['prompt'])
			? sanitize_text_field($_POST['params']['prompt'])
			: '';

		/*--------------------------------------------------------------
		| 2. Build final formatted prompt (same for OpenAI + Gemini)
		--------------------------------------------------------------*/
		$prompt = SftcyWordaiOpenai::generate_prompt(trim($prompt_hints), 'suggest-title');

		/*--------------------------------------------------------------
		| 3. Build provider-aware API params (OpenAI OR Gemini)
		--------------------------------------------------------------*/
		$api_params = SftcyWordaiAiProviderRouter::build_content_params($prompt);
		// Suggested titles are short. Use one complete provider response so every
		// provider is normalized by the same parser before the radio list renders.
		if ( is_array( $api_params ) && ! isset( $api_params['status'] ) ) {
			$api_params['stream'] = false;
			if ( isset( $api_params['params'] ) && is_array( $api_params['params'] ) ) {
				$api_params['params']['stream'] = false;
			}
		}

		/*--------------------------------------------------------------
		| 4. Call unified AI provider router → returns normalized output
		--------------------------------------------------------------*/
		$response = SftcyWordaiAiProviderRouter::generate_content($api_params);

		/*--------------------------------------------------------------
		| 5. On Success → extract Titles from responseText
		--------------------------------------------------------------*/
		if (isset($response['status']) && $response['status'] === 'success') {

			$raw_text = (string) ( $response['responseText'] ?? '' );
			$content_settings = SftcyWordaiBase::sc_wordai_get_current_content_settings();
			$title_limit = isset( $content_settings['wordai-suggested-title-number'] ) ? (int) $content_settings['wordai-suggested-title-number'] : 2;
			$titles   = self::normalize_suggested_titles( $raw_text, $title_limit );
			if ( empty( $titles ) ) {
				$response['status']       = 'fail';
				$response['errorMessage'] = __( 'No usable title suggestions were returned. Please try again.', 'wordai' );
				echo wp_json_encode( $response );
				wp_die();
			}
			$list_html = self::render_suggested_titles_list( $titles );

			// Attach to response
			$response['suggestedTitles'] = $titles;
			$response['listOfTitles'] = $list_html;

			// Also add <br/> version for UI usage
			$response['responseTextWithBR'] =
				preg_replace("/\n\n/", "<br/><br/>", $response['responseText']);
		}

		/*--------------------------------------------------------------
		| 6. Return final JSON response
		--------------------------------------------------------------*/
		echo wp_json_encode($response);
		wp_die();
	}

	/**
	 * Normalize provider output into clean, unique title candidates.
	 * Handles JSON arrays, quoted titles, malformed adjacent quotes, numbered
	 * lists, bullets, Markdown links, and provider commentary.
	 *
	 * @param string $raw_text Provider response text.
	 * @param int    $limit Maximum titles to return.
	 * @return array
	 */
	public static function normalize_suggested_titles( $raw_text, $limit = 10 ) {
		$text = html_entity_decode( wp_strip_all_tags( (string) $raw_text ), ENT_QUOTES | ENT_HTML5, 'UTF-8' );
		$text = preg_replace( '/```(?:json|text)?|```/iu', '', $text );
		$text = str_replace( array( '“', '”', '„', '‟' ), '"', $text );
		$text = trim( preg_replace( "/\r\n?/", "\n", $text ) );
		$candidates = array();

		$decoded = json_decode( $text, true );
		if ( is_array( $decoded ) ) {
			if ( isset( $decoded['titles'] ) && is_array( $decoded['titles'] ) ) {
				$decoded = $decoded['titles'];
			}
			foreach ( $decoded as $value ) {
				if ( is_scalar( $value ) ) {
					$candidates[] = (string) $value;
				}
			}
		}
		$parse_text = preg_replace( '/\\\\(["“”„‟])/u', '$1', $text );

		if ( empty( $candidates ) ) {
			$adjacent = preg_split( '/"\s*(?:,|;|\||\/)?\s*"/u', $parse_text );
			if ( is_array( $adjacent ) && count( $adjacent ) > 1 ) {
				$candidates = $adjacent;
			}
		}

		if ( empty( $candidates ) && preg_match_all( '/"([^"\r\n]{2,})"/u', $parse_text, $quoted ) ) {
			$candidates = $quoted[1];
		}

		if ( empty( $candidates ) ) {
			$candidates = preg_split( '/\n+|(?=\s*\d+\s*[\.\):\-]\s+)/u', $parse_text );
		}

		$titles = array();
		foreach ( (array) $candidates as $candidate ) {
			$title = self::clean_suggested_title( $candidate );
			if ( '' === $title || preg_match( '/^(?:here\s+are\b.*|suggested\s+titles?\b.*|titles?\s*:?)$/iu', $title ) ) {
				continue;
			}
			$key = strtolower( $title );
			if ( isset( $titles[ $key ] ) ) {
				continue;
			}
			$titles[ $key ] = $title;
			if ( count( $titles ) >= max( 1, min( 10, (int) $limit ) ) ) {
				break;
			}
		}

		return array_values( $titles );
	}

	private static function clean_suggested_title( $candidate ) {
		$title = trim( (string) $candidate );
		if ( preg_match( '/^\[([^\]]+)\]\([^\)]+\)$/u', $title, $link ) ) {
			$title = $link[1];
		}
		$title = preg_replace( '/\]\([^\)]+\)$/u', '', $title );
		$title = preg_replace( '/^\s*(?:[-*•]+\s*|\d+\s*[\.\):\-]\s*|title\s*\d*\s*[:\-]\s*)/iu', '', $title );
		$title = str_replace( array( '"', '“', '”', '„', '‟' ), '', $title );
		$title = trim( $title, " \t\n\r\0\x0B[]{}(),;|" );
		$title = sanitize_text_field( preg_replace( '/\s+/u', ' ', $title ) );

		return trim( $title );
	}

	private static function render_suggested_titles_list( array $titles ) {
		$list_html = '';
		foreach ( $titles as $index => $title ) {
			$id = 'WordAISuggesTitleRadioBox-' . ( $index + 1 );
			$list_html .= '<li><label for="' . esc_attr( $id ) . '">'
				. '<input type="radio" id="' . esc_attr( $id ) . '" class="suggested-title-radio" name="suggested-title-radio" value="' . esc_attr( $title ) . '" /> '
				. esc_html( $title )
				. '</label></li>';
		}

		return $list_html;
	}


				
	
	/**
	 * Update - suggest title
	 * return - json
	 */
	public static function sc_wordai_update_suggest_title() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );								
		self::$output			= [];
		$selected_title			=  isset( $_POST['params']['selectedTitle'] )? sanitize_text_field( $_POST['params']['selectedTitle'] ) : '';		
		$post_id				=  isset( $_POST['params']['postID'] )? sanitize_text_field( $_POST['params']['postID'] ) : 0;		
		//var_dump( $post_id );
		//var_dump( $selected_title );
		
		// Update post title
        $post_data = array(
            'ID'           => intval($post_id),
            'post_title'   => $selected_title,
        );

        // Update post title into the database
        $update_status	=	wp_update_post( $post_data );
		if ( $update_status ) {
			self::$output['status']	= 'success';
			self::$output['postID']	= $update_status;
		}
		else {
			self::$output['status']	= 'fail';
		}
						
		echo wp_json_encode( self::$output );		
		wp_die();		
	}
	
	/**
	 * Ajax Request
	 * Write content
	 * return - json
	 * @since 1.0.0
	 */
	// public static function sc_wordai_write_content() {
	// 	check_ajax_referer( 'scwordai_wpnonce', 'security' );								
	// 	$prompt_hints			= isset( $_POST['params']['prompt'] )? sanitize_text_field( $_POST['params']['prompt'] ) : '';		
	// 	$prompt					= SftcyWordaiOpenai::generate_prompt( trim( $prompt_hints ), 'content' );								
	// 	$api_params				= SftcyWordaiOpenai::set_openai_params();
	// 	//$api_params['prompt']	= $prompt;
	// 	$api_params['messages']	= [ array('role' => 'user', 'content' => $prompt ) ];
				
	// 	$response				= SftcyWordaiOpenai::create_content( $api_params);		
	// 	// var_dump( SftcyWordaiOpenai::$output );		

	// 	//SftcyWordaiOpenai::$output['status']			= 'success';
	// 	//SftcyWordaiOpenai::$output['responseText']	= "\n\nDog: Man's Best Friend\n\nIntroduction\n\nThe dog is one of the most beloved animals in the world. It is a loyal and faithful companion that has been a part of human life for thousands of years. Dogs have been used for hunting, protection, and companionship, and they are still a popular pet today. Dogs come in a variety of shapes, sizes, and colors, and they can be found in almost every country in the world. Dogs are known for their intelligence, loyalty, and unconditional love, and they are often referred to as \"man's best friend.\"\n\nPhysical Characteristics\n\nDogs come in a wide variety of shapes, sizes, and colors. They can range from small toy breeds such as Chihuahuas and Pomeranians to large breeds such as Great Danes and St. Bernards. They can have short or long coats, and their fur can be straight, wavy, or curly. Dogs can be solid colors, or they can have a variety of markings. Some of the most popular colors are black, white, brown, and red.\n\nPersonality Traits\n\nDogs are known for their intelligence, loyalty, and unconditional love. They are very social animals and enjoy spending time with their owners. Dogs are also very protective of their owners and will often bark or growl when they sense danger. They are also very playful and enjoy playing fetch, tug-of-war, and other games. Dogs are also very trainable and can learn a variety of commands and tricks.\n\nConclusion\n\nThe dog is one of the most beloved animals in the world. It is a loyal and faithful companion that has been a part of human life for thousands of years. Dogs come in a variety of shapes, sizes, and colors, and they are known for their intelligence, loyalty, and unconditional love. Dogs are often referred to as \"man's best friend,\" and they make wonderful pets.";
				
	// 	if ( isset( SftcyWordaiOpenai::$output['status'] ) && SftcyWordaiOpenai::$output['status'] == 'success' ) {
	// 		// Replace all patterns of '### | ## | #' from each paragraph title what is found in GPT 4 models responses 
	// 		$hash_symbols = array('###', '##', '#');
	// 		SftcyWordaiOpenai::$output['responseText'] = str_replace( $hash_symbols,"", SftcyWordaiOpenai::$output['responseText'] );

	// 		// Replace \n\n with br to insert into dynamic created core/paragraph inside properly
	// 		SftcyWordaiOpenai::$output['responseTextWithBR'] = preg_replace("/\n\n/","<br/><br/>", SftcyWordaiOpenai::$output['responseText'] );
	// 	}
		
	// 	echo wp_json_encode( SftcyWordaiOpenai::$output );		
	// 	wp_die();
	// }

	/**
	 * ======================================================================
	 * AJAX: Generate Content (OpenAI + Gemini + Future Providers)
	 * ======================================================================
	 */
	// public static function sc_wordai_write_content() {

	// 	check_ajax_referer('scwordai_wpnonce', 'security');

	// 	// Your old UI sends params['prompt']
	// 	$prompt_raw = isset($_POST['params']['prompt'])
	// 		? sanitize_text_field($_POST['params']['prompt'])
	// 		: '';

	// 	if (empty(trim($prompt_raw))) {
	// 		wp_send_json([
	// 			'status'      => 'fail',
	// 			'feedbackMsg' => __('Prompt is empty.', 'wordai-pro'),
	// 		]);
	// 	}

	// 	// 🟦 Normalize prompt using existing OpenAI-style formatter
	// 	$prompt = SftcyWordaiOpenai::generate_prompt(trim($prompt_raw), 'content');

	// 	// 🟦 Build provider-aware $api_params
	// 	$api_params = SftcyWordaiAiProviderRouter::build_content_params($prompt);

	// 	// 🟦 Route to correct provider
	// 	$response = SftcyWordaiAiProviderRouter::generate_content($api_params);

	// 	// If WP_Error → convert to JSON format
	// 	if (is_wp_error($response)) {
	// 		wp_send_json([
	// 			'status'      => 'fail',
	// 			'feedbackMsg' => $response->get_error_message(),
	// 		]);
	// 	}

	// 	// SUCCESS CASE
	// 	if (isset($response['status']) && $response['status'] === 'success') {

	// 		// Clean headings for Gutenberg safety
	// 		$hash_symbols = ['###', '##', '#'];
	// 		$response['responseText'] = str_replace($hash_symbols, '', $response['responseText']);

	// 		// Ensure BR output exists (UI needs it)
	// 		$response['responseTextWithBR'] = preg_replace(
	// 			"/\n\n/",
	// 			"<br/><br/>",
	// 			$response['responseText']
	// 		);
	// 	}

	// 	wp_send_json($response);
	// }

	/**
	 * ======================================================================
	 * AJAX: Generate Content (Router + OpenAI + Gemini)
	 * ======================================================================
	 */
	public static function sc_wordai_write_content() {

		check_ajax_referer('scwordai_wpnonce', 'security');

		// Read raw prompt
		$prompt_raw = isset($_POST['params']['prompt'])
			? sanitize_text_field($_POST['params']['prompt'])
			: '';

		if (empty(trim($prompt_raw))) {
			wp_send_json([
				'status'      => 'fail',
				'feedbackMsg' => __('Prompt is empty.', 'wordai-pro'),
			]);
		}

		// Normalize prompt using your existing formatter
		$prompt = SftcyWordaiOpenai::generate_prompt(trim($prompt_raw), 'content');

		// Build provider-aware API params (central router)
		$api_params = SftcyWordaiAiProviderRouter::build_content_params($prompt);

		// STREAMING HANDLED INTERNALLY (router → provider → cURL hook)
		$response = SftcyWordaiAiProviderRouter::generate_content($api_params);

		// Convert WP_Error → JSON
		if (is_wp_error($response)) {
			wp_send_json([
				'status'      => 'fail',
				'feedbackMsg' => $response->get_error_message(),
			]);
		}

		// SUCCESS CASE → Clean & format
		if (isset($response['status']) && $response['status'] === 'success') {

			// Remove Markdown globally using helper
			$response['responseText'] = SftcyWordaiBase::sc_wordai_strip_markdown($response['responseText']);
			$response['responseText'] = SftcyWordaiBase::sc_wordai_normalize_generated_content_html($response['responseText']);

			// UI expects <br/> friendly version
			$response['responseTextWithBR'] = preg_replace(
				"/\n\n/",
				"<br/><br/>",
				$response['responseText']
			);
		}

		wp_send_json($response);
	}

	
	
	/**
	 * Write Excerpt
	 * return - json
	 */
	// public static function sc_wordai_write_excerpt() {
	// 	check_ajax_referer( 'scwordai_wpnonce', 'security' );						
	// 	$prompt_hints			= isset( $_POST['params']['prompt'] )? sanitize_text_field( $_POST['params']['prompt'] ) : '';				
	// 	$prompt					= SftcyWordaiOpenai::generate_prompt( trim( $prompt_hints ), 'excerpt' );		
	// 	$api_params				= SftcyWordaiOpenai::set_openai_params();	
	// 	//$api_params['prompt']	= $prompt;
	// 	$api_params['messages']	= [ array('role' => 'user', 'content' => $prompt ) ];		
	// 	//var_dump( $api_params );						
	// 	$response				= SftcyWordaiOpenai::create_content( $api_params);		
	// 	//var_dump( SftcyWordaiOpenai::$output );	
		
	// 	if ( isset( SftcyWordaiOpenai::$output['status'] ) && SftcyWordaiOpenai::$output['status'] == 'success' ) {
	// 		// Replace \n\n with br to insert content into dynamic created core/paragraph inside properly			
	// 		SftcyWordaiOpenai::$output['responseTextWithBR'] = preg_replace("/\n\n/","<br/><br/>", SftcyWordaiOpenai::$output['responseText'] );			
	// 	}		
		
	// 	echo wp_json_encode( SftcyWordaiOpenai::$output );		
	// 	wp_die();
	// }

	/**
	 * ======================================================================
	 * AJAX: Generate Excerpt (Router + OpenAI + Gemini)
	 * ======================================================================
	 */
	public static function sc_wordai_write_excerpt() {

		check_ajax_referer('scwordai_wpnonce', 'security');

		// 1. Read Prompt
		$prompt_raw = isset($_POST['params']['prompt'])
			? sanitize_text_field($_POST['params']['prompt'])
			: '';

		if (empty(trim($prompt_raw))) {
			wp_send_json([
				'status'      => 'fail',
				'feedbackMsg' => __('Prompt is empty.', 'wordai-pro'),
			]);
		}

		// 2. Normalize prompt using your existing formatter
		$prompt = SftcyWordaiOpenai::generate_prompt(trim($prompt_raw), 'excerpt');

		// 3. Build provider-aware $api_params (OpenAI or Google)
		$api_params = SftcyWordaiAiProviderRouter::build_content_params($prompt);

		// 4. Route → Provider → Normalized Response
		$response = SftcyWordaiAiProviderRouter::generate_content($api_params);

		// 5. Handle WP_Error
		if (is_wp_error($response)) {
			wp_send_json([
				'status'      => 'fail',
				'errorMessage'=> $response->get_error_message(),
			]);
		}

		// 6. SUCCESS PROCESSING
		if (isset($response['status']) && $response['status'] === 'success') {

			// Remove markdown artifacts (bold/italic/lists etc.)
			$response['responseText'] =
				SftcyWordaiBase::sc_wordai_strip_markdown($response['responseText']);

			// Ensure BR version for UI
			$response['responseTextWithBR'] = preg_replace(
				"/\n\n/",
				"<br/><br/>",
				$response['responseText']
			);
		}

		wp_send_json($response);
	}

	
	/**
	 * Write Tags
	 * return - json
	 */
	// public static function sc_wordai_write_tags() {
	// 	check_ajax_referer( 'scwordai_wpnonce', 'security' );						
	// 	$prompt_hints			= isset( $_POST['params']['prompt'] )? sanitize_text_field( $_POST['params']['prompt'] ) : '';				
	// 	$prompt					= SftcyWordaiOpenai::generate_prompt( trim( $prompt_hints ), 'tags' );		
	// 	$api_params				= SftcyWordaiOpenai::set_openai_params();	
	// 	//$api_params['prompt']	= $prompt;
	// 	$api_params['messages']	= [ array('role' => 'user', 'content' => $prompt ) ];		
	// 	//var_dump( $api_params );								
	// 	$response				= SftcyWordaiOpenai::create_content( $api_params);		
	// 	//var_dump( SftcyWordaiOpenai::$output );	
		
	// 	if ( isset( SftcyWordaiOpenai::$output['status'] ) && SftcyWordaiOpenai::$output['status'] == 'success' ) {
	// 		// Replace \n\n with br to insert content into dynamic created core/paragraph inside properly
	// 		SftcyWordaiOpenai::$output['responseText'] = preg_replace("/[\n\n\"]+/","", SftcyWordaiOpenai::$output['responseText'] );
	// 	}		
		
	// 	echo wp_json_encode( SftcyWordaiOpenai::$output );		
	// 	wp_die();
	// }	

	/**
	 * ======================================================================
	 * AJAX: Generate Tags (Router + OpenAI + Gemini)
	 * ======================================================================
	 */
	public static function sc_wordai_write_tags() {

		check_ajax_referer('scwordai_wpnonce', 'security');

		// 1. Read Prompt
		$prompt_raw = isset($_POST['params']['prompt'])
			? sanitize_text_field($_POST['params']['prompt'])
			: '';

		if (empty(trim($prompt_raw))) {
			wp_send_json([
				'status'      => 'fail',
				'feedbackMsg' => __('Prompt is empty.', 'wordai-pro'),
			]);
		}

		// 2. Normalize using your existing prompt generator
		$prompt = SftcyWordaiOpenai::generate_prompt(trim($prompt_raw), 'tags');

		// 3. Build provider-aware params
		$api_params = SftcyWordaiAiProviderRouter::build_content_params($prompt);

		// 4. Call correct provider (OpenAI or Gemini)
		$response = SftcyWordaiAiProviderRouter::generate_content($api_params);

		// 5. Handle WP_Error
		if (is_wp_error($response)) {
			wp_send_json([
				'status'      => 'fail',
				'errorMessage'=> $response->get_error_message(),
			]);
		}

		// 6. SUCCESS PROCESSING
		if (isset($response['status']) && $response['status'] === 'success') {

			// Remove markdown symbols (bold, italic, lists, #, *) etc.
			$response['responseText'] =
				SftcyWordaiBase::sc_wordai_strip_markdown($response['responseText']);

			// Remove newlines and quotes for comma-style tags
			$response['responseText'] = preg_replace(
				"/[\n\r\"]+/", "",
				$response['responseText']
			);

			// UI expects BR version (not used for tags, but safe)
			$response['responseTextWithBR'] = str_replace(
				"\n",
				"<br/>",
				$response['responseText']
			);
		}

		wp_send_json($response);
	}


	/**
	 * ======================================================================
	 * AJAX: Generate SEO Title (Router + OpenAI + Gemini)
	 * ======================================================================
	 */
	public static function sc_wordai_write_seo_titles() {

		check_ajax_referer('scwordai_wpnonce', 'security');

		/** 1. Collect Inputs */
		$prompt_raw = isset($_POST['params']['prompt'])
			? sanitize_text_field($_POST['params']['prompt'])
			: '';

		if (empty(trim($prompt_raw))) {
			wp_send_json([
				'status'      => 'fail',
				'feedbackMsg' => __('Prompt is empty.', 'wordai-pro'),
			]);
		}

		// Optional inputs (kept intact)
		// $post_id    = isset($_POST['params']['postID']) ? intval($_POST['params']['postID']) : 0;
		// $post_title = isset($_POST['params']['postTitle']) ? sanitize_text_field($_POST['params']['postTitle']) : '';

		/** 2. Build SEO-title-specific prompt */
		$prompt = SftcyWordaiOpenai::generate_prompt(
			trim($prompt_raw),
			'seotitle'
		);

		/** 3. Build provider-aware API params */
		$api_params = SftcyWordaiAiProviderRouter::build_content_params($prompt);

		/** 4. Execute provider (OpenAI or Gemini) */
		$response = SftcyWordaiAiProviderRouter::generate_content($api_params);

		if (is_wp_error($response)) {
			wp_send_json([
				'status'      => 'fail',
				'errorMessage'=> $response->get_error_message(),
			]);
		}

		/** 5. Success Case */
		if (isset($response['status']) && $response['status'] === 'success') {

			// Remove markdown syntax
			$clean_text = SftcyWordaiBase::sc_wordai_strip_markdown($response['responseText']);

			// Remove quotes + newlines (SEO titles should be one clean line)
			$clean_text = preg_replace('/[\n\r\"]+/', '', $clean_text);

			$response['responseText'] = trim($clean_text);

			// UI expects <br/> version (not really used for SEO title)
			$response['responseTextWithBR'] = str_replace("\n", "<br/>", $response['responseText']);
		}

		wp_send_json($response);
	}


	/**
	 * Write SEO Meta Description
	 * return - json
	 * @since 1.0.0
	 */
	// public static function sc_wordai_write_seo_meta_description() {
	// 	check_ajax_referer( 'scwordai_wpnonce', 'security' );						
	// 	$prompt_hints			= isset( $_POST['params']['prompt'] )? sanitize_text_field( $_POST['params']['prompt'] ) : '';				
	// 	$prompt					= SftcyWordaiOpenai::generate_prompt( trim( $prompt_hints ), 'seometadescription' );		
	// 	$api_params				= SftcyWordaiOpenai::set_openai_params();	
	// 	//$api_params['prompt']	= $prompt;
	// 	$api_params['messages']	= [ array('role' => 'user', 'content' => $prompt ) ];
		
	// 	//var_dump( $api_params );						
		
	// 	$response				= SftcyWordaiOpenai::create_content( $api_params);		
	// 	//var_dump( SC_Wordai_OpenAI::$output );	
		
	// 	if ( isset( SftcyWordaiOpenai::$output['status'] ) && SftcyWordaiOpenai::$output['status'] == 'success' ) {
	// 		// Replace \n\n with br to insert content into dynamic created core/paragraph inside properly
	// 		SftcyWordaiOpenai::$output['responseText'] = preg_replace("/[\n\n\"]+/","", SftcyWordaiOpenai::$output['responseText'] );
	// 	}		
		
	// 	echo wp_json_encode( SftcyWordaiOpenai::$output );		
	// 	wp_die();
	// }

	/**
	 * ======================================================================
	 * AJAX: Generate SEO Meta Description (Router + OpenAI + Gemini)
	 * ======================================================================
	 */
	public static function sc_wordai_write_seo_meta_description() {

		check_ajax_referer('scwordai_wpnonce', 'security');

		/** 1. Read prompt */
		$prompt_raw = isset($_POST['params']['prompt'])
			? sanitize_text_field($_POST['params']['prompt'])
			: '';

		if (empty(trim($prompt_raw))) {
			wp_send_json([
				'status'      => 'fail',
				'errorMessage'=> __('Prompt is empty.', 'wordai-pro'),
			]);
		}

		/** 2. Build meta-description-specific prompt */
		$prompt = SftcyWordaiOpenai::generate_prompt(
			trim($prompt_raw),
			'seometadescription'
		);

		/** 3. Build provider-aware params (OpenAI or Gemini) */
		$api_params = SftcyWordaiAiProviderRouter::build_content_params($prompt);

		/** 4. Run provider */
		$response = SftcyWordaiAiProviderRouter::generate_content($api_params);

		if (is_wp_error($response)) {
			wp_send_json([
				'status'      => 'fail',
				'errorMessage'=> $response->get_error_message(),
			]);
		}

		/** 5. Normalize success response */
		if (isset($response['status']) && $response['status'] === 'success') {

			// Remove markdown, hashes, *, underscores, formatting
			$clean = SftcyWordaiBase::sc_wordai_strip_markdown($response['responseText']);

			// Remove unnecessary quotes/newlines
			$clean = preg_replace('/[\n\r\"]+/', ' ', $clean);

			// Final trim
			$response['responseText'] = trim($clean);

			// Output with <br/> for UI panel
			$response['responseTextWithBR'] = nl2br($response['responseText']);
		}

		wp_send_json($response);
	}


	/**
	 * Write SEO Meta Focus Keyword
	 * return - json
	 * @since 1.0.0
	 */
	// public static function sc_wordai_write_seo_meta_focus_keyword() {
	// 	check_ajax_referer( 'scwordai_wpnonce', 'security' );						
	// 	$prompt_hints			= isset( $_POST['params']['prompt'] )? sanitize_text_field( $_POST['params']['prompt'] ) : '';				
	// 	$prompt					= SftcyWordaiOpenai::generate_prompt( trim( $prompt_hints ), 'seometafocuskeyword' );		
	// 	$api_params				= SftcyWordaiOpenai::set_openai_params();	
	// 	//$api_params['prompt']	= $prompt;
	// 	$api_params['messages']	= [ array('role' => 'user', 'content' => $prompt ) ];
		
	// 	//var_dump( $api_params );						
		
	// 	$response				= SftcyWordaiOpenai::create_content( $api_params);		
	// 	// var_dump( SftcyWordaiOpenai::$output );	
	// 	// exit;
		
	// 	// --- Process Output ---
	// 	if ( isset( SftcyWordaiOpenai::$output['status'] ) && SftcyWordaiOpenai::$output['status'] === 'success' ) {

	// 			$focus_keyword = trim( SftcyWordaiOpenai::$output['responseText'] );

	// 			// Sanitize and clean up unwanted characters
	// 			$focus_keyword = preg_replace( '/["\n\r\t]+/', '', $focus_keyword );
	// 			$focus_keyword = sanitize_text_field( $focus_keyword );

	// 			// Add it back to response for frontend
	// 			SftcyWordaiOpenai::$output['responseText'] = $focus_keyword;
	// 			SftcyWordaiOpenai::$output['focus_keyword'] = $focus_keyword;
	// 	}		
		
	// 	echo wp_json_encode( SftcyWordaiOpenai::$output );		
	// 	wp_die();
	// }

	/**
	 * ======================================================================
	 * AJAX: Generate SEO Meta Focus Keyword (Router + OpenAI + Gemini)
	 * ======================================================================
	 */
	public static function sc_wordai_write_seo_meta_focus_keyword() {

		check_ajax_referer('scwordai_wpnonce', 'security');

		/** 1. Read input */
		$prompt_raw = isset($_POST['params']['prompt'])
			? sanitize_text_field($_POST['params']['prompt'])
			: '';

		if (empty(trim($prompt_raw))) {
			wp_send_json([
				'status'      => 'fail',
				'errorMessage'=> __('Prompt is empty.', 'wordai-pro'),
			]);
		}

		/** 2. Build keyword-specific prompt */
		$prompt = SftcyWordaiOpenai::generate_prompt(
			trim($prompt_raw),
			'seometafocuskeyword'
		);

		/** 3. Build provider-aware API parameters */
		$api_params = SftcyWordaiAiProviderRouter::build_content_params($prompt);

		/** 4. Route to correct provider (OpenAI/Gemini) */
		$response = SftcyWordaiAiProviderRouter::generate_content($api_params);

		/** 5. Error handling */
		if (is_wp_error($response)) {
			wp_send_json([
				'status'      => 'fail',
				'errorMessage'=> $response->get_error_message(),
			]);
		}

		/** 6. Success output cleaning */
		if (isset($response['status']) && $response['status'] === 'success') {

			// Remove markdown formatting
			$clean = SftcyWordaiBase::sc_wordai_strip_markdown($response['responseText']);

			// One-line keyword — remove breaks/quotes
			$clean = preg_replace('/[\n\r\"\t]+/', ' ', $clean);
			$clean = sanitize_text_field($clean);

			$response['responseText']  = trim($clean);
			$response['focus_keyword'] = trim($clean);
		}

		wp_send_json($response);
	}

	/**
	 * AJAX: Generate SEO-friendly image alt text.
	 */
	public static function sc_wordai_write_image_alt_text() {

		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		if ( class_exists( 'SftcyWordaiFeatures' ) && ! SftcyWordaiFeatures::wordai_is_feature_available( 'seo_generation_options' ) ) {
			wp_send_json( array(
				'status'       => 'fail',
				'errorMessage' => __( 'Image alt text generation is available in WordAI Pro.', 'wordai' ),
			) );
		}

		$prompt_raw = isset( $_POST['params']['prompt'] )
			? sanitize_text_field( wp_unslash( $_POST['params']['prompt'] ) )
			: '';

		if ( '' === trim( $prompt_raw ) ) {
			wp_send_json( array(
				'status'       => 'fail',
				'errorMessage' => __( 'Prompt is empty.', 'wordai' ),
			) );
		}

		$prompt     = SftcyWordaiOpenai::generate_prompt( trim( $prompt_raw ), 'imagealttext' );
		$api_params = SftcyWordaiAiProviderRouter::build_content_params( $prompt );
		$response   = SftcyWordaiAiProviderRouter::generate_content( $api_params );

		if ( is_wp_error( $response ) ) {
			wp_send_json( array(
				'status'       => 'fail',
				'errorMessage' => $response->get_error_message(),
			) );
		}

		if ( isset( $response['status'] ) && 'success' === $response['status'] ) {
			$clean = isset( $response['responseText'] ) ? $response['responseText'] : '';
			$clean = SftcyWordaiBase::sc_wordai_strip_markdown( $clean );
			$clean = html_entity_decode( wp_strip_all_tags( $clean ), ENT_QUOTES, get_bloginfo( 'charset' ) );
			$clean = preg_replace( '/[\r\n\t"]+/', ' ', $clean );
			$clean = preg_replace( "/[']+/", '', $clean );
			$clean = preg_replace( '/\s+/', ' ', $clean );
			$clean = trim( $clean, " \t\n\r\0\x0B.,;:-" );
			$clean = sanitize_text_field( $clean );
			$clean = self::sc_wordai_trim_alt_text( $clean );

			$response['responseText']       = $clean;
			$response['responseTextWithBR'] = esc_html( $clean );
		}

		wp_send_json( $response );
	}
	


	/**
	 * Ajax Request
	 * Generate image
	 * Both streaming & non-streaming
	 * Ref: https://platform.openai.com/docs/api-reference/images/create#images_create-response_format
	 * The format in which generated images with 'dall-e-2' and 'dall-e-3' are returned. Must be one of url or b64_json. 
	 * URLs are only valid for 60 minutes after the image has been generated. This parameter isn't supported for 'gpt-image-1' which will always return base64-encoded images
	 * Output Response format Ref: https://platform.openai.com/docs/api-reference/images/create#images_create-response_format
	 * 'gpt-image-1' returns 'b64_json' as default - 'dall-e-2' & 'dall-e-3' models default response format 'url' but if set 'b64_json' then returns base64 encoded data
     * 'dall-e-2' & 'dall-e-3' models 'response_format' sets as 'b64_json'
	 * @since 1.0.0
	 */
	// public static function sc_wordai_generate_image() {
	// 	check_ajax_referer( 'scwordai_wpnonce', 'security' );
	// 	$api_image_params			= [];
	// 	$prompt_hints				= isset( $_POST['params']['prompt'] )? sanitize_text_field( $_POST['params']['prompt'] ) : '';		
	// 	$prompt						= SftcyWordaiOpenai::generate_prompt( trim( $prompt_hints ), 'image' );	
	// 	$api_image_params			= SftcyWordaiOpenai::set_openai_image_params();	
	// 	$api_image_params['prompt']	= $prompt;
	// 	$selected_image_model       = isset( $api_image_params['model'] )? $api_image_params['model'] : '';	
	// 	// $prompt_slug				= preg_replace( '/[\s]+/', '-', strtolower( trim( $prompt_hints ) ) );			
	// 	$prompt_slug				= self::sanitize_prompt_slug( $prompt_hints );
	// 	$upload_dir 			    = wp_upload_dir();

	// 	// Start Test Base64 encoded string data //
	// 	/***
	// 	$test_img_filename = 'woocommerce-placeholder.png';
	// 	$test_img_filename = 'Tax-Submission-2024-2025.jpeg';
	// 	$test_img_filename = 'Remitly-Payment-Screenshot 2025-08-21 164049.jpg';
    // 	$wp_dir_img_file = $upload_dir['basedir'] . '/' . $test_img_filename;		
	// 	$base64_encoded = base64_encode( file_get_contents( $wp_dir_img_file ) );		
	// 	$base64_decoded = base64_decode( $base64_encoded );
	// 	// Create a new Fileinfo resource
    // 	$finfo = new finfo(FILEINFO_MIME_TYPE);
    // 	// Get the MIME type from the decoded data
    // 	$mime_type = $finfo->buffer( $base64_decoded );		
	// 	$img_ext = explode( '/', $mime_type )[1];
	// 	var_dump( $mime_type ); // 'image/png' | 'image/jpeg' 
	// 	var_dump( $img_ext ); // 'png' | 'jpeg'
	// 	$tmp_img_filename = 'image-' . time() . '.' . strtolower( $img_ext ); // Generate a unique filename
	// 	$temp_file_path = $upload_dir['path'] . '/' . $tmp_img_filename;
	// 	$temp_file_url  = $upload_dir['url'] . '/' . $tmp_img_filename;
    // 	file_put_contents( $temp_file_path, $base64_decoded );				

	// 	SftcyWordaiOpenai::$output = [];
	// 	$test_img_encoded_data['b64_json'] = $base64_encoded;
	// 	SftcyWordaiOpenai::$output['responseImageData'][] = $test_img_encoded_data;
	// 	SftcyWordaiOpenai::$output['status'] = 'success';
		
	// 	var_dump( $base64_encoded );		
	// 	var_dump( $temp_file_path );
	// 	var_dump( $temp_file_url );
	// 	var_dump( pathinfo( $temp_file_url, PATHINFO_EXTENSION ) );
	// 	exit;
	// 	***/
	// 	// End Test Base64 encoded string data //

	// 	$response				= SftcyWordaiOpenai::generate_image( $api_image_params );		
	// 	$images_url				= [];		
	// 	SftcyWordaiOpenai::$output['selectedImageModel'] = $selected_image_model; // Add selected image model	with output
	// 	if ( SftcyWordaiOpenai::$output['responseImageData'] ) {
	// 		foreach ( SftcyWordaiOpenai::$output['responseImageData'] as $image ) {
	// 			$temp_file_url = '';
	// 			if ( isset( $image['b64_json'] ) && ! empty( $image['b64_json'] ) ) {
	// 				$base64_decoded = base64_decode( $image['b64_json'] );
	// 				// Create a new Fileinfo resource
	// 				$finfo = new finfo(FILEINFO_MIME_TYPE);
	// 				// Get the MIME type from the decoded data
	// 				$mime_type = $finfo->buffer( $base64_decoded );	// 'image/png' | 'image/jpeg'	
	// 				$img_ext = explode( '/', $mime_type )[1];       // 'png' | 'jpeg'
	// 				// Generate a unique filename
	// 				$random_string = bin2hex( random_bytes(6) );    // Generate a random string to add with image name
	// 				$tmp_img_filename = $prompt_slug . '-' . time() . '-' . $random_string  . '.' . strtolower( $img_ext ); 
	// 				$temp_file_path = $upload_dir['path'] . '/' . $tmp_img_filename;
	// 				$temp_file_url  = $upload_dir['url'] . '/' . $tmp_img_filename;
	// 				file_put_contents( $temp_file_path, $base64_decoded ); // Write base64 decoded data into image file inside media gallery	
	// 			}						
	// 			$images_url[] = $temp_file_url;
	// 		} // foreach
	// 		// SftcyWordaiOpenai::$output['openAIImgURLs']	= implode( ',', $images_url );	
	// 		SftcyWordaiOpenai::$output['openAIImgURLs']	= $images_url;				
	// 	}
		
	// 	// var_dump( SftcyWordaiOpenai::$output );
	// 	// exit;
	// 	echo wp_json_encode( SftcyWordaiOpenai::$output );		
	// 	wp_die();		
	// }
	

	/**
	 * Ajax Request
	 * Generate image (OpenAI + Gemini via router)
	 *
	 * Both streaming toggles share same image endpoint
	 * Images themselves are non-streaming.
	 *
	 * @since 1.0.0
	 */
	public static function sc_wordai_generate_image() {

		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		$prompt_hints = isset( $_POST['params']['prompt'] )
			? sanitize_text_field( $_POST['params']['prompt'] )
			: '';

		if ( empty( $prompt_hints ) ) {
			echo wp_json_encode( [
				'status'      => 'fail',
				'errorMessage'=> __( 'Image prompt is empty.', 'wordai-pro' ),
			] );
			wp_die();
		}

		/**
		 * ---------------------------------------------------------------------
		 * 1️⃣  Build the FINAL prompt using your existing system (do NOT change)
		 * ---------------------------------------------------------------------
		 */
		$image_subject = self::sc_wordai_extract_image_subject( $prompt_hints );
		$prompt        = SftcyWordaiOpenai::generate_prompt( $image_subject, 'image' );
		$prompt_slug   = self::sanitize_prompt_slug( $image_subject );
		$upload_dir  = wp_upload_dir();

		/**
		 * ---------------------------------------------------------------------
		 * 2️⃣ Build provider-aware params
		 * ---------------------------------------------------------------------
		 */
		$api_image_params = SftcyWordaiAiProviderRouter::build_image_params( $prompt );

		// echo '<pre>';
		// print_r( $api_image_params );
		// echo '</pre>';
		// exit;

		if ( isset( $api_image_params['status'] ) && $api_image_params['status'] === 'fail' ) {
			echo wp_json_encode( [
				'status'      => 'fail',
				'errorMessage'=> $api_image_params['feedbackMsg']
					?? __( 'No valid AI provider for image generation.', 'wordai-pro' ),
			] );
			wp_die();
		}
		
		/**
		 * ---------------------------------------------------------------------
		 * 3️⃣ Call the provider (OpenAI or Gemini)
		 * ---------------------------------------------------------------------
		 */
		$response = SftcyWordaiAiProviderRouter::generate_image( $api_image_params );

		if ( is_wp_error( $response ) ) {
			echo wp_json_encode( [
				'status'      => 'fail',
				'errorMessage'=> $response->get_error_message(),
			] );
			wp_die();
		}

		$status = $response['status'] ?? 'fail';
		$image_blobs = ! empty( $response['responseImageData'] ) && is_array( $response['responseImageData'] )
			? $response['responseImageData']
			: [];

		if ( $status !== 'success' ) {
			echo wp_json_encode([
				'status'      => 'fail',
				'errorType'   => $response['errorType'] ?? '',
				'errorMessage'=> $response['errorMessage']
					?? __('Failed to generate image.', 'wordai-pro'),
				'selectedImageModel' => $response['selectedImageModel'] ?? ( $response['model'] ?? '' ),
			]);
			wp_die();
		}

		/**
		 * ---------------------------------------------------------------------
		 * 4️⃣ Convert base64 → files
		 * ---------------------------------------------------------------------
		 */
		$images_url = [];

		foreach ( $image_blobs as $image ) {

			if ( empty( $image['b64_json'] ) ) {
				continue;
			}

			$base64_decoded = base64_decode( $image['b64_json'] );

			/**
			 * -------------------------------------------------------------
			 * 4.1️⃣ Determine MIME type:
			 *  - Gemini → mimeType key
			 *  - OpenAI → detect with finfo
			 * -------------------------------------------------------------
			 */
			if ( ! empty( $image['mimeType'] ) ) {
				// Gemini native MIME support
				$mime_type = $image['mimeType'];
			} else {
				// OpenAI fallback
				$finfo     = new finfo( FILEINFO_MIME_TYPE );
				$mime_type = $finfo->buffer( $base64_decoded );
			}

			/**
			 * -------------------------------------------------------------
			 * 4.2️⃣ Get extension from MIME
			 * -------------------------------------------------------------
			 */
			$img_ext = 'png'; // fallback

			if ( ! empty( $mime_type ) && strpos( $mime_type, '/' ) !== false ) {
				$parts   = explode( '/', $mime_type );
				$img_ext = strtolower( $parts[1] );
			}

			// Normalize
			if ( $img_ext === 'jpeg' ) {
				$img_ext = 'jpg';
			}

			/**
			 * -------------------------------------------------------------
			 * 4.3️⃣ Build filename
			 * -------------------------------------------------------------
			 */
			$random_string    = bin2hex( random_bytes( 6 ) );
			$tmp_img_filename = $prompt_slug . '-' . time() . '-' . $random_string . '.' . $img_ext;

			$temp_file_path = trailingslashit( $upload_dir['path'] ) . $tmp_img_filename;
			$temp_file_url  = trailingslashit( $upload_dir['url'] )  . $tmp_img_filename;

			$bytes_written = file_put_contents( $temp_file_path, $base64_decoded );

			if ( false === $bytes_written || ! file_exists( $temp_file_path ) ) {
				continue;
			}

			$images_url[] = $temp_file_url;
		}

		if ( empty( $images_url ) ) {
			echo wp_json_encode( [
				'status'      => 'fail',
				'errorMessage'=> __( 'Failed to write image files.', 'wordai-pro' ),
			] );
			wp_die();
		}

		/**
		 * ---------------------------------------------------------------------
		 * 5️⃣ Final output (must match your JS format)
		 * ---------------------------------------------------------------------
		 */
		$selected_image_model =
			$response['selectedImageModel']
			?? ( $response['model'] ?? '' );

		$output = [
			'status'             => 'success',
			'openAIImgURLs'      => $images_url,
			'selectedImageModel' => $selected_image_model,
		];

		if ( ! empty( $response['wordAIAPIKeyMissing'] ) ) {
			$output['wordAIAPIKeyMissing'] = $response['wordAIAPIKeyMissing'];
		}

		if ( ! empty( $response['errorMessage'] ) ) {
			$output['errorMessage'] = $response['errorMessage'];
		}

		echo wp_json_encode( $output );
		wp_die();
	}



	/**
	 * Allowd raw images
	 *
	 * @param $settings
	 * @return $settings
	 */
	public static function sc_wordai_image_upload_mime_type_issue( $settings ) {
		if (defined('ALLOW_UNFILTERED_UPLOADS') ) {
			unset($settings['filters']['mime_types']);
		}		
		return $settings;
	}
	
	/**
	 * Ajax Request
	 * @param Array POST
	 * POST['params'] hold all required data
	 * @since 1.0.0
	 */
	// public static function sc_wordai_upload_image_to_wp_media() {								
	// 	check_ajax_referer( 'scwordai_wpnonce', 'security' );
	// 	self::$output							= [];				
	// 	$post_id								= sanitize_text_field( $_POST['params']['postID'] );			
	// 	$image_model                            = sanitize_text_field( $_POST['params']['imageModel'] );
	// 	// $post_title							= sanitize_text_field( $_POST['params']['postTitle'] );	
					
	// 	// $imgURLS								= isset( $_POST['params']['imgURLs'] ) ? sanitize_url( $_POST['params']['imgURLs'] ) : '';
	// 	// $images_url								= explode( ',', $imgURLS );

	// 	$imgURLS = isset($_POST['params']['imgURLs'])
	// 	? sanitize_text_field( wp_unslash($_POST['params']['imgURLs']) )
	// 	: '';
	// 	$images_url = array_filter( array_map( 'trim', explode( ',', $imgURLS ) ) );
	// 	$images_url = array_map( 'esc_url_raw', $images_url );


	// 	// array_walk( $images_url, function( &$value, $key ) { $value = sanitize_url( $value ); });		
	// 	array_walk( $images_url, function( &$value, $key ) { $value = esc_url_raw( $value ); });
	// 	$prompt									= isset( $_POST['params']['prompt'] )? sanitize_text_field( $_POST['params']['prompt'] ) : time() . '-image';
	// 	$prompt_slug							= preg_replace( '/[\s]+/', '-', $prompt );							
		
	// 	// $images_url array - image URLs - when base64 data decoded and stored into media gallery - urls directory structure [uploads/Year-Number/Month-Number/{image-file-name}] 
	// 	foreach ( $images_url as $image_url ) {						
	// 		self::$output['imgaesUploadInfo'][]	= self::sc_wordai_upload_image_to_media_gallery( $image_url, $prompt, $image_model );											
	// 	}
				
	// 	self::$output['totalImages']			= count( $images_url );
	// 	self::$output['totalSuccess']			= count ( array_filter( self::$output['imgaesUploadInfo'], function($eachArr) { if ( $eachArr['status'] == 'success') return true; }) );
	// 	self::$output['totalFail']			    = count ( array_filter( self::$output['imgaesUploadInfo'], function($eachArr) { if ( $eachArr['status'] == 'fail') return true; }) );
	// 	self::$output['attachmentIDs']			= array_map( function($eachArr) { if ( $eachArr['status'] == 'success') { return $eachArr['attachmentID'];} }, self::$output['imgaesUploadInfo'] );
	// 	self::$output['attachmentURLs']			= array_map( function($eachArr) { if ( $eachArr['status'] == 'success') { return $eachArr['attachmentURL'];} }, self::$output['imgaesUploadInfo'] );
		
	// 	self::$output['firstImageAttachmentID']	= reset( self::$output['attachmentIDs'] );
	// 	self::$output['firstImageAttachmentURL']= reset( self::$output['attachmentURLs'] );		
	// 	//self::$output['firstImageAtltText']		= update_post_meta(self::$output['firstImageAttachmentID'], '_wp_attachment_image_alt', 'Alt Text for prompt ' . $prompt );				
		
	// 	if ( self::$output['totalImages'] ==  self::$output['totalSuccess'] ) {
	// 		self::$output['status']				= 'success';
	// 		self::$output['statusMsg']          = 'All images uploaded.';
	// 	}
	// 	else if ( self::$output['totalSuccess'] > 0 ) {
	// 		self::$output['status']				= 'success';
	// 		self::$output['statusMsg']          = 'Total ' . self::$output['totalSuccess'] . ' success of ' . self::$output['totalImages'];
	// 	}
	// 	else {
	// 		self::$output['status']				= 'fail';
	// 	}
		
	// 	// print_r( self::$output );
	// 	echo wp_json_encode( self::$output );
	// 	wp_die();		
	// }
	
	public static function sc_wordai_upload_image_to_wp_media() {

		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		self::$output = [];

		$post_id     = isset( $_POST['params']['postID'] ) ? absint( $_POST['params']['postID'] ) : 0;
		$image_model = isset( $_POST['params']['imageModel'] ) ? sanitize_text_field( wp_unslash( $_POST['params']['imageModel'] ) ) : '';
		$set_featured = ! empty( $_POST['params']['setFeatured'] );

		$imgURLS = isset( $_POST['params']['imgURLs'] )
			? sanitize_text_field( wp_unslash( $_POST['params']['imgURLs'] ) )
			: '';

		$images_url = array_filter( array_map( 'trim', explode( ',', $imgURLS ) ) );
		$images_url = array_map( 'esc_url_raw', $images_url );

		$prompt = isset( $_POST['params']['prompt'] )
			? sanitize_text_field( wp_unslash( $_POST['params']['prompt'] ) )
			: ( time() . '-image' );

		$image_alt_text = isset( $_POST['params']['imageAltText'] )
			? sanitize_text_field( wp_unslash( $_POST['params']['imageAltText'] ) )
			: '';
		
		// error_log('WORDAI upload_image_to_wp_media prompt=' . print_r($prompt, true));
	

		self::$output['imgaesUploadInfo'] = [];

		foreach ( $images_url as $image_url ) {
			self::$output['imgaesUploadInfo'][] = self::sc_wordai_upload_image_to_media_gallery(
				$image_url,
				$prompt,
				$image_model,
				$post_id,
				$image_alt_text
			);
		}

		self::$output['totalImages']   = count( $images_url );
		self::$output['totalSuccess']  = count( array_filter( self::$output['imgaesUploadInfo'], function( $eachArr ) {
			return isset( $eachArr['status'] ) && $eachArr['status'] === 'success';
		} ) );
		self::$output['totalFail']     = count( array_filter( self::$output['imgaesUploadInfo'], function( $eachArr ) {
			return isset( $eachArr['status'] ) && $eachArr['status'] === 'fail';
		} ) );

		// ✅ Build clean arrays (no nulls)
		$attachment_ids  = [];
		$attachment_urls = [];

		foreach ( self::$output['imgaesUploadInfo'] as $eachArr ) {
			if ( isset( $eachArr['status'] ) && $eachArr['status'] === 'success' ) {
				if ( ! empty( $eachArr['attachmentID'] ) ) {
					$attachment_ids[] = absint( $eachArr['attachmentID'] );
				}
				if ( ! empty( $eachArr['attachmentURL'] ) ) {
					$attachment_urls[] = esc_url_raw( $eachArr['attachmentURL'] );
				}
			}
		}

		self::$output['attachmentIDs']  = $attachment_ids;
		self::$output['attachmentURLs'] = $attachment_urls;

		self::$output['firstImageAttachmentID']  = ! empty( $attachment_ids ) ? $attachment_ids[0] : 0;
		self::$output['firstImageAttachmentURL'] = ! empty( $attachment_urls ) ? $attachment_urls[0] : '';
		self::$output['featuredImageAttachmentID'] = 0;

		if ( $set_featured && $post_id && ! empty( self::$output['firstImageAttachmentID'] ) && current_user_can( 'edit_post', $post_id ) ) {
			$featured_set = set_post_thumbnail( $post_id, self::$output['firstImageAttachmentID'] );
			if ( false !== $featured_set ) {
				self::$output['featuredImageAttachmentID'] = self::$output['firstImageAttachmentID'];
			}
		}

		if ( self::$output['totalImages'] === self::$output['totalSuccess'] && self::$output['totalImages'] > 0 ) {
			self::$output['status']    = 'success';
			self::$output['statusMsg'] = 'All images uploaded.';
		} elseif ( self::$output['totalSuccess'] > 0 ) {
			self::$output['status']    = 'success';
			self::$output['statusMsg'] = 'Total ' . self::$output['totalSuccess'] . ' success of ' . self::$output['totalImages'];
		} else {
			self::$output['status']       = 'fail';
			self::$output['errorMessage'] = 'No image uploaded successfully.';
		}

		echo wp_json_encode( self::$output );
		wp_die();
	}


	/**
	 * @param $image_url - image URL which is stored as image file into media gallery
	 * @param $prompt - users input
	 * @param $image_model - name fo the image model selected
	 * Base64 encoded Images data returned from OpenAI response are stored in media gallery as image file
	 * Insert image as attachment into WP DB records 
	 * @return array
	 * @since 1.0.0
	 */
	// public static function sc_wordai_upload_image_to_media_gallery( $image_url = null, $prompt = null, $image_model = null ) {
	// 	$output									= [];		
	// 	// Ref: https://platform.openai.com/docs/api-reference/images/create#images_create-response_format
	// 	// $url_data_response_models = [ 'dall-e-2', 'dall-e-3' ];
	// 	// $base64_data_response_models = [ 'gpt-image-1' ];	

	// 	if ( empty( $image_url ) || empty( $prompt ) || empty( $image_model ) ) {
	// 		$output['status']					= 'fail';	
	// 		$output['errorMessage']				= 'Image URL / Prompt / Image Model name missing!.';
	// 	}
	// 	else {
	// 		// Dependent files
	// 		require_once( ABSPATH . 'wp-admin/includes/image.php' );
	// 		require_once( ABSPATH . 'wp-admin/includes/file.php' );
	// 		require_once( ABSPATH . 'wp-admin/includes/media.php' );
								
	// 		$image_name = basename( $image_url ); // image-file-name.jpeg | image-file-name.png etc. 	
	// 		$upload_dir = wp_upload_dir();		
	// 		$upload_dir_image_file_path = $upload_dir['path'] . '/' . $image_name;	// Image directory path ( not $upload_dir['url'] URL )

	// 		// Sideload image to gallery - creating image thumbnails or variations
	// 		// $tmp = download_url( $image_url );
	// 		// $file_array 						= array(
	// 		// 										//'name'     => basename( $image_url ),
	// 		// 	                                    'name'     => $image_name, 
	// 		// 										'tmp_name' => $tmp
	// 		// );
	// 		// $id 								= media_handle_sideload( $file_array, 0 );									


	// 		// Attach downloaded image information - added into WP DB as attachment - not creating thumbnail versions or variations
	// 		// Prepare the attachment data array
	// 		$attachment_data = array(
	// 			'guid'           => $upload_dir_image_file_path,                                    // Recommended to include for URL generation
	// 			'post_mime_type' => mime_content_type( $upload_dir_image_file_path ),               // Get the MIME type
	// 			'post_title'     => $prompt,                                                        // Title for the attachment image
	// 			'post_content'   => $prompt,                                                        // Optional: Description for the attachment image
	// 			'post_status'    => 'inherit',                                                      // Status should be 'inherit' for attachments
	// 		);
			
	// 		// Define the parent post ID (0 if not associating with a specific post)
	// 		$parent_post_id = 0; 
	// 		// Insert the attachment into the database - return attachment_id 
	// 		$id = wp_insert_attachment( $attachment_data, $upload_dir_image_file_path, $parent_post_id );

	// 		// Check WP Error Object
	// 		if ( is_wp_error( $id ) ) {										
	// 			$output['attachmentID']			= $id;	
	// 			$output['status']				= 'fail';	
	// 			$output['errorMessage']			= $id->get_error_message();				
	// 		}
	// 		else {
	// 			$output['status']				= 'success';
	// 			$output['attachmentID']			= $id;				
	// 			$output['attachmentURL']		= $image_url;
	// 		}

	// 		// Unlink tmp
	// 		// @unlink( $tmp );		
	// 	}
		
	// 	return $output;			
	// }


	/**
	 * Upload/Register an image into WP Media Library (attachment)
	 * Assumes the image file already exists in the current uploads path.
	 *
	 * @since 1.0.0
	 */
	// public static function sc_wordai_upload_image_to_media_gallery( $image_url = null, $prompt = null, $image_model = null, $parent_post_id = 0 ) {

	// 	$output = [];

	// 	if ( empty( $image_url ) || empty( $prompt ) || empty( $image_model ) ) {
	// 		$output['status']       = 'fail';
	// 		$output['errorMessage'] = 'Image URL / Prompt / Image Model name missing!.';
	// 		return $output;
	// 	}

	// 	require_once ABSPATH . 'wp-admin/includes/image.php';
	// 	require_once ABSPATH . 'wp-admin/includes/file.php';
	// 	require_once ABSPATH . 'wp-admin/includes/media.php';

	// 	$image_name = basename( $image_url );

	// 	$upload_dir = wp_upload_dir();

	// 	// Physical file path expected
	// 	$file_path = trailingslashit( $upload_dir['path'] ) . $image_name;

	// 	// If file is not there, fail early (prevents broken attachments)
	// 	if ( ! file_exists( $file_path ) ) {
	// 		$output['status']       = 'fail';
	// 		$output['errorMessage'] = 'Image file not found in uploads path: ' . $file_path;
	// 		return $output;
	// 	}

	// 	// Correct URL
	// 	$file_url = trailingslashit( $upload_dir['url'] ) . $image_name;

	// 	$filetype = wp_check_filetype( $image_name, null );

	// 	$attachment_data = [
	// 		'guid'           => esc_url_raw( $file_url ),
	// 		'post_mime_type' => $filetype['type'] ? $filetype['type'] : 'image/jpeg',
	// 		'post_title'     => sanitize_text_field( $prompt ),
	// 		'post_content'   => sanitize_text_field( $prompt ),
	// 		'post_status'    => 'inherit',
	// 	];

	// 	$parent_post_id = absint( $parent_post_id );

	// 	$attachment_id = wp_insert_attachment( $attachment_data, $file_path, $parent_post_id );

	// 	if ( is_wp_error( $attachment_id ) ) {
	// 		$output['status']       = 'fail';
	// 		$output['errorMessage'] = $attachment_id->get_error_message();
	// 		return $output;
	// 	}

	// 	// ✅ VERY IMPORTANT: generate metadata (thumbnails/sizes) so admin preview updates reliably
	// 	$attach_meta = wp_generate_attachment_metadata( $attachment_id, $file_path );
	// 	if ( ! is_wp_error( $attach_meta ) && ! empty( $attach_meta ) ) {
	// 		wp_update_attachment_metadata( $attachment_id, $attach_meta );
	// 	}

	// 	$output['status']        = 'success';
	// 	$output['attachmentID']  = $attachment_id;
	// 	$output['attachmentURL'] = wp_get_attachment_url( $attachment_id );

	// 	return $output;
	// }


	/**
	 * Upload/Register an image into WP Media Library (attachment)
	 * Assumes the image file already exists in the current uploads path. 
	 * @param string|null $image_url
	 * @param string|null $prompt
	 * @param string|null $image_model
	 * @return array
	 */
	public static function sc_wordai_upload_image_to_media_gallery( $image_url = null, $prompt = null, $image_model = null, $parent_post_id = 0, $image_alt_text = '' ) {

		$output = [];

		if ( empty( $image_url ) || empty( $prompt ) || empty( $image_model ) ) {
			$output['status']       = 'fail';
			$output['errorMessage'] = 'Image URL / Prompt / Image Model name missing!.';
			return $output;
		}

		require_once ABSPATH . 'wp-admin/includes/image.php';
		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/media.php';

		$image_name = basename( $image_url );
		$upload_dir = wp_upload_dir();
		$upload_dir_image_file_path = $upload_dir['path'] . '/' . $image_name;

		if ( ! file_exists( $upload_dir_image_file_path ) ) {
			$output['status']       = 'fail';
			$output['errorMessage'] = 'Image file was not found in the uploads folder.';
			return $output;
		}

		// Prepare SEO strings from the normalized image subject, not the raw content prompt.
		$prompt_clean = self::sc_wordai_extract_image_subject( $prompt );
		$alt_text     = self::sc_wordai_trim_alt_text( $image_alt_text );
		if ( '' === $alt_text ) {
			$alt_text = self::sc_wordai_build_image_alt_text( $prompt, $parent_post_id );
		}
		$caption_text = mb_substr( $alt_text, 0, 180 );

		// Attachment post fields
		$attachment_data = array(
			'guid'           => $upload_dir_image_file_path,
			'post_mime_type' => ( file_exists( $upload_dir_image_file_path ) ? mime_content_type( $upload_dir_image_file_path ) : 'image/jpeg' ),
			'post_title'     => mb_substr( $prompt_clean, 0, 180 ),  // title
			'post_content'   => $prompt_clean,                       // description
			'post_excerpt'   => $caption_text,                       // ✅ caption
			'post_status'    => 'inherit',
		);

		$parent_post_id = absint( $parent_post_id );
		$id = wp_insert_attachment( $attachment_data, $upload_dir_image_file_path, $parent_post_id );

		if ( is_wp_error( $id ) ) {
			$output['attachmentID']  = $id;
			$output['status']        = 'fail';
			$output['errorMessage']  = $id->get_error_message();
			return $output;
		}

		// ✅ Set ALT text (attachment meta)
		update_post_meta( $id, '_wp_attachment_image_alt', $alt_text );

		// ✅ Optional: store model + raw prompt for later use/debug/SEO tools
		update_post_meta( $id, '_wordai_image_model', sanitize_text_field( $image_model ) );
		update_post_meta( $id, '_wordai_image_prompt', $prompt_clean );

		// ✅ Optional but recommended: generate attachment metadata (sizes) if file exists
		// This will NOT break anything if the file is present.
		if ( file_exists( $upload_dir_image_file_path ) ) {
			$attach_meta = wp_generate_attachment_metadata( $id, $upload_dir_image_file_path );
			if ( ! is_wp_error( $attach_meta ) && ! empty( $attach_meta ) ) {
				wp_update_attachment_metadata( $id, $attach_meta );
			}
		}

		$output['status']        = 'success';
		$output['attachmentID']  = $id;
		$output['attachmentURL'] = $image_url;
		$output['altText']       = $alt_text;

		return $output;
	}

	public static function sc_wordai_set_featured_image() {

		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		$post_id       = isset( $_POST['params']['postID'] ) ? absint( $_POST['params']['postID'] ) : 0;
		$attachment_id = isset( $_POST['params']['attachmentID'] ) ? absint( $_POST['params']['attachmentID'] ) : 0;

		if ( ! $post_id || ! $attachment_id || ! current_user_can( 'edit_post', $post_id ) ) {
			wp_send_json( array(
				'status'       => 'fail',
				'errorMessage' => __( 'Permission denied or missing image data.', 'wordai' ),
			) );
		}

		if ( ! wp_attachment_is_image( $attachment_id ) ) {
			wp_send_json( array(
				'status'       => 'fail',
				'errorMessage' => __( 'Selected media item is not a valid image.', 'wordai' ),
			) );
		}

		$result = set_post_thumbnail( $post_id, $attachment_id );

		if ( false === $result ) {
			wp_send_json( array(
				'status'       => 'fail',
				'errorMessage' => __( 'Featured image could not be updated.', 'wordai' ),
			) );
		}

		wp_send_json( array(
			'status'       => 'success',
			'attachmentID' => $attachment_id,
			'postID'       => $post_id,
			'statusMsg'    => __( 'Featured image updated.', 'wordai' ),
		) );
	}

	public static function sc_wordai_apply_image_alt_text() {

		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		if ( class_exists( 'SftcyWordaiFeatures' ) && ! SftcyWordaiFeatures::wordai_is_feature_available( 'seo_generation_options' ) ) {
			wp_send_json( array(
				'status'       => 'fail',
				'errorMessage' => __( 'Image alt text insertion is available in WordAI Pro.', 'wordai' ),
			) );
		}

		$post_id  = isset( $_POST['params']['postID'] ) ? absint( $_POST['params']['postID'] ) : 0;
		$alt_text = isset( $_POST['params']['imageAltText'] )
			? self::sc_wordai_trim_alt_text( wp_unslash( $_POST['params']['imageAltText'] ) )
			: '';

		if ( '' === $alt_text ) {
			wp_send_json( array(
				'status'       => 'fail',
				'errorMessage' => __( 'Generate or enter image alt text first.', 'wordai' ),
			) );
		}

		$attachment_ids = array();
		if ( isset( $_POST['params']['attachmentIDs'] ) ) {
			$posted_ids = wp_unslash( $_POST['params']['attachmentIDs'] );
			if ( is_array( $posted_ids ) ) {
				$attachment_ids = array_map( 'absint', $posted_ids );
			} else {
				$attachment_ids = array_map( 'absint', array_map( 'trim', explode( ',', (string) $posted_ids ) ) );
			}
		}

		if ( $post_id && has_post_thumbnail( $post_id ) ) {
			$attachment_ids[] = absint( get_post_thumbnail_id( $post_id ) );
		}

		$attachment_ids = array_values( array_unique( array_filter( $attachment_ids ) ) );

		if ( empty( $attachment_ids ) ) {
			wp_send_json( array(
				'status'       => 'fail',
				'errorMessage' => __( 'Save generated images to the Media Library before inserting alt text.', 'wordai' ),
			) );
		}

		if ( $post_id && ! current_user_can( 'edit_post', $post_id ) ) {
			wp_send_json( array(
				'status'       => 'fail',
				'errorMessage' => __( 'Permission denied for this post.', 'wordai' ),
			) );
		}

		$updated_ids = array();
		foreach ( $attachment_ids as $attachment_id ) {
			if ( ! wp_attachment_is_image( $attachment_id ) ) {
				continue;
			}

			if ( ! $post_id && ! current_user_can( 'edit_post', $attachment_id ) ) {
				continue;
			}

			update_post_meta( $attachment_id, '_wp_attachment_image_alt', $alt_text );
			$updated_ids[] = $attachment_id;
		}

		if ( empty( $updated_ids ) ) {
			wp_send_json( array(
				'status'       => 'fail',
				'errorMessage' => __( 'No saved generated images were available to update.', 'wordai' ),
			) );
		}

		wp_send_json( array(
			'status'        => 'success',
			'attachmentIDs' => $updated_ids,
			'statusMsg'     => sprintf(
				/* translators: %d: number of images. */
				_n( 'Image alt text inserted for %d image.', 'Image alt text inserted for %d images.', count( $updated_ids ), 'wordai' ),
				count( $updated_ids )
			),
		) );
	}

	private static function sc_wordai_extract_image_subject( $prompt_hints ) {

		$clean = html_entity_decode( wp_strip_all_tags( (string) $prompt_hints ), ENT_QUOTES, get_bloginfo( 'charset' ) );
		$clean = preg_replace( '/\s+/', ' ', $clean );
		$clean = trim( $clean, " \t\n\r\0\x0B\"'`.,;:-" );

		if ( '' === $clean ) {
			return 'WordAI generated image';
		}

		$patterns = array(
			'/Focus keyword:\s*([^.\n\r;]+)/i',
			'/Create\s+high-quality\s+WordPress\s+content\s+about\s+([^.\n\r]+)/i',
			'/Generate\s+(?:a|an)?\s*(?:high-quality\s+)?image\s+for\s+([^.\n\r]+)/i',
			'/Write\s+(?:an?\s+)?(?:SEO-friendly\s+)?(?:blog\s+post|article|content|page|product\s+content)\s+(?:about|for)\s+([^.\n\r]+)/i',
		);

		foreach ( $patterns as $pattern ) {
			if ( preg_match( $pattern, $clean, $matches ) && ! empty( $matches[1] ) ) {
				$subject = trim( $matches[1], " \t\n\r\0\x0B\"'`.,;:-" );
				if ( '' !== $subject ) {
					return mb_substr( self::sc_wordai_normalize_image_subject( $subject ), 0, 240 );
				}
			}
		}

		$clean = preg_replace( '/\b(Target audience|Content goal|Cover these key points|Call to action|Use it naturally|Keep the writing clear)[^.]*(?:\.|$)/i', '', $clean );
		$clean = self::sc_wordai_normalize_image_subject( $clean );

		return mb_substr( $clean, 0, 240 );
	}

	private static function sc_wordai_normalize_image_subject( $subject ) {
		$subject = wp_strip_all_tags( (string) $subject );
		$subject = preg_replace( '/\[[^\]]+\]/', '', $subject );
		$subject = preg_replace( '/\s+/', ' ', $subject );
		$subject = trim( $subject, " \t\n\r\0\x0B\"'`.,;:-" );

		return '' !== $subject ? $subject : 'WordAI generated image';
	}

	private static function sc_wordai_build_image_alt_text( $prompt_hints, $parent_post_id = 0 ) {

		$subject = self::sc_wordai_extract_image_subject( $prompt_hints );
		$subject = preg_replace( '/^(create|write|generate|make)\b[^a-z0-9]+/i', '', $subject );
		$subject = trim( $subject, " \t\n\r\0\x0B\"'`.,;:-" );

		$parent_post_id = absint( $parent_post_id );
		if ( $parent_post_id ) {
			$post_title = wp_strip_all_tags( get_the_title( $parent_post_id ) );
			if ( $post_title && ( '' === $subject || 'WordAI generated image' === $subject ) ) {
				$subject = $post_title;
			}
		}

		$alt_text = sprintf( 'Illustration about %s', $subject );
		$alt_text = preg_replace( '/\s+/', ' ', $alt_text );
		$alt_text = trim( $alt_text );

		return mb_substr( $alt_text, 0, 125 );
	}

	private static function sc_wordai_trim_alt_text( $alt_text ) {

		$alt_text = html_entity_decode( wp_strip_all_tags( (string) $alt_text ), ENT_QUOTES, get_bloginfo( 'charset' ) );
		$alt_text = preg_replace( '/[\r\n\t"]+/', ' ', $alt_text );
		$alt_text = preg_replace( "/[']+/", '', $alt_text );
		$alt_text = preg_replace( '/\s+/', ' ', $alt_text );
		$alt_text = trim( $alt_text, " \t\n\r\0\x0B.,;:-" );
		$alt_text = sanitize_text_field( $alt_text );

		if ( '' === $alt_text ) {
			return '';
		}

		if ( mb_strlen( $alt_text ) <= 125 ) {
			return $alt_text;
		}

		$trimmed = mb_substr( $alt_text, 0, 125 );
		$space   = mb_strrpos( $trimmed, ' ' );
		if ( false !== $space && $space > 60 ) {
			$trimmed = mb_substr( $trimmed, 0, $space );
		}

		return trim( $trimmed, " \t\n\r\0\x0B.,;:-" );
	}



	/**
	 * Sanitize Prompt String to Safe Slug (for image or file names)
	 *
	 * Converts a user-provided prompt into a lowercase, URL-safe, and filesystem-safe slug.
	 * Removes any characters not allowed in file names.
	 *
	 * Example:
	 * "AI Generated Image #1!" → "ai-generated-image-1"
	 *
	 * @param string $prompt_hints Raw user prompt or phrase.
	 * @param string $fallback Optional fallback slug if result becomes empty.
	 * @return string Safe, sanitized slug.
	 * @since 1.0.0
	 */
	public static function sanitize_prompt_slug( $prompt_hints, $fallback = 'wordai-image' ) {

		// --- Step 1: Normalize ---
		$slug = strtolower( trim( wp_strip_all_tags( $prompt_hints ) ) );

		// --- Step 2: Replace spaces/underscores with hyphens ---
		$slug = preg_replace( '/[\s_]+/', '-', $slug );

		// --- Step 3: Remove disallowed characters (keep a–z, 0–9, and hyphen) ---
		$slug = preg_replace( '/[^a-z0-9\-]/', '', $slug );

		// --- Step 4: Collapse multiple hyphens ---
		$slug = preg_replace( '/-+/', '-', $slug );

		// --- Step 5: Trim hyphens from ends ---
		$slug = trim( $slug, '-' );

		// --- Step 6: Fallback if empty ---
		if ( empty( $slug ) ) {
			$slug = sanitize_title( $fallback );
		}

		return $slug;
	}


			
				
} // End Class
}
?>
