<?php

/**
 * TTW statistics controller
 */
final class VAPPV_TTW_Statistics {

	/**
	 * Add stats to current date. Pass +1 to any param to increment value, 0 to skip addition,
	 *
	 * @param int $dialogues_count Daily dialogues count. Pass +1 to increment, 0 to skip.
	 * @param int $income_messages_count Daily messages count. Pass +1 to increment, 0 to skip.
	 * @param int $income_words_count Daily income words count. Pass +1 to increment, 0 to skip.
	 * @param int $income_characters_count Daily income characters count. Pass +1 to increment, 0 to skip.
	 * @param int $output_words_count Daily output words count. Pass +1 to increment, 0 to skip.
	 * @param int $output_characters_count Daily output characters count. Pass +1 to increment, 0 to skip.
	 * @param int $output_completion_tokens_count Daily output completion tokens count. Pass +1 to increment, 0 to skip.
	 *
	 * @return void
	 * @throws Exception
	 */
	public function add_stats(
		int $dialogues_count,
		int $income_messages_count,
		int $income_words_count,
		int $income_characters_count,
		int $output_words_count,
		int $output_characters_count,
		int $output_completion_tokens_count
	) {
		global $wpdb;

		//Prepare call to the DB table
		$db_tables_prefix                             = $wpdb->prefix;
		$wp_ttw_usage_statistics_table_name           = "{$db_tables_prefix}vappv_ttw_usage_statistics";
		$current_usage_statistics_entry_from_wpdb     = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE `tdate`=%s ORDER BY `id` DESC LIMIT 0, 1", array( $wp_ttw_usage_statistics_table_name, gmdate( "Y-m-d" ) ) ), ARRAY_A );

		//Analyse rows
		if (
			is_null( $current_usage_statistics_entry_from_wpdb ) ||
			0 === count( $current_usage_statistics_entry_from_wpdb )
		) {
			//Add new stat entry for this day
			$wpdb->insert(
				$wp_ttw_usage_statistics_table_name,
				array(
					'tdate'                          => gmdate( 'Y-m-d' ),
					'dialogues_count'                => $dialogues_count,
					'income_messages_count'          => $income_messages_count,
					'income_words_count'             => $income_words_count,
					'income_characters_count'        => $income_characters_count,
					'output_words_count'             => $output_words_count,
					'output_characters_count'        => $output_characters_count,
					'output_completion_tokens_count' => $output_completion_tokens_count
				)
			);
		} else {
			//Update current entry for this day
			$wpdb->update(
				$wp_ttw_usage_statistics_table_name,
				array(
					'dialogues_count'                => $current_usage_statistics_entry_from_wpdb[0]['dialogues_count'] + $dialogues_count,
					'income_messages_count'          => $current_usage_statistics_entry_from_wpdb[0]['income_messages_count'] + $income_messages_count,
					'income_words_count'             => $current_usage_statistics_entry_from_wpdb[0]['income_words_count'] + $income_words_count,
					'income_characters_count'        => $current_usage_statistics_entry_from_wpdb[0]['income_characters_count'] + $income_characters_count,
					'output_words_count'             => $current_usage_statistics_entry_from_wpdb[0]['output_words_count'] + $output_words_count,
					'output_characters_count'        => $current_usage_statistics_entry_from_wpdb[0]['output_characters_count'] + $output_characters_count,
					'output_completion_tokens_count' => $current_usage_statistics_entry_from_wpdb[0]['output_completion_tokens_count'] + $output_completion_tokens_count,
				),
				array(
					'id' => $current_usage_statistics_entry_from_wpdb[0]['id']
				)
			);
		}
	}

	/**
	 * Get current day stats
	 * @return array
	 * @throws Exception
	 */
	public function get_today_stats(): array {

		global $wpdb;

		//Prepare call to the DB table
		$db_tables_prefix                             = $wpdb->prefix;
		$wp_ttw_usage_statistics_table_name           = "{$db_tables_prefix}vappv_ttw_usage_statistics";
		$current_usage_statistics_entry_from_wpdb     = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE `tdate`=%s ORDER BY `id` DESC LIMIT 0, 1", array( $wp_ttw_usage_statistics_table_name, gmdate( 'Y-m-d' ) ) ), ARRAY_A );

		if (
			is_null( $current_usage_statistics_entry_from_wpdb ) ||
			0 === count( $current_usage_statistics_entry_from_wpdb )
		) {
			return array(
				'tdate'                          => gmdate( 'Y-m-d' ),
				'dialogues_count'                => 0,
				'income_messages_count'          => 0,
				'income_words_count'             => 0,
				'income_characters_count'        => 0,
				'output_words_count'             => 0,
				'output_characters_count'        => 0,
				'output_completion_tokens_count' => 0
			);
		} else {
			return $current_usage_statistics_entry_from_wpdb[0];
		}
	}

	/**
	 * Check сan we process a message from a user based on the current daily limits
	 *
	 * @param VAPPV_TTW_Settings $settings_controller Settings controller object
	 * @param string $message_text Message text
	 *
	 * @return bool
	 * @throws Exception
	 */
	public function can_process_message_from_user(
		VAPPV_TTW_Settings $settings_controller,
		string $message_text
	): bool {

		$settings_max_input_words_per_day_by_all_users      = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_max_input_words_per_day_by_all_users );
		$settings_max_input_characters_per_day_by_all_users = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_max_input_characters_per_day_by_all_users );
		$settings_max_output_characters_per_day_by_ai       = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_max_output_characters_per_day_by_ai );
		$settings_max_output_tokens_per_day_by_ai           = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_max_output_tokens_per_day_by_ai );

		$message_text_words_count = count( explode( ' ', $message_text ) );
		$message_text_length      = mb_strlen( $message_text, 'utf-8' );
		$today_stats              = $this->get_today_stats();

		// Check max words count by all users per day. Skip check if value set to -1;
		if (
			-1 !== (int)$settings_max_input_words_per_day_by_all_users &&
			$today_stats['income_words_count'] + $message_text_words_count > $settings_max_input_words_per_day_by_all_users
		) {
			return false;
		}

		// Check max characters count by all users per day. Skip check if value set to -1;
		if (
			-1 !== (int)$settings_max_input_characters_per_day_by_all_users &&
			$today_stats['income_characters_count'] + $message_text_length > $settings_max_input_characters_per_day_by_all_users
		) {
			return false;
		}

		// Check max output characters per day by AI. Skip check if value set to -1;
		if (
			-1 !== (int)$settings_max_output_characters_per_day_by_ai &&
			$today_stats['output_characters_count'] > $settings_max_output_characters_per_day_by_ai
		) {
			return false;
		}

		// Check max output tokens count per day by AI. Skip check if value set to -1;
		if (
			-1 !== (int)$settings_max_output_tokens_per_day_by_ai &&
			$today_stats['output_completion_tokens_count'] > $settings_max_output_tokens_per_day_by_ai
		) {
			return false;
		}

		return true;
	}
}

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

?>