<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'SftcyWordaiXaiSettings' ) ) :

class SftcyWordaiXaiSettings {

	protected static $initiated = false;
	public static $output = [];

	public function __construct() {
		if ( ! self::$initiated ) {
			self::initiate_hooks();
		}
	}

	protected static function initiate_hooks() {
		add_action( 'wp_ajax_wordai_xai_api_key_data_save', [ __CLASS__, 'wordai_xai_api_key_data_save' ] );
		add_action( 'wp_ajax_sc_wordai_xai_apisettings_data', [ __CLASS__, 'sc_wordai_xai_apisettings_data' ] );
		add_action( 'wp_ajax_sc_wordai_xai_apisettings_reset_data', [ __CLASS__, 'sc_wordai_xai_apisettings_reset_data' ] );
		add_action( 'wp_ajax_sc_wordai_xai_content_settings_data', [ __CLASS__, 'sc_wordai_xai_content_settings_data' ] );
		add_action( 'wp_ajax_sc_wordai_xai_content_settings_reset_data', [ __CLASS__, 'sc_wordai_xai_content_settings_reset_data' ] );
		add_action( 'wp_ajax_sc_wordai_xai_image_settings_data', [ __CLASS__, 'sc_wordai_xai_image_settings_data' ] );
		add_action( 'wp_ajax_sc_wordai_xai_image_settings_reset_data', [ __CLASS__, 'sc_wordai_xai_image_settings_reset_data' ] );

		self::$initiated = true;
	}

	public static function get_default_xai_settings() {
		return [
			'sc-wordai-xai-model-slug'            => SftcyWordaiXaiApi::$MODEL,
			'sc-wordai-streaming'                 => 0,
			'sc-wordai-temperature'               => 0.4,
			'sc-wordai-top-p'                     => 0.9,
			'sc-wordai-max-tokens'                => 4096,
			'sc-wordai-presence-penalty-input'    => 0.0,
			'sc-wordai-frequency-penalty-input'   => 0.0,
			'sc-wordai-best-of-input'             => 1,
			'sc-wordai-stop-input'                => '',
		];
	}

	public static function sc_wordai_xai_default_image_settings() {
		return [
			'sc-wordai-xai-image-model-slug'    => SftcyWordaiXaiApi::$IMAGE_MODEL,
			'sc-wordai-xai-image-aspect-ratio'  => 'auto',
			'sc-wordai-xai-image-resolution'    => '1k',
			'sc-wordai-imagesave-togallery'     => 1,
			'sc-wordai-set-feature-image'       => 1,
			'sc-wordai-image-number'            => 1,
		];
	}

	public static function xai_models() {
		return [
			'xAI Grok' => [
				'grok-4.5'        => 'Grok 4.5 (Recommended)',
				'grok-4.5-latest' => 'Grok 4.5 Latest',
			],
		];
	}

	public static function xai_model_slugs() {
		$slugs = [];
		foreach ( self::xai_models() as $models ) {
			$slugs = array_merge( $slugs, array_keys( $models ) );
		}
		return $slugs;
	}

	public static function normalize_xai_model_slug( $model = '' ) {
		$model = trim( (string) $model );
		return in_array( $model, self::xai_model_slugs(), true ) ? $model : SftcyWordaiXaiApi::$MODEL;
	}

	public static function xai_model_hints() {
		return [
			'grok-4.5'        => 'Grok 4.5 is the recommended xAI model for high-quality content, titles, and AI assistant replies.',
			'grok-4.5-latest' => 'Grok 4.5 Latest follows xAI latest-alias behavior for users who want newer Grok updates automatically.',
		];
	}

	public static function xai_model_hint( $model = '' ) {
		$model = self::normalize_xai_model_slug( $model );
		$hints = self::xai_model_hints();
		return $hints[ $model ] ?? $hints[ SftcyWordaiXaiApi::$MODEL ];
	}

	public static function xai_image_models() {
		return [
			'xAI Grok Imagine' => [
				'grok-imagine-image-quality' => 'Grok Imagine Image Quality',
				'grok-imagine-image'         => 'Grok Imagine Image',
			],
		];
	}

	public static function normalize_xai_image_model_slug( $model = '' ) {
		$model = trim( (string) $model );
		$allowed = [];
		foreach ( self::xai_image_models() as $models ) {
			$allowed = array_merge( $allowed, array_keys( $models ) );
		}
		return in_array( $model, $allowed, true ) ? $model : SftcyWordaiXaiApi::$IMAGE_MODEL;
	}

