<?php
/**
 * Shared settings helpers for Chatbot AI.
 *
 * @package Replyan_AI
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Replyan_AI_Settings {
	public const OPTION_NAME = 'replyan_ai_settings';
	public const NONCE_ACTION = 'replyan_ai_chat';
	public const SETTINGS_GROUP = 'replyan_ai_settings_group';
	public const SETTINGS_PAGE = 'replyan-ai';

	public static function defaults(): array {
		return array(
			'enabled'          => '1',
			'title'            => 'AI Assistant',
			'welcome_message'  => 'Hi! How can I help you today?',
			'placeholder'      => 'Type your question...',
			'api_key'                   => '',
			'api_key_enabled'           => '1',
			'anthropic_api_key'         => '',
			'anthropic_api_key_enabled' => '1',
			'gemini_api_key'            => '',
			'gemini_api_key_enabled'    => '1',
			'openrouter_api_key'        => '',
			'openrouter_api_key_enabled'=> '1',
			'model'                     => 'gpt-4o',
			'system_prompt'    => 'You are a helpful assistant for this website. Keep replies clear, friendly, and concise.',
			'temperature'      => '0.2',
			'max_tokens'       => '500',
			'position'         => 'bottom-right',
			'primary_color'    => '#2563eb',
			'auto_open'        => '0',
			'display_mode'     => 'floating',
			'settings_version' => '2',
			'default_agent_id' => 0,
			'embedding_provider' => '',
			'embedding_model'    => '',
			'similarity_threshold' => 0.75,
			'knowledge_sources'  => array( 'post', 'page' ),
			'index_permalinks'   => '1',
			'cpt_fields_config'  => array(),
			'enable_admin_sound' => '0',
			'admin_sound_file'   => '',
			'enable_user_sound'  => '0',
			'user_sound_file'    => '',
		);
	}

	public static function get(): array {
		return wp_parse_args( get_option( self::OPTION_NAME, array() ), self::defaults() );
	}

	public static function activate(): void {
		if ( false === get_option( self::OPTION_NAME, false ) ) {
			add_option( self::OPTION_NAME, self::defaults() );
		}
	}

	public static function maybe_upgrade(): void {
		$settings = get_option( self::OPTION_NAME, false );

		if ( ! is_array( $settings ) || isset( $settings['settings_version'] ) ) {
			return;
		}

		if ( isset( $settings['temperature'] ) && '0.7' === (string) $settings['temperature'] ) {
			$settings['temperature'] = '0.2';
		}

		$settings['settings_version'] = '2';
		update_option( self::OPTION_NAME, $settings );
	}

	public static function allowed_models(): array {
		return array(
			'gpt-4o-mini'                 => __( 'GPT-4o mini', 'replyan-ai' ),
			'gpt-4o'                      => __( 'GPT-4o', 'replyan-ai' ),
			'gpt-4.1-mini'                => __( 'GPT-4.1 mini', 'replyan-ai' ),
			'gpt-4.1'                     => __( 'GPT-4.1', 'replyan-ai' ),
			'gpt-5'                       => __( 'GPT-5', 'replyan-ai' ),
			'gpt-5-mini'                  => __( 'GPT-5 mini', 'replyan-ai' ),
			'claude-4-opus'               => __( 'Claude 4 Opus', 'replyan-ai' ),
			'claude-4-sonnet'             => __( 'Claude 4 Sonnet', 'replyan-ai' ),
			'claude-4-haiku'              => __( 'Claude 4 Haiku', 'replyan-ai' ),
			'claude-3-5-sonnet-20240620'  => __( 'Claude 3.5 Sonnet', 'replyan-ai' ),
			'claude-3-opus-20240229'      => __( 'Claude 3 Opus', 'replyan-ai' ),
			'claude-3-sonnet-20240229'    => __( 'Claude 3 Sonnet', 'replyan-ai' ),
			'claude-3-haiku-20240307'     => __( 'Claude 3 Haiku', 'replyan-ai' ),
			'gemini-2.0-flash'            => __( 'Gemini 2.0 Flash', 'replyan-ai' ),
			'gemini-2.5-flash'            => __( 'Gemini 2.5 Flash', 'replyan-ai' ),
			'gemini-2.5-pro'              => __( 'Gemini 2.5 Pro', 'replyan-ai' ),
		);
	}

	public static function sanitize( array $input ): array {
		$defaults = self::defaults();
		$current  = self::get();
		$output   = array();

		$output['enabled']          = empty( $input['enabled'] ) ? '0' : '1';
		$output['auto_open']        = empty( $input['auto_open'] ) ? '0' : '1';
		$output['display_mode']     = in_array( $input['display_mode'] ?? '', array( 'floating', 'shortcode' ), true ) ? $input['display_mode'] : $defaults['display_mode'];
		$output['title']            = sanitize_text_field( $input['title'] ?? $defaults['title'] );
		$output['welcome_message']  = sanitize_textarea_field( $input['welcome_message'] ?? $defaults['welcome_message'] );
		$output['placeholder']      = sanitize_text_field( $input['placeholder'] ?? $defaults['placeholder'] );
		$output['model']            = self::sanitize_model( $input['model'] ?? $defaults['model'] );
		$output['system_prompt']    = sanitize_textarea_field( $input['system_prompt'] ?? $defaults['system_prompt'] );
		$output['position']         = in_array( $input['position'] ?? '', array( 'bottom-right', 'bottom-left' ), true ) ? $input['position'] : $defaults['position'];
		$output['primary_color']    = sanitize_hex_color( $input['primary_color'] ?? $defaults['primary_color'] ) ?: $defaults['primary_color'];
		$output['temperature']      = (string) min( 2, max( 0, (float) ( $input['temperature'] ?? $defaults['temperature'] ) ) );
		$output['max_tokens']       = (string) min( 4000, max( 50, absint( $input['max_tokens'] ?? $defaults['max_tokens'] ) ) );
		$output['default_agent_id'] = absint( $input['default_agent_id'] ?? ( $current['default_agent_id'] ?? $defaults['default_agent_id'] ) );
		$output['knowledge_sources']= isset( $input['knowledge_sources'] ) && is_array( $input['knowledge_sources'] ) ? array_map( 'sanitize_text_field', $input['knowledge_sources'] ) : $defaults['knowledge_sources'];
		$output['index_permalinks'] = empty( $input['index_permalinks'] ) ? '0' : '1';
		if ( isset( $input['cpt_fields_config'] ) && is_array( $input['cpt_fields_config'] ) ) {
			$clean_cpt_config = array();
			foreach ( $input['cpt_fields_config'] as $cpt_key => $cpt_val ) {
				$clean_key = sanitize_key( $cpt_key );
				if ( ! empty( $clean_key ) && is_array( $cpt_val ) ) {
					$clean_cpt_config[ $clean_key ] = array(
						'include_content'   => ! empty( $cpt_val['include_content'] ),
						'include_permalink' => ! empty( $cpt_val['include_permalink'] ),
						'taxonomies'        => isset( $cpt_val['taxonomies'] ) && is_array( $cpt_val['taxonomies'] ) ? array_values( array_map( 'sanitize_text_field', $cpt_val['taxonomies'] ) ) : array(),
						'custom_fields'     => isset( $cpt_val['custom_fields'] ) && is_array( $cpt_val['custom_fields'] ) ? array_values( array_map( 'sanitize_text_field', $cpt_val['custom_fields'] ) ) : array(),
					);
				}
			}
			$output['cpt_fields_config'] = $clean_cpt_config;
		} else {
			$output['cpt_fields_config'] = $current['cpt_fields_config'] ?? array();
		}
		$output['embedding_provider']= sanitize_text_field( $input['embedding_provider'] ?? $defaults['embedding_provider'] );
		$output['embedding_model']   = sanitize_text_field( $input['embedding_model'] ?? $defaults['embedding_model'] );
		$output['similarity_threshold'] = (float) min( 0.99, max( 0.1, (float) ( $input['similarity_threshold'] ?? $defaults['similarity_threshold'] ) ) );
		$output['settings_version'] = '2';

		// Sound notification settings.
		$output['enable_admin_sound'] = empty( $input['enable_admin_sound'] ) ? '0' : '1';
		$output['admin_sound_file']   = sanitize_file_name( $input['admin_sound_file'] ?? '' );
		$output['enable_user_sound']  = empty( $input['enable_user_sound'] ) ? '0' : '1';
		$output['user_sound_file']    = sanitize_file_name( $input['user_sound_file'] ?? '' );

		$new_api_key    = sanitize_text_field( $input['api_key'] ?? '' );
		$delete_api_key = ( '1' === ( $input['api_key_delete'] ?? '0' ) );

		if ( $delete_api_key ) {
			$output['api_key']         = '';
			$output['api_key_enabled'] = '0';
		} elseif ( '' !== $new_api_key ) {
			$output['api_key']         = $new_api_key;
			$output['api_key_enabled'] = '1';
		} else {
			$output['api_key']         = $current['api_key'] ?? '';
			$output['api_key_enabled'] = empty( $input['api_key_enabled'] ) ? '0' : '1';
		}

		// Anthropic Key Handling
		$new_anthropic_key    = sanitize_text_field( $input['anthropic_api_key'] ?? '' );
		$delete_anthropic_key = ( '1' === ( $input['anthropic_api_key_delete'] ?? '0' ) );

		if ( $delete_anthropic_key ) {
			$output['anthropic_api_key']         = '';
			$output['anthropic_api_key_enabled'] = '0';
		} elseif ( '' !== $new_anthropic_key ) {
			$output['anthropic_api_key']         = $new_anthropic_key;
			$output['anthropic_api_key_enabled'] = '1';
		} else {
			$output['anthropic_api_key']         = $current['anthropic_api_key'] ?? '';
			$output['anthropic_api_key_enabled'] = empty( $input['anthropic_api_key_enabled'] ) ? '0' : '1';
		}

		// Gemini Key Handling
		$new_gemini_key    = sanitize_text_field( $input['gemini_api_key'] ?? '' );
		$delete_gemini_key = ( '1' === ( $input['gemini_api_key_delete'] ?? '0' ) );

		if ( $delete_gemini_key ) {
			$output['gemini_api_key']         = '';
			$output['gemini_api_key_enabled'] = '0';
		} elseif ( '' !== $new_gemini_key ) {
			$output['gemini_api_key']         = $new_gemini_key;
			$output['gemini_api_key_enabled'] = '1';
		} else {
			$output['gemini_api_key']         = $current['gemini_api_key'] ?? '';
			$output['gemini_api_key_enabled'] = empty( $input['gemini_api_key_enabled'] ) ? '0' : '1';
		}

		// OpenRouter Key Handling
		$new_openrouter_key    = sanitize_text_field( $input['openrouter_api_key'] ?? '' );
		$delete_openrouter_key = ( '1' === ( $input['openrouter_api_key_delete'] ?? '0' ) );

		if ( $delete_openrouter_key ) {
			$output['openrouter_api_key']         = '';
			$output['openrouter_api_key_enabled'] = '0';
		} elseif ( '' !== $new_openrouter_key ) {
			$output['openrouter_api_key']         = $new_openrouter_key;
			$output['openrouter_api_key_enabled'] = '1';
		} else {
			$output['openrouter_api_key']         = $current['openrouter_api_key'] ?? '';
			$output['openrouter_api_key_enabled'] = empty( $input['openrouter_api_key_enabled'] ) ? '0' : '1';
		}

		return $output;
	}

	private static function sanitize_model( string $model ): string {
		$allowed_models = array_keys( self::allowed_models() );

		if ( in_array( $model, $allowed_models, true ) ) {
			return $model;
		}

		if ( strpos( $model, 'openrouter/' ) === 0 ) {
			return sanitize_text_field( $model );
		}

		return self::defaults()['model'];
	}
}
