<?php
/**
 * Google Gemini Settings + AJAX class for WordAI.
 *
 * This class contains ONLY:
 *  - API key save/reset
 *  - API settings save/reset
 *  - Content settings save/reset
 *  - Image settings save/reset
 *  - Model lists & defaults for UI
 *
 * All low-level HTTP logic lives in SftcyWordaiGoogleGeminiApi.
 */

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

if ( ! class_exists( 'SftcyWordaiGoogleGeminiSettings' ) ) :

class SftcyWordaiGoogleGeminiSettings {

	/**
	 * Prevent multiple hook registration.
	 *
	 * @var bool
	 */
	protected static $initiated = false;

	/**
	 * Shared output container for AJAX responses.
	 *
	 * @var array
	 */
	public static $output = array();

	/**
	 * Constructor – registers all Gemini-related AJAX hooks.
	 */
	public function __construct() {
		if ( ! self::$initiated ) {
			self::initiate_hooks();
		}
	}

	/**
	 * Register AJAX actions for Gemini key & settings.
	 *
	 * @return void
	 */
	protected static function initiate_hooks() {

		// API Key Save
		add_action(
			'wp_ajax_wordai_google_gemini_api_key_data_save',
			array( __CLASS__, 'wordai_google_gemini_api_key_data_save' )
		);

		// API Settings Save / Reset
		add_action(
			'wp_ajax_sc_wordai_google_gemini_apisettings_data',
			array( __CLASS__, 'sc_wordai_google_gemini_apisettings_data' )
		);
		add_action(
			'wp_ajax_sc_wordai_google_gemini_apisettings_reset_data',
			array( __CLASS__, 'sc_wordai_google_gemini_apisettings_reset_data' )
		);

		// Content Settings Save / Reset
		add_action(
			'wp_ajax_sc_wordai_google_gemini_content_settings_data',
			array( __CLASS__, 'sc_wordai_google_gemini_content_settings_data' )
		);
		add_action(
			'wp_ajax_sc_wordai_google_gemini_content_settings_reset_data',
			array( __CLASS__, 'sc_wordai_google_gemini_content_settings_reset_data' )
		);

		// Image Settings Save / Reset
		add_action(
			'wp_ajax_sc_wordai_google_gemini_image_settings_data',
			array( __CLASS__, 'sc_wordai_google_gemini_image_settings_data' )
		);
		add_action(
			'wp_ajax_sc_wordai_google_gemini_image_settings_reset_data',
			array( __CLASS__, 'sc_wordai_google_gemini_image_settings_reset_data' )
		);

		self::$initiated = true;
	}

	/*───────────────────────────────────────────────────────────────
	| DEFAULT SETTINGS & MODEL LISTS
	───────────────────────────────────────────────────────────────*/

	/**
	 * Default Gemini API settings for content generation.
	 *
	 * Keys are aligned with your API Settings panel.
	 *
	 * @return array
	 */
	public static function get_default_gemini_settings() {
		return array(
			// Model selection
			'sc-wordai-gemini-model-slug' => SftcyWordaiGoogleGeminiApi::$MODEL,

			// Generation parameters
			'sc-wordai-temperature'       => 0.4,
			'sc-wordai-top-p'             => 0.9,
			'sc-wordai-max-tokens'        => 8192,
			// 'sc-wordai-max-tokens'        => null,

			// Penalties
			'sc-wordai-presence-penalty-input'  => 0.0,
			'sc-wordai-frequency-penalty-input' => 0.0,

			// Stop sequences
			'sc-wordai-stop-input'        => '',

			// Streaming toggle
			'sc-wordai-streaming'         => 0,
		);
	}

	/**
	 * Default Gemini image settings.
	 *
	 * @return array
	 */
	public static function sc_wordai_google_gemini_default_image_settings() {
		return array(
			'sc-wordai-gemini-image-model-slug' => SftcyWordaiGoogleGeminiApi::$IMAGE_MODEL,
			'sc-wordai-gemini-image-size'       => '1024x1024',
			'sc-wordai-gemini-image-style'      => 'photorealistic',
			'sc-wordai-gemini-image-quality'    => 'standard',
			'sc-wordai-gemini-image-mime'       => 'image/jpeg',

			// Save to gallery
			'sc-wordai-imagesave-togallery'     => 1,
			// Set as feature image
			'sc-wordai-set-feature-image'       => 1,

			// How many images to generate
			'sc-wordai-image-number'           => 2,
		);
	}