	public static function xai_image_aspect_ratios() {
		return [
			'auto'   => 'Auto',
			'1:1'    => 'Square 1:1',
			'16:9'   => 'Landscape 16:9',
			'9:16'   => 'Portrait 9:16',
			'4:3'    => 'Classic 4:3',
			'3:4'    => 'Portrait 3:4',
			'3:2'    => 'Photo 3:2',
			'2:3'    => 'Portrait 2:3',
			'2:1'    => 'Wide 2:1',
			'1:2'    => 'Tall 1:2',
			'19.5:9' => 'Mobile Wide 19.5:9',
			'9:19.5' => 'Mobile Tall 9:19.5',
			'20:9'   => 'Ultra Wide 20:9',
			'9:20'   => 'Ultra Tall 9:20',
		];
	}

	public static function normalize_xai_image_aspect_ratio( $ratio = '' ) {
		$ratio = trim( (string) $ratio );
		return array_key_exists( $ratio, self::xai_image_aspect_ratios() ) ? $ratio : 'auto';
	}

	public static function xai_image_resolutions() {
		return [
			'1k' => '1K',
			'2k' => '2K',
		];
	}

	public static function normalize_xai_image_resolution( $resolution = '' ) {
		$resolution = trim( (string) $resolution );
		return array_key_exists( $resolution, self::xai_image_resolutions() ) ? $resolution : '1k';
	}

