<?php
// Защита от прямого доступа
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

function enqueue_statistics_page_styles() {
	// Подключение стилей для страницы статистики
	wp_enqueue_style( 'ai-content-wizard-statistics-page-style', AI_CONTENT_WIZARD_URL . 'css/statistics-page-styles.css', array(), AI_CONTENT_WIZARD_VERSION );
}
add_action( 'admin_enqueue_scripts', 'enqueue_statistics_page_styles' );

function ai_content_wizard_statistics_page() {
	global $wpdb;
	
	echo '<div class="ai-content-wizard-statistics-page">';
	echo '<h1>' . __( 'AI Content Wizard - Statistics', 'ai-content-wizard' ) . '</h1>';

	// Форма фильтрации по периоду
	echo '<form method="get" class="ai-cw-statistics-filter-form">';
	// Сохраняем параметр страницы, если он есть
	if ( isset( $_GET['page'] ) ) {
		echo '<input type="hidden" name="page" value="' . esc_attr( $_GET['page'] ) . '">';
	}
	
	echo '<label for="time_filter">' . __( 'Period', 'ai-content-wizard' ) . ':</label>';
	$selected = isset( $_GET['time_filter'] ) ? sanitize_text_field( $_GET['time_filter'] ) : 'all';
	echo '<select name="time_filter" id="time_filter">';
		echo '<option value="all"' . selected( $selected, 'all', false ) . '>' . __( 'All Time', 'ai-content-wizard' ) . '</option>';
		echo '<option value="week"' . selected( $selected, 'week', false ) . '>' . __( 'Last Week', 'ai-content-wizard' ) . '</option>';
		echo '<option value="month"' . selected( $selected, 'month', false ) . '>' . __( 'Last Month', 'ai-content-wizard' ) . '</option>';
		echo '<option value="year"' . selected( $selected, 'year', false ) . '>' . __( 'Last Year', 'ai-content-wizard' ) . '</option>';
		echo '<option value="custom"' . selected( $selected, 'custom', false ) . '>' . __( 'Custom', 'ai-content-wizard' ) . '</option>';
	echo '</select>';

	// Поля для произвольного периода
	$custom_start = isset( $_GET['custom_start'] ) ? sanitize_text_field( $_GET['custom_start'] ) : '';
	$custom_end   = isset( $_GET['custom_end'] ) ? sanitize_text_field( $_GET['custom_end'] ) : '';
	// Если выбран custom, не задаём inline-стиль (он будет задан через класс), иначе скрываем блок
	$custom_display = ($selected === 'custom') ? '' : 'display:none;';
	echo '<div id="custom_period_fields" style="' . $custom_display . '">';
		echo '<div class="custom-dates-wrapper">';
			echo '<label for="custom_start">' . __( 'Start Date', 'ai-content-wizard' ) . ':</label>';
			echo '<input type="date" name="custom_start" id="custom_start" value="' . esc_attr( $custom_start ) . '">';
			echo '<label for="custom_end">' . __( 'End Date', 'ai-content-wizard' ) . ':</label>';
			echo '<input type="date" name="custom_end" id="custom_end" value="' . esc_attr( $custom_end ) . '">';
		echo '</div>';
	echo '</div>';

	echo '<input type="submit" value="' . __( 'Apply', 'ai-content-wizard' ) . '">';
	echo '</form>';

	// JS для переключения отображения полей произвольного периода
	echo "<script>
		document.getElementById('time_filter').addEventListener('change', function() {
			var customFields = document.getElementById('custom_period_fields');
			if ( this.value === 'custom' ) {
				customFields.style.display = '';
				customFields.classList.add('custom-active');
			} else {
				customFields.style.display = 'none';
				customFields.classList.remove('custom-active');
			}
		});
	</script>";

	// Определение временного интервала для фильтрации
	$date_condition_posts = '';
	$date_condition_plan  = '';
	$start_date = '';
	$end_date   = '';

	if ( $selected === 'week' ) {
		$start_date = date( 'Y-m-d', strtotime( '-7 days' ) );
		$end_date   = date( 'Y-m-d' );
	} elseif ( $selected === 'month' ) {
		$start_date = date( 'Y-m-d', strtotime( '-1 month' ) );
		$end_date   = date( 'Y-m-d' );
	} elseif ( $selected === 'year' ) {
		$start_date = date( 'Y-m-d', strtotime( '-1 year' ) );
		$end_date   = date( 'Y-m-d' );
	} elseif ( $selected === 'custom' ) {
		if ( ! empty( $custom_start ) && ! empty( $custom_end ) ) {
			$start_date = $custom_start;
			$end_date   = $custom_end;
		}
	}

	if ( $start_date && $end_date ) {
		// Для логов статей (поле generation_time)
		$date_condition_posts = $wpdb->prepare( "WHERE DATE(generation_time) BETWEEN %s AND %s", $start_date, $end_date );
		// Для логов контент-планов (поле date)
		$date_condition_plan = $wpdb->prepare( "WHERE DATE(`date`) BETWEEN %s AND %s", $start_date, $end_date );
	}

	$statistics = array();

	// Имена таблиц логов
	$posts_logs_table        = $wpdb->prefix . 'ai_content_wizard_posts_logs';
	$content_plan_logs_table = $wpdb->prefix . 'ai_content_wizard_content_plan_logs';

	// Получаем логи генерации статей с учётом фильтра
	$posts_logs_query = "SELECT * FROM $posts_logs_table ";
	if ( $date_condition_posts ) {
		$posts_logs_query .= $date_condition_posts;
	}
	$posts_logs = $wpdb->get_results( $posts_logs_query, ARRAY_A );

	// Получаем логи контент-планов с учётом фильтра
	$content_plan_logs_query = "SELECT * FROM $content_plan_logs_table ";
	if ( $date_condition_plan ) {
		$content_plan_logs_query .= $date_condition_plan;
	}
	$content_plan_logs = $wpdb->get_results( $content_plan_logs_query, ARRAY_A );

	// Обрабатываем логи генерации статей
	foreach ( $posts_logs as $log ) {
		$date = date( 'Y-m-d', strtotime( $log['generation_time'] ) );
		$type = __( 'Article Generation', 'ai-content-wizard' );
		if ( ! isset( $statistics[ $date ][ $type ] ) ) {
			$statistics[ $date ][ $type ] = array( 'count' => 0, 'total_cost' => 0 );
		}
		$statistics[ $date ][ $type ]['count']++;
		$statistics[ $date ][ $type ]['total_cost'] += floatval( $log['total_cost'] );
	}

	// Обрабатываем логи контент-планов
	foreach ( $content_plan_logs as $log ) {
		$date = date( 'Y-m-d', strtotime( $log['date'] ) );
		$type = __( 'Content Plan', 'ai-content-wizard' );
		if ( ! isset( $statistics[ $date ][ $type ] ) ) {
			$statistics[ $date ][ $type ] = array( 'count' => 0, 'total_cost' => 0 );
		}
		$statistics[ $date ][ $type ]['count']++;
		$statistics[ $date ][ $type ]['total_cost'] += floatval( $log['total_cost'] );
	}

	// Сортируем статистику по дате (от новых к старым)
	krsort( $statistics );

	// Вывод статистики в виде таблицы
	echo '<table class="ai-cw-statistics-table wp-list-table widefat fixed striped">';
	echo '<thead><tr>';
		echo '<th>' . __( 'Date', 'ai-content-wizard' ) . '</th>';
		echo '<th>' . __( 'Type', 'ai-content-wizard' ) . '</th>';
		echo '<th>' . __( 'Count', 'ai-content-wizard' ) . '</th>';
		echo '<th>' . __( 'Total Cost', 'ai-content-wizard' ) . '</th>';
	echo '</tr></thead>';
	echo '<tbody>';

	$grand_total_count = 0;
	$grand_total_cost  = 0;

	foreach ( $statistics as $date => $types ) {
		$daily_total_count = 0;
		$daily_total_cost  = 0;

		foreach ( $types as $type => $data ) {
			echo '<tr>';
				echo '<td>' . esc_html( $date ) . '</td>';
				echo '<td>' . esc_html( $type ) . '</td>';
				echo '<td>' . intval( $data['count'] ) . '</td>';
				echo '<td>$' . number_format( $data['total_cost'], 2 ) . '</td>';
			echo '</tr>';

			$daily_total_count += $data['count'];
			$daily_total_cost  += $data['total_cost'];
		}

		// Итог за день
		echo '<tr class="daily-total">';
			echo '<td>' . esc_html( $date ) . '</td>';
			echo '<td><strong>' . __( 'Daily Total', 'ai-content-wizard' ) . '</strong></td>';
			echo '<td><strong>' . intval( $daily_total_count ) . '</strong></td>';
			echo '<td><strong>$' . number_format( $daily_total_cost, 2 ) . '</strong></td>';
		echo '</tr>';

		$grand_total_count += $daily_total_count;
		$grand_total_cost  += $daily_total_cost;
	}

	// Итог за выбранный период
	echo '<tr class="grand-total">';
		echo '<td colspan="2"><strong>' . __( 'Grand Total', 'ai-content-wizard' ) . '</strong></td>';
		echo '<td><strong>' . intval( $grand_total_count ) . '</strong></td>';
		echo '<td><strong>$' . number_format( $grand_total_cost, 2 ) . '</strong></td>';
	echo '</tr>';

	echo '</tbody></table>';
	echo '</div>';
}