	/**
	 * Gemini content model list for dropdowns.
	 *
	 * @return array slug => label
	 */
	// public static function gemini_models() {
	// 	return array(
	// 		'gemini-2.5-flash-lite' => __( 'Gemini 2.5 Flash-Lite — Ultra Fast', 'wordai-pro' ),
	// 		'gemini-2.5-flash'      => __( 'Gemini 2.5 Flash — Fast & Intelligent (Recommended)', 'wordai-pro' ),
	// 		'gemini-2.5-pro'        => __( 'Gemini 2.5 Pro — Most Advanced Reasoning', 'wordai-pro' ),
	// 	);
	// }
	

	/**
	 * Gemini content model list for dropdowns (grouped).
	 *
	 * @return array
	 */
	// public static function gemini_models() {

	// 	return [
	// 		'🧠 Gemini 2.5 (Advanced Reasoning)' => [
	// 			'gemini-2.5-pro' => __( 'Gemini 2.5 Pro — Most Advanced Reasoning', 'wordai-pro' ),
	// 		],

	// 		'⚡ Gemini 2.5 (Fast & Recommended)' => [
	// 			'gemini-2.5-flash'      => __( 'Gemini 2.5 Flash — Fast & Intelligent (Recommended)', 'wordai-pro' ),
	// 			'gemini-2.5-flash-lite' => __( 'Gemini 2.5 Flash-Lite — Ultra Fast', 'wordai-pro' ),
	// 		],

	// 		'🧩 Gemini 2.0 (Previous Gen)' => [
	// 			'gemini-2.0-flash'     => __( 'Gemini 2.0 Flash — Previous Gen Fast', 'wordai-pro' ),
	// 			'gemini-2.0-flash-001' => __( 'Gemini 2.0 Flash-001 — Stable', 'wordai-pro' ),
	// 		],

	// 		'🧪 Experimental (Use Carefully)' => [
	// 			'gemini-2.0-flash-exp' => __( 'Gemini 2.0 Flash (Experimental)', 'wordai-pro' ),
	// 		],
	// 	];
	// }

	/**
	 * Gemini content model list for dropdowns (grouped).
	 *
	 * @return array
	 */
	public static function gemini_models() {

		return [
			'Gemini 3 (Stable & Recommended)' => [
				'gemini-3.5-flash'      => __( 'Gemini 3.5 Flash — Recommended', 'wordai-pro' ),
				'gemini-3.1-flash-lite' => __( 'Gemini 3.1 Flash-Lite — Lowest Cost', 'wordai-pro' ),
			],
			'Gemini 3 (Advanced Preview)' => [
				'gemini-3.1-pro-preview' => __( 'Gemini 3.1 Pro Preview — Advanced Reasoning', 'wordai-pro' ),
			],
			'Gemini 2.5 (Compatibility)' => [
				'gemini-2.5-flash'      => __( 'Gemini 2.5 Flash — Price/Performance', 'wordai-pro' ),
				'gemini-2.5-flash-lite' => __( 'Gemini 2.5 Flash-Lite — Budget Friendly', 'wordai-pro' ),
				'gemini-2.5-pro'        => __( 'Gemini 2.5 Pro — Advanced Reasoning', 'wordai-pro' ),
			],
		];
	}

	public static function normalize_gemini_model_slug( $model_slug = '' ) {
		$model_slug = sanitize_text_field( (string) $model_slug );
		$aliases = array(
			'gemini-3-flash-preview'        => 'gemini-3.5-flash',
			'gemini-3.1-flash-lite-preview' => 'gemini-3.1-flash-lite',
		);

		if ( isset( $aliases[ $model_slug ] ) ) {
			$model_slug = $aliases[ $model_slug ];
		}

		$allowed = array(
			'gemini-3.5-flash',
			'gemini-3.1-flash-lite',
			'gemini-3.1-pro-preview',
			'gemini-2.5-flash',
			'gemini-2.5-flash-lite',
			'gemini-2.5-pro',
		);

		if ( in_array( $model_slug, $allowed, true ) ) {
			return $model_slug;
		}

		return SftcyWordaiGoogleGeminiApi::$MODEL;
	}