	public static function wordai_xai_api_key_data_save() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );

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

		$data        = class_exists( 'SftcyWordaiBase' ) ? SftcyWordaiBase::sc_wordai_get_current_api_settings() : [];
		$real_stored = $data['wordai-xai-api-key-data'] ?? '';
		$mask_value  = $data['wordai-xai-api-key-mask'] ?? 'xai-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

		if ( $input_key === '' || $input_key === $mask_value ) {
			wp_send_json(
				[
					'status'      => 'fail',
					'feedbackMsg' => __( 'Enter a real xAI Grok API key.', 'wordai' ),
				]
			);
		}

		if ( $input_key === $real_stored ) {
			wp_send_json(
				[
					'status'      => 'warning',
					'feedbackMsg' => __( 'Nothing changes.', 'wordai' ),
				]
			);
		}

		$mask = class_exists( 'SftcyWordaiBase' )
			? SftcyWordaiBase::wordai_api_key_mask_format( $input_key, 'xai' )
			: 'xai-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

		$existing = get_option( 'sftcy-wordai-xai-apisettings-data' );
		$existing = $existing ? maybe_unserialize( $existing ) : [];
		$existing = is_array( $existing ) ? $existing : [];

		$updated = array_merge(
			$existing,
			[
				'wordai-xai-api-key-data' => $input_key,
				'wordai-xai-api-key-mask' => $mask,
			]
		);

		update_option( 'sftcy-wordai-xai-apisettings-data', maybe_serialize( $updated ) );

		wp_send_json(
			[
				'status'      => 'success',
				'feedbackMsg' => __( 'API key saved successfully.', 'wordai' ),
				'savedKey'    => $input_key,
				'savedMask'   => $mask,
			]
		);
	}

	public static function sc_wordai_xai_apisettings_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );
		$post_data = isset( $_POST['postData'] ) ? sanitize_text_field( wp_unslash( $_POST['postData'] ) ) : '';
		parse_str( $post_data, $params );
		$params = self::sanitize_flat_params( $params );

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

		$existing = get_option( 'sftcy-wordai-xai-apisettings-data' );
		$existing = $existing ? maybe_unserialize( $existing ) : [];
		$existing = is_array( $existing ) ? $existing : [];

		$updated = update_option( 'sftcy-wordai-xai-apisettings-data', maybe_serialize( array_merge( $existing, $params ) ) );

		wp_send_json(
			[
				'status'      => $updated ? 'success' : 'warning',
				'feedbackMsg' => $updated ? __( 'xAI Grok API settings saved successfully.', 'wordai' ) : __( 'Nothing Changes.', 'wordai' ),
			]
		);
	}

	public static function sc_wordai_xai_apisettings_reset_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );
		$defaults = self::get_default_xai_settings();
		$existing = get_option( 'sftcy-wordai-xai-apisettings-data' );
		$existing = $existing ? maybe_unserialize( $existing ) : [];
		$existing = is_array( $existing ) ? $existing : [];

		$updated = update_option( 'sftcy-wordai-xai-apisettings-data', maybe_serialize( array_merge( $existing, $defaults ) ) );

		wp_send_json(
			[
				'status'      => $updated ? 'success' : 'warning',
				'feedbackMsg' => $updated ? __( 'xAI Grok settings reset successfully.', 'wordai' ) : __( 'Nothing changed.', 'wordai' ),
			]
		);
	}

	public static function sc_wordai_xai_content_settings_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );
		$post_data = isset( $_POST['postData'] ) ? sanitize_text_field( wp_unslash( $_POST['postData'] ) ) : '';
		parse_str( $post_data, $params );
		$params = self::sanitize_flat_params( $params );

		foreach ( self::content_checkbox_keys() as $key ) {
			$params[ $key ] = isset( $params[ $key ] ) ? 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-xai-content-settings-data' );
		$existing = $existing ? maybe_unserialize( $existing ) : [];
		$existing = is_array( $existing ) ? $existing : [];

		$updated = update_option( 'sftcy-wordai-xai-content-settings-data', maybe_serialize( array_merge( $existing, $params ) ) );

		wp_send_json(
			[
				'status'      => $updated ? 'success' : 'warning',
				'feedbackMsg' => $updated ? __( 'xAI Grok content settings saved successfully.', 'wordai' ) : __( 'Nothing Changed.', 'wordai' ),
			]
		);
	}

	public static function sc_wordai_xai_content_settings_reset_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );

		$defaults = class_exists( 'SftcyWordaiBase' )
			? SftcyWordaiBase::sc_wordai_api_content_settings_default_parameters()
			: [];

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

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

		wp_send_json(
			[
				'status'      => $updated ? 'success' : 'warning',
				'feedbackMsg' => $updated ? __( 'xAI Grok content settings reset successfully.', 'wordai' ) : __( 'Nothing changed. Already default.', 'wordai' ),
			]
		);
	}

	public static function sc_wordai_xai_image_settings_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );
		$post_data = isset( $_POST['postData'] ) ? wp_unslash( $_POST['postData'] ) : '';
		parse_str( $post_data, $params );
		$params = self::sanitize_flat_params( $params );

		$params['sc-wordai-xai-image-model-slug']   = self::normalize_xai_image_model_slug( $params['sc-wordai-xai-image-model-slug'] ?? '' );
		$params['sc-wordai-xai-image-aspect-ratio'] = self::normalize_xai_image_aspect_ratio( $params['sc-wordai-xai-image-aspect-ratio'] ?? '' );
		$params['sc-wordai-xai-image-resolution']   = self::normalize_xai_image_resolution( $params['sc-wordai-xai-image-resolution'] ?? '' );
		$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;
		$params['sc-wordai-image-number']           = isset( $params['sc-wordai-image-number'] ) ? max( 1, min( 10, intval( $params['sc-wordai-image-number'] ) ) ) : 1;

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

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

		wp_send_json(
			[
				'status'      => $updated ? 'success' : 'warning',
				'feedbackMsg' => $updated ? __( 'xAI Grok image settings saved successfully.', 'wordai' ) : __( 'Nothing changed.', 'wordai' ),
			]
		);
	}

	public static function sc_wordai_xai_image_settings_reset_data() {
		check_ajax_referer( 'scwordai_wpnonce', 'security' );
		$updated = update_option( 'sftcy-wordai-xai-image-settings-data', maybe_serialize( self::sc_wordai_xai_default_image_settings() ) );

		wp_send_json(
			[
				'status'      => $updated ? 'success' : 'warning',
				'feedbackMsg' => $updated ? __( 'xAI Grok image settings have been reset to default values.', 'wordai' ) : __( 'Nothing changed.', 'wordai' ),
			]
		);
	}

	private static function sanitize_flat_params( array $params ) {
		foreach ( $params as $key => $value ) {
			$params[ $key ] = sanitize_text_field( $value );
		}
		return $params;
	}

	private static function content_checkbox_keys() {
		return [
			'sc-wordai-insert-title',
			'sc-wordai-insert-content',
			'sc-wordai-insert-excerpt',
			'sc-wordai-insert-tags',
			'sc-wordai-insert-seo-title',
			'sc-wordai-insert-seo-meta-description',
			'sc-wordai-insert-seo-meta-focus-keyword',
			'sc-wordai-use-seo-content-structure',
			'sc-wordai-use-heading-structure',
			'sc-wordai-use-seo-content-depth',
			'sc-wordai-use-people-first-content',
			'sc-wordai-use-trust-signals',
			'sc-wordai-use-content-freshness',
			'sc-wordai-enable-pinterest-richpins',
			'sc-wordai-enable-faq-section',
		];
	}
}

endif;
