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

if ( ! class_exists( 'SftcyWordaiAnthropicSettings' ) ) :

class SftcyWordaiAnthropicSettings {

	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_anthropic_api_key_data_save',
			[ __CLASS__, 'wordai_anthropic_api_key_data_save' ]
		);

		add_action(
			'wp_ajax_sc_wordai_anthropic_apisettings_data',
			[ __CLASS__, 'sc_wordai_anthropic_apisettings_data' ]
		);
		add_action(
			'wp_ajax_sc_wordai_anthropic_apisettings_reset_data',
			[ __CLASS__, 'sc_wordai_anthropic_apisettings_reset_data' ]
		);

		add_action(
			'wp_ajax_sc_wordai_anthropic_content_settings_data',
			[ __CLASS__, 'sc_wordai_anthropic_content_settings_data' ]
		);
		add_action(
			'wp_ajax_sc_wordai_anthropic_content_settings_reset_data',
			[ __CLASS__, 'sc_wordai_anthropic_content_settings_reset_data' ]
		);

		self::$initiated = true;
	}

	public static function get_default_anthropic_settings() {
		return [
			'sc-wordai-anthropic-model-slug'    => SftcyWordaiAnthropicApi::$MODEL,
			'sc-wordai-streaming'               => 0,
			'sc-wordai-temperature'             => 0.7,
			'sc-wordai-top-p'                   => 0.9,
			'sc-wordai-max-tokens'              => 2048,
			'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 anthropic_models() {
		return SftcyWordaiAnthropicApi::anthropic_models();
	}

	public static function normalize_anthropic_model_slug( $model = '' ) {
		return SftcyWordaiAnthropicApi::normalize_anthropic_model_slug( $model );
	}

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

		self::$output = [];

		$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-anthropic-api-key-data'] ?? '';
		$mask_value  = $data['wordai-anthropic-api-key-mask'] ?? 'sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

		if ( $input_key === '' || $input_key === $mask_value ) {
			if ( class_exists( 'SftcyWordaiSupport' ) ) {
				SftcyWordaiSupport::log_event( 'settings', 'error', 'anthropic_api_key_invalid', 'Anthropic Claude API key save failed because no real API key was provided.', array( 'page' => 'api_settings' ), 'anthropic', 'settings', 0 );
			}
			self::$output['status']      = 'fail';
			self::$output['feedbackMsg'] = __( 'Enter a real Anthropic Claude API key.', 'wordai-pro' );
			echo wp_json_encode( self::$output );
			wp_die();
		}

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

		$mask = class_exists( 'SftcyWordaiBase' )
			? SftcyWordaiBase::wordai_api_key_mask_format( $input_key, 'anthropic' )
			: 'sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

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

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

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

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

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

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

		self::$output = [];

		$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-anthropic-model-slug'] = self::normalize_anthropic_model_slug( $params['sc-wordai-anthropic-model-slug'] ?? '' );

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

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

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

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

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

		$defaults = self::get_default_anthropic_settings();
		$existing = get_option( 'sftcy-wordai-anthropic-apisettings-data' );
		$existing = $existing ? maybe_unserialize( $existing ) : [];
		$existing = is_array( $existing ) ? $existing : [];

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

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

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

		self::$output = [];

		$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-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;
		$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-anthropic-content-settings-data' );
		$existing = $existing ? maybe_unserialize( $existing ) : [];
		$existing = is_array( $existing ) ? $existing : [];

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

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

	public static function sc_wordai_anthropic_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-anthropic-content-settings-data',
			maybe_serialize( $defaults )
		);

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

endif;