	/**
	 * Gemini image generation models (Gemini API / API-key compatible)
	 *
	 * @return array slug => label
	 */
	public static function gemini_image_models() {

		return [
			'Gemini 3 Image' => [
				'gemini-3.1-flash-image'      => __( 'Gemini 3.1 Flash Image — Recommended', 'wordai-pro' ),
				'gemini-3.1-flash-lite-image' => __( 'Gemini 3.1 Flash-Lite Image — Lowest Cost', 'wordai-pro' ),
				'gemini-3-pro-image'           => __( 'Gemini 3 Pro Image — Professional Quality', 'wordai-pro' ),
			],

			'Gemini 2.5 Image (Compatibility)' => [
				'gemini-2.5-flash-image' => __( 'Gemini 2.5 Flash Image — Legacy Compatible', 'wordai-pro' ),
			],
		];
	}

	public static function normalize_gemini_image_model_slug( $model_slug = '' ) {
		$model_slug = sanitize_text_field( (string) $model_slug );
		$aliases    = array(
			'gemini-3.1-flash-image-preview' => 'gemini-3.1-flash-image',
			'gemini-3-pro-image-preview'     => 'gemini-3-pro-image',
			'gemini-2.5-flash-image-preview' => 'gemini-2.5-flash-image',
		);

		if ( isset( $aliases[ $model_slug ] ) ) {
			$model_slug = $aliases[ $model_slug ];
		}

		$allowed    = array(
			'gemini-3.1-flash-image',
			'gemini-3.1-flash-lite-image',
			'gemini-3-pro-image',
			'gemini-2.5-flash-image',
		);

		if ( in_array( $model_slug, $allowed, true ) ) {
			return $model_slug;
		}

		return SftcyWordaiGoogleGeminiApi::$IMAGE_MODEL;
	}



	/**
	 * Gemini image sizes used in dropdown.
	 *
	 * @return array
	 */
	public static function gemini_image_sizes() {
		return array(
			'512x512'   => '512 × 512 (Small Square)',
			'768x1024'  => '768 × 1024 (Portrait)',
			'1024x768'  => '1024 × 768 (Landscape)',
			'1024x1024' => '1024 × 1024 (Square)',
			'1536x1536' => '1536 × 1536 (Large Square)',
			'1536x1024' => '1536 × 1024 (Landscape)',
			'1024x1536' => '1024 × 1536 (Portrait)',
		);
	}

	/**
	 * Style presets for Gemini image prompts.
	 *
	 * @return array
	 */
	// public static function gemini_image_styles() {
	// 	return array(
	// 		'photorealistic' => __( 'Photorealistic', 'wordai-pro' ),
	// 		'illustration'   => __( 'Illustration', 'wordai-pro' ),
	// 		'anime'          => __( 'Anime / Stylized', 'wordai-pro' ),
	// 		'3d'             => __( '3D Render', 'wordai-pro' ),
	// 		'flat'           => __( 'Flat / Minimal', 'wordai-pro' ),
	// 	);
	// }

	/**
	 * Style presets for Gemini image prompts (UI only).
	 * Grouped for better UX.
	 *
	 * @return array groupLabel => [ slug => label ]
	 */
	public static function gemini_image_styles_grouped() {
		return [
			'Realistic' => [
				'photorealistic' => __( 'Photorealistic', 'wordai-pro' ),
				'cinematic'      => __( 'Cinematic / Film Look', 'wordai-pro' ),
				'product'        => __( 'Product Photo / Studio', 'wordai-pro' ),
				'architectural'  => __( 'Architectural / Interior', 'wordai-pro' ),
			],
			'Illustration & Art' => [
				'illustration' => __( 'Illustration', 'wordai-pro' ),
				'watercolor'   => __( 'Watercolor', 'wordai-pro' ),
				'oilpainting'  => __( 'Oil Painting', 'wordai-pro' ),
				'ink'          => __( 'Ink / Line Art', 'wordai-pro' ),
				'comic'        => __( 'Comic / Graphic Novel', 'wordai-pro' ),
			],
			'3D & Design' => [
				'3d'        => __( '3D Render', 'wordai-pro' ),
				'isometric' => __( 'Isometric', 'wordai-pro' ),
				'lowpoly'   => __( 'Low Poly', 'wordai-pro' ),
				'flat'      => __( 'Flat / Minimal', 'wordai-pro' ),
				'vector'    => __( 'Vector / SVG Style', 'wordai-pro' ),
			],
			'Stylized' => [
				'anime'      => __( 'Anime / Stylized', 'wordai-pro' ),
				'pixelart'   => __( 'Pixel Art', 'wordai-pro' ),
				'fantasy'    => __( 'Fantasy Art', 'wordai-pro' ),
				'cyberpunk'  => __( 'Cyberpunk', 'wordai-pro' ),
			],
		];
	}


