<?php

/**
 * Common functions
 */
final class VAPPV_TTW_Common {

	/**
	 * Get user IP address based on HTTP request
	 * @return null|string
	 * @throws Exception
	 */
	public static function get_client_ip() {

		$params_to_lookup_list = array(
			'HTTP_CLIENT_IP',
			'HTTP_X_FORWARDED_FOR',
			'HTTP_X_FORWARDED',
			'HTTP_X_CLUSTER_CLIENT_IP',
			'HTTP_FORWARDED_FOR',
			'HTTP_FORWARDED',
			'REMOTE_ADDR'
		);

		foreach ( $params_to_lookup_list as $key ) {
			if ( true === array_key_exists( $key, $_SERVER ) ) {
				foreach ( array_map( 'trim', explode( ',', sanitize_text_field( wp_unslash( $_SERVER[ $key ] ) ) ) ) as $ip ) {
					if ( false !== filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) {
						return $ip;
					}
				}
			}
		}

		return null;
	}

	/**
	 * List OpenAI available models and save temp data into DB
	 * @return array
	 */
	public static function list_available_gpt_models(): array {

		//Create controllers
		$settings_controller = new VAPPV_TTW_Settings();
		$settings_controller->load_all_saved_settings();

		//Get OpenAI API address and key
		$openai_api_address = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_openai_api_address );
		$openai_api_key = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_openai_api_key );

		//Check is API key set
		if (
			is_null( $openai_api_key ) ||
			'' === $openai_api_key
		) {
			return VAPPV_TTW_Core::ajax_pack_error(
				'OPENAI_KEY_NOT_SET',
				esc_html(
					/* translators: plugin exception = OpenAI API key is not set */
					__( 'OpenAI API key is not set.', 'talk-to-website' )
				)
			);
		}

		//Try to get data via API
		$ttw_openai_api_controller = new VAPPV_TTW_OpenAI_API_Connector( $openai_api_address, $openai_api_key );
		$available_openai_models_response_data = $ttw_openai_api_controller->list_available_models();

		//Check API response / Try to locate OpenAI error
		if ( ! is_array( $available_openai_models_response_data ) ) {
			if (
				'VAPPV_TTW_OpenAI_API_Error' === get_class( $available_openai_models_response_data ) ||
				'VAPPV_TTW_Common_Error' === get_class( $available_openai_models_response_data )
			) {
				return VAPPV_TTW_Core::ajax_pack_error(
					'FAILED_TO_LIST_OPENAI_MODELS',
					sprintf(
						'%1$s // %2$s',
						esc_html(
							/* translators: plugin exception = failed to list OpenAI available models */
							__( 'Failed to list OpenAI available models.', 'talk-to-website' )
						),
						esc_html( $available_openai_models_response_data->message )
					)
				);
			}
		}

		//Save temp data into DB
		$settings_controller->update_setting( VAPPV_TTW_Settings::$settings_available_gpt_models, wp_json_encode( $available_openai_models_response_data ) );

		//Return results
		return VAPPV_TTW_Core::ajax_pack_success( $available_openai_models_response_data );
	}
}

/*
	© 2024 Copyright Vitalii A. Popov. All rights reserved.
*/

?>