<?php

/**
 * TalkToWebsite dialogues controller
 */
final class VAPPV_TTW_Chat_Dialogues {

	/**
	 * Get a list of dialogs that have taken place between users and the AI. Return the result as a packed JSON string.
	 *
	 * @param integer $offset Numerical indentation in the list of all dialogs
	 * @param integer $limit Number of dialogs to be extracted
	 *
	 * @return array
	 * @throws Exception
	 */
	public function list_dialogues_as_admin( int $offset, int $limit ): array {

		global $wpdb;

		$db_tables_prefix = $wpdb->prefix;
		$dialogues_wpdb_table_name = "{$db_tables_prefix}vappv_ttw_dialogues";
		$gialogues_messages_db_table_name = "{$db_tables_prefix}vappv_ttw_dialogues_messages";

		//-----------------------------------------------------------------------------------
		//Get dialogues primary data
		//Get data itself
		$dialogues_from_wpdb_data_rows = $wpdb->get_results(
			$wpdb->prepare( 'SELECT * FROM %i ORDER BY `id` DESC LIMIT %d, %d', array(
				$dialogues_wpdb_table_name,
				$offset,
				$limit
			) ),
			ARRAY_A
		);

		//Get items count
		$dialogues_count_from_wpdb_data_rows = $wpdb->get_results(
			$wpdb->prepare( "SELECT COUNT(*) AS `items_total_count` FROM %i", array( $dialogues_wpdb_table_name ) ),
			ARRAY_A
		);

		//Check resulted rows
		if ( count( $dialogues_from_wpdb_data_rows ) > 0 ) {
			//-----------------------------------------------------------------------------------
			//Get dialogue metrics (messages count, characters count, etc.)
			$dialogues_chunk_identifiers = array();
			for ( $q = 0; $q < count( $dialogues_from_wpdb_data_rows ); $q++ ) {
				array_push( $dialogues_chunk_identifiers, $dialogues_from_wpdb_data_rows[ $q ]['id'] );
				$dialogues_from_wpdb_data_rows[ $q ]['messages'] = array(
					'list'                       => array(),
					'messages_from_user_count'   => 0,
					'messages_from_ai_count'     => 0,
					'characters_from_user_count' => 0,
					'characters_from_ai_count'   => 0,
					'have_errors'                => false,
					'first_message_date'         => null,
					'last_message_date'          => null,
					'dialogue_duration_minutes'  => 0
				);
			}

			//Esacape identifiers
			$dialogued_identifiers_placeholders = implode( ', ', array_fill( 0, count( $dialogues_chunk_identifiers ), '%d' ) );
			$prepared_sql_values = array_merge( array( $gialogues_messages_db_table_name ), $dialogues_chunk_identifiers );

			//Get messages based on imploded identifiers
			$dialogues_messages_from_wpdb_data_rows = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT * FROM %i WHERE `dialogue_id` IN ( $dialogued_identifiers_placeholders ) ORDER BY `id` ASC",
					$prepared_sql_values
				),
				ARRAY_A
			);

			//Itterate messages results
			for ( $t = 0; $t < count( $dialogues_from_wpdb_data_rows ); $t++ ) {
				for ( $q = 0; $q < count( $dialogues_messages_from_wpdb_data_rows ); $q++ ) {
					if ( $dialogues_from_wpdb_data_rows[ $t ]['id'] === $dialogues_messages_from_wpdb_data_rows[ $q ]['dialogue_id'] ) {

						//Add message into dualogue, analyse primary metrics
						array_push( $dialogues_from_wpdb_data_rows[ $t ]['messages']['list'], $dialogues_messages_from_wpdb_data_rows[ $q ] );
						if ( 'user' === $dialogues_messages_from_wpdb_data_rows[ $q ]['sender_role'] ) {
							$dialogues_from_wpdb_data_rows[ $t ]['messages']['messages_from_user_count']++;
							$dialogues_from_wpdb_data_rows[ $t ]['messages']['characters_from_user_count'] += mb_strlen( $dialogues_messages_from_wpdb_data_rows[ $q ]['message_text'], 'utf-8' );
						} elseif ( 'ai' === $dialogues_messages_from_wpdb_data_rows[ $q ]['sender_role'] ) {
							$dialogues_from_wpdb_data_rows[ $t ]['messages']['messages_from_ai_count']++;
							$dialogues_from_wpdb_data_rows[ $t ]['messages']['characters_from_ai_count'] += mb_strlen( $dialogues_messages_from_wpdb_data_rows[ $q ]['message_text'], 'utf-8' );
						}

						//Check for errors
						if ( 1 === $dialogues_messages_from_wpdb_data_rows[ $q ]['is_executed_with_error'] ) {
							$dialogues_from_wpdb_data_rows[ $t ]['messages']['is_executed_with_error'] = true;
						}
					}
				}

				$fisrt_message_date = null;
				if ( count( $dialogues_from_wpdb_data_rows[ $t ]['messages']['list'] ) > 0 ) {
					$fisrt_message_date = new DateTime( $dialogues_from_wpdb_data_rows[ $t ]['messages']['list'][0]['message_date'] );
					$dialogues_from_wpdb_data_rows[ $t ]['messages']['first_message_date'] = $dialogues_from_wpdb_data_rows[ $t ]['messages']['list'][0]['message_date'];
				}

				$last_message_date = null;
				if ( count( $dialogues_from_wpdb_data_rows[ $t ]['messages']['list'] ) > 1 ) {
					$dialogue_messages_count  = count( $dialogues_from_wpdb_data_rows[ $t ]['messages']['list'] );
					$last_message_date = new DateTime( $dialogues_from_wpdb_data_rows[ $t ]['messages']['list'][ $dialogue_messages_count - 1 ]['message_date'] );
					$dialogues_from_wpdb_data_rows[ $t ]['messages']['last_message_date'] = $dialogues_from_wpdb_data_rows[ $t ]['messages']['list'][ $dialogue_messages_count - 1 ]['message_date'];
				}

				if (
					! is_null( $fisrt_message_date ) &&
					! is_null( $last_message_date )
				) {
					$dates_diff = $last_message_date->diff( $fisrt_message_date );
					$total_minutes = $dates_diff->days * 24 * 60;
					$total_minutes += $dates_diff->h * 60;
					$total_minutes += $dates_diff->i;
					$dialogues_from_wpdb_data_rows[ $t ]['messages']['dialogue_duration_minutes'] = $total_minutes;
				}
			}

			//-----------------------------------------------------------------------------------

			//Pack results
			$results_logs_and_pagination = array(
				'dialogues'  => $dialogues_from_wpdb_data_rows,
				'pagination' => VAPPV_TTW_UI_Data_Paginator::paginate( $dialogues_count_from_wpdb_data_rows[0]['items_total_count'], $offset, $limit )
			);

			return VAPPV_TTW_Core::ajax_pack_success( $results_logs_and_pagination );

		} else {

			//No dialogues yet. Return empty results.
			return VAPPV_TTW_Core::ajax_pack_success( array(
				'dialogues'  => array(),
				'pagination' => VAPPV_TTW_UI_Data_Paginator::paginate( 0, $offset, $limit )
			) );

		}
	}
}

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

?>