<?php
/**
 * Pro edition helpers: licensing gate + editorial analytics.
 *
 * @package Newsroom_AI_Assistant
 */

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

if ( ! function_exists( 'newsai_pro_author_initials' ) ) {
	function newsai_pro_author_initials( $display_name ) {
		$display_name = trim( preg_replace( '/\s+/u', ' ', (string) $display_name ) );
		if ( $display_name === '' ) {
			return '?';
		}
		$parts = preg_split( '/\s+/u', $display_name, -1, PREG_SPLIT_NO_EMPTY );
		if ( count( $parts ) >= 2 ) {
			$a = mb_substr( $parts[0], 0, 1, 'UTF-8' );
			$b = mb_substr( $parts[ count( $parts ) - 1 ], 0, 1, 'UTF-8' );
			return mb_strtoupper( $a . $b, 'UTF-8' );
		}
		return mb_strtoupper( mb_substr( $display_name, 0, 2, 'UTF-8' ), 'UTF-8' );
	}
}

if ( ! function_exists( 'newsai_pro_invalidate_writer_leaderboard' ) ) {
	function newsai_pro_invalidate_writer_leaderboard() {
		delete_transient( 'newsai_pro_writer_lb_v1' );
	}
}

if ( ! function_exists( 'newsai_pro_get_writer_leaderboard' ) ) {
	/**
	 * Top authors by publish volume (last 30 days) with trend vs prior 30 days.
	 *
	 * @param int $limit Max rows (default 5).
	 * @return array<int, array{user_id:int, name:string, initials:string, posts_30d:int, prior_30d:int, trend:string}>
	 */
	function newsai_pro_get_writer_leaderboard( $limit = 5 ) {
		$limit = max( 1, min( 12, (int) $limit ) );
		$cached = get_transient( 'newsai_pro_writer_lb_v1' );
		if ( is_array( $cached ) && isset( $cached['limit'], $cached['rows'] ) && (int) $cached['limit'] === $limit ) {
			return $cached['rows'];
		}

		global $wpdb;
		$since_30 = function_exists( 'newsai_sql_datetime_days_ago' ) ? newsai_sql_datetime_days_ago( 30, true ) : gmdate( 'Y-m-d H:i:s', strtotime( '-30 days' ) );
		$since_60 = function_exists( 'newsai_sql_datetime_days_ago' ) ? newsai_sql_datetime_days_ago( 60, true ) : gmdate( 'Y-m-d H:i:s', strtotime( '-60 days' ) );
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$recent_rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT post_author AS uid, COUNT(*) AS cnt
				FROM {$wpdb->posts}
				WHERE post_type = 'post' AND post_status = 'publish'
				AND post_date_gmt > %s
				GROUP BY post_author
				ORDER BY cnt DESC
				LIMIT 20",
				$since_30
			)
		);

		$out = [];
		if ( ! empty( $recent_rows ) ) {
			foreach ( $recent_rows as $row ) {
				$uid = (int) $row->uid;
				if ( $uid <= 0 ) {
					continue;
				}
				$user = get_userdata( $uid );
				if ( ! $user ) {
					continue;
				}
				$recent = (int) $row->cnt;
				$prior = (int) $wpdb->get_var(
					$wpdb->prepare(
						"SELECT COUNT(*) FROM {$wpdb->posts}
						WHERE post_type = 'post' AND post_status = 'publish' AND post_author = %d
						AND post_date_gmt <= %s
						AND post_date_gmt > %s",
						$uid,
						$since_30,
						$since_60
					)
				);

				$trend = 'flat';
				if ( $recent > $prior ) {
					$trend = 'up';
				} elseif ( $prior > 0 && $recent < $prior ) {
					$trend = 'down';
				}

				$out[] = [
					'user_id'    => $uid,
					'name'       => (string) $user->display_name,
					'initials'   => newsai_pro_author_initials( $user->display_name ),
					'posts_30d'  => $recent,
					'prior_30d'  => $prior,
					'trend'      => $trend,
				];
			}
		}

		$out = array_slice( $out, 0, $limit );
		set_transient(
			'newsai_pro_writer_lb_v1',
			[
				'limit' => $limit,
				'rows'  => $out,
			],
			15 * MINUTE_IN_SECONDS
		);

		return $out;
	}
}

add_action( 'save_post', 'newsai_pro_bump_writer_cache_on_publish', 25, 3 );
if ( ! function_exists( 'newsai_pro_bump_writer_cache_on_publish' ) ) {
	function newsai_pro_bump_writer_cache_on_publish( $post_id, $post, $update ) {
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}
		if ( ! $post || $post->post_type !== 'post' ) {
			return;
		}
		newsai_pro_invalidate_writer_leaderboard();
	}
}