	/**
	 * MIME types for Gemini image output.
	 *
	 * @return array
	 */
	public static function gemini_image_mime_types( $model_slug = '' ) {
		$model_slug = self::normalize_gemini_image_model_slug( $model_slug );

		if ( in_array( $model_slug, array( 'gemini-3.1-flash-image', 'gemini-3.1-flash-lite-image', 'gemini-3-pro-image' ), true ) ) {
			return array(
				'image/jpeg' => __( 'JPEG (Required for Gemini 3 Image API)', 'wordai-pro' ),
			);
		}

		return array(
			'image/png'  => __( 'PNG (Lossless, Best Quality)', 'wordai-pro' ),
			'image/jpeg' => __( 'JPEG (Compressed, Smaller Size)', 'wordai-pro' ),
			'image/webp' => __( 'WEBP (Modern, Lightweight)', 'wordai-pro' ),
		);
	}

	public static function normalize_gemini_image_mime_type( $mime, $model_slug = '' ) {
		$mime    = preg_replace( '/[^a-zA-Z0-9\/\-\+\.]/', '', (string) $mime );
		$allowed = array_keys( self::gemini_image_mime_types( $model_slug ) );

		return in_array( $mime, $allowed, true ) ? $mime : reset( $allowed );
	}

	/**
	 * Logical quality presets (you can map internally to different configs).
	 *
	 * @return array
	 */
	public static function gemini_image_qualities() {
		return array(
			'standard' => __( 'Standard Quality', 'wordai-pro' ),
			'high'     => __( 'High Quality', 'wordai-pro' ),
			'fast'     => __( 'Fast (Lower Cost)', 'wordai-pro' ),
		);
	}

	/*───────────────────────────────────────────────────────────────
	| AJAX HANDLERS – API KEY & API SETTINGS
	───────────────────────────────────────────────────────────────*/

	/**
	 * AJAX: Save Google Gemini API key safely.
	 *
	 * Expects:
	 *   - POST['realKey']
	 *
	 * Stores into:
	 *   - option: sftcy-wordai-google-gemini-apisettings-data
	 *       - wordai-google-gemini-api-key-data
	 *       - wordai-google-gemini-api-key-mask
	 *
	 * @return void
	 */
	public static function wordai_google_gemini_api_key_data_save() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		self::$output = array();

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

		$data       = class_exists( 'SftcyWordaiBase' ) ? SftcyWordaiBase::sc_wordai_get_current_api_settings() : array();
		$real_stored = isset( $data['wordai-google-gemini-api-key-data'] ) ? $data['wordai-google-gemini-api-key-data'] : '';
		$mask_value  = isset( $data['wordai-google-gemini-api-key-mask'] ) ? $data['wordai-google-gemini-api-key-mask'] : 'gm-********************';

		// Empty or using mask placeholder → invalid.
		if ( $input_key === '' || $input_key === $mask_value ) {
			if ( class_exists( 'SftcyWordaiSupport' ) ) {
				SftcyWordaiSupport::log_event( 'settings', 'error', 'google_api_key_invalid', 'Google Gemini API key save failed because no real API key was provided.', array( 'page' => 'api_settings' ), 'google', 'settings', 0 );
			}
			self::$output['status']      = 'fail';
			self::$output['feedbackMsg'] = __( 'Enter real Gemini API key.', 'wordai-pro' );
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Same as stored → nothing changed.
		if ( $input_key === $real_stored ) {
			self::$output['status']      = 'warning';
			self::$output['feedbackMsg'] = __( 'Nothing changes.', 'wordai-pro' );
			echo wp_json_encode( self::$output );
			wp_die();
		}

		// Save new key.
		$mask = class_exists( 'SftcyWordaiBase' )
			? SftcyWordaiBase::wordai_api_key_mask_format( $input_key, 'google' )
			: 'gm-********************';

		$options = array(
			'wordai-google-gemini-api-key-data' => $input_key,
			'wordai-google-gemini-api-key-mask' => $mask,
		);

		update_option( 'sftcy-wordai-google-gemini-apisettings-data', maybe_serialize( $options ) );

		self::$output = array(
			'status'      => 'success',
			'feedbackMsg' => __( 'API key saved successfully.', 'wordai-pro' ),
			'savedKey'    => $input_key,
			'savedMask'   => $mask,
		);

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

	/**
	 * AJAX: Save Google Gemini API settings (model, temperature, etc.).
	 *
	 * Expects:
	 *   - POST['postData'] : serialized form string.
	 *
	 * Writes into:
	 *   - option: sftcy-wordai-google-gemini-apisettings-data
	 *
	 * @return void
	 */
	public static function sc_wordai_google_gemini_apisettings_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		self::$output = array();

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

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

		$params['sc-wordai-streaming'] = 0;
		$params['sc-wordai-gemini-model-slug'] = self::normalize_gemini_model_slug( $params['sc-wordai-gemini-model-slug'] ?? '' );

		$option_name          = 'sftcy-wordai-google-gemini-apisettings-data';
		$is_option_data_added = get_option( $option_name );
		$existing             = $is_option_data_added ? maybe_unserialize( $is_option_data_added ) : array();

		if ( ! is_array( $existing ) ) {
			$existing = array();
		}

		$updated_options_data = array_merge( $existing, $params );
		$update_data          = update_option( $option_name, maybe_serialize( $updated_options_data ) );

		if ( $update_data ) {
			self::$output['status']      = 'success';
			self::$output['feedbackMsg'] = __( 'API Settings Parameter saved successfully.', 'wordai-pro' );
		} else {
			self::$output['status']      = 'warning';
			self::$output['feedbackMsg'] = __( 'Nothing Changes.', 'wordai-pro' );
		}

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

	/**
	 * AJAX: Reset Google Gemini API settings to defaults.
	 *
	 * @return void
	 */
	public static function sc_wordai_google_gemini_apisettings_reset_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		$default = self::get_default_gemini_settings();

		$is_option_data_added = get_option('sftcy-wordai-google-gemini-apisettings-data');
		$updated_options_data = $is_option_data_added ? array_merge( maybe_unserialize( $is_option_data_added ), $default ) : $default;

		$updated = update_option(
			'sftcy-wordai-google-gemini-apisettings-data',
			maybe_serialize( $updated_options_data )
		);

		if ( $updated ) {
			wp_send_json(
				array(
					'status'      => 'success',
					'feedbackMsg' => __( 'Google Gemini settings reset successfully.', 'wordai-pro' ),
				)
			);
		}

		wp_send_json(
			array(
				'status'      => 'warning',
				'feedbackMsg' => __( 'Nothing changed.', 'wordai-pro' ),
			)
		);
	}

	/*───────────────────────────────────────────────────────────────
	| AJAX HANDLERS – CONTENT SETTINGS
	───────────────────────────────────────────────────────────────*/

	/**
	 * AJAX: Save Gemini content settings.
	 *
	 * Mirrors OpenAI content settings, but stored separately:
	 *   option: sftcy-wordai-google-gemini-content-settings-data
	 *
	 * @return void
	 */
	public static function sc_wordai_google_gemini_content_settings_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		self::$output = array();

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

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

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

		// Social metadata defaults
		$params['sc-wordai-twitter-site']           = ! empty( $params['sc-wordai-twitter-site'] ) ? $params['sc-wordai-twitter-site'] : '@yourbrand';
		$params['sc-wordai-twitter-creator']        = ! empty( $params['sc-wordai-twitter-creator'] ) ? $params['sc-wordai-twitter-creator'] : '@creatorname';
		$params['sc-wordai-pinterest-verification'] = ! empty( $params['sc-wordai-pinterest-verification'] ) ? $params['sc-wordai-pinterest-verification'] : '';
		$params['sc-wordai-enable-pinterest-richpins'] = isset( $params['sc-wordai-enable-pinterest-richpins'] ) ? 1 : 0;

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

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

		$existing = get_option( 'sftcy-wordai-google-gemini-content-settings-data' );
		$updated  = $existing ? array_merge( maybe_unserialize( $existing ), $params ) : $params;

		$update_result = update_option(
			'sftcy-wordai-google-gemini-content-settings-data',
			maybe_serialize( $updated )
		);

		self::$output = array(
			'status'      => $update_result ? 'success' : 'warning',
			'feedbackMsg' => $update_result
				? __( 'Content settings saved successfully.', 'wordai-pro' )
				: __( 'Nothing Changed.', 'wordai-pro' ),
		);

		wp_send_json( self::$output );
	}

	/**
	 * AJAX: Reset Gemini content settings to defaults.
	 *
	 * Uses the SAME default parameters as OpenAI content settings.
	 *
	 * @return void
	 */
	public static function sc_wordai_google_gemini_content_settings_reset_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		self::$output = array();

		$default_params = class_exists( 'SftcyWordaiBase' )
			? SftcyWordaiBase::sc_wordai_api_content_settings_default_parameters()
			: array();
		if ( class_exists( 'SftcyWordaiFeatures' ) ) {
			$default_params = SftcyWordaiFeatures::wordai_apply_content_setting_limits( $default_params );
		}

		$update_result = update_option(
			'sftcy-wordai-google-gemini-content-settings-data',
			maybe_serialize( $default_params )
		);

		self::$output = array(
			'status'      => $update_result ? 'success' : 'warning',
			'feedbackMsg' => $update_result
				? __( 'Google Gemini content settings reset successfully.', 'wordai-pro' )
				: __( 'Nothing changed. Already default.', 'wordai-pro' ),
		);

		wp_send_json( self::$output );
	}

	/*───────────────────────────────────────────────────────────────
	| AJAX HANDLERS – IMAGE SETTINGS
	───────────────────────────────────────────────────────────────*/

	/**
	 * AJAX: Save Google Gemini image settings (with MIME-type safe handling).
	 *
	 * Stored in:
	 *   option: sftcy-wordai-google-gemini-image-settings-data
	 *
	 * @return void
	 */
	public static function sc_wordai_google_gemini_image_settings_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		self::$output = array();

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

		array_walk(
			$params,
			function ( &$v, $k ) {
				if ( 'sc-wordai-gemini-image-mime' === $k ) {
					// Allow MIME characters: letters, digits, /, -, +, .
					$v = preg_replace( '/[^a-zA-Z0-9\/\-\+\.]/', '', $v );
				} else {
					$v = sanitize_text_field( $v );
				}
			}
		);

		$params['sc-wordai-gemini-image-model-slug'] = self::normalize_gemini_image_model_slug( $params['sc-wordai-gemini-image-model-slug'] ?? '' );
		$params['sc-wordai-gemini-image-mime']       = self::normalize_gemini_image_mime_type(
			$params['sc-wordai-gemini-image-mime'] ?? '',
			$params['sc-wordai-gemini-image-model-slug']
		);

		// Checkboxes.
		$params['sc-wordai-imagesave-togallery'] = isset( $params['sc-wordai-imagesave-togallery'] ) ? 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-google-gemini-image-settings-data',
			maybe_serialize( $params )
		);

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

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

	/**
	 * AJAX: Reset Gemini image settings to defaults.
	 *
	 * @return void
	 */
	public static function sc_wordai_google_gemini_image_settings_reset_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		self::$output = array();

		$defaults = self::sc_wordai_google_gemini_default_image_settings();
		if ( class_exists( 'SftcyWordaiFeatures' ) ) {
			$defaults = SftcyWordaiFeatures::wordai_apply_image_setting_limits( $defaults );
		}

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

		self::$output['status']      = $updated ? 'success' : 'warning';
		self::$output['feedbackMsg'] = $updated
			? __( 'Gemini image settings have been reset to default values.', 'wordai-pro' )
			: __( 'Nothing changed.', 'wordai-pro' );

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

endif;
