<?php
/**
 * Author Performance payload for React admin (2.7).
 *
 * @package Newsroom_AI_Assistant
 */

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

if ( ! function_exists( 'newsai_author_perf_registry_i18n' ) ) {
	function newsai_author_perf_registry_i18n() {
		return [
			'loading'    => __( 'Loading author performance…', 'newsroom-ai-assistant' ),
			'error'      => __( 'Author Performance could not load.', 'newsroom-ai-assistant' ),
			'title'      => __( 'Author Performance', 'newsroom-ai-assistant' ),
			'subtitle'   => __( 'Detailed metrics and AI coaching insights per author.', 'newsroom-ai-assistant' ),
			'search'     => __( 'Search authors by name or role…', 'newsroom-ai-assistant' ),
			'ai_desk'    => __( 'AI desk overview', 'newsroom-ai-assistant' ),
			'posts'      => __( 'Posts', 'newsroom-ai-assistant' ),
			'focus'      => __( 'Focus score', 'newsroom-ai-assistant' ),
			'discover'   => __( 'Discover %', 'newsroom-ai-assistant' ),
			'clicks'     => __( 'Clicks', 'newsroom-ai-assistant' ),
			'details'    => __( 'Details', 'newsroom-ai-assistant' ),
			'summary'    => __( 'Summary', 'newsroom-ai-assistant' ),
			'articles'   => __( 'Articles', 'newsroom-ai-assistant' ),
			'coaching'   => __( 'Coaching', 'newsroom-ai-assistant' ),
			'your_perf'  => __( 'Your performance', 'newsroom-ai-assistant' ),
			'pro_only'   => __( 'Author Performance requires Pro and editor access.', 'newsroom-ai-assistant' ),
			'pro_only_license' => __( 'Author Performance requires an active PRO license.', 'newsroom-ai-assistant' ),
			'pro_only_capability' => __( 'Author Performance is available to editors who can manage other authors\' posts.', 'newsroom-ai-assistant' ),
			'activate_pro' => __( 'Go to PRO license', 'newsroom-ai-assistant' ),
			'classicLink' => __( 'Open classic Author Performance', 'newsroom-ai-assistant' ),
			'export_pdf' => __( 'Export PDF', 'newsroom-ai-assistant' ),
			'editorial'  => __( 'Editorial quality', 'newsroom-ai-assistant' ),
			'categories' => __( 'Categories', 'newsroom-ai-assistant' ),
			'gsc_totals' => __( 'Search Console totals', 'newsroom-ai-assistant' ),
			'latest_articles' => __( 'Latest articles', 'newsroom-ai-assistant' ),
			'top_gsc'    => __( 'Top articles by Search Console clicks', 'newsroom-ai-assistant' ),
			'no_coaching'=> __( 'No coaching gaps detected for this author.', 'newsroom-ai-assistant' ),
			'overview_loading' => __( 'Generating desk overview…', 'newsroom-ai-assistant' ),
			'days_7'     => __( '7 days', 'newsroom-ai-assistant' ),
			'days_30'    => __( '30 days', 'newsroom-ai-assistant' ),
			'days_90'    => __( '90 days', 'newsroom-ai-assistant' ),
		];
	}
}

if ( ! function_exists( 'newsai_author_perf_registry_author_row' ) ) {
	function newsai_author_perf_registry_author_row( $bundle, $days, $is_self = false ) {
		if ( empty( $bundle ) || ! is_array( $bundle ) ) {
			return null;
		}
		$score = isset( $bundle['score'] ) && is_array( $bundle['score'] ) ? $bundle['score'] : [];
		$disc  = isset( $bundle['discover_readiness'] ) && is_array( $bundle['discover_readiness'] ) ? $bundle['discover_readiness'] : [];
		$posts = isset( $bundle['posts'] ) && is_array( $bundle['posts'] ) ? $bundle['posts'] : [];
		$web   = function_exists( 'newsai_pro_author_bundle_web_clicks' )
			? (int) newsai_pro_author_bundle_web_clicks( $bundle )
			: 0;

		return [
			'userId'    => (int) ( $bundle['user_id'] ?? 0 ),
			'name'      => (string) ( $bundle['name'] ?? '' ),
			'role'      => (string) ( $bundle['job_title'] ?? '' ),
			'avatar'    => (string) ( $bundle['avatar'] ?? '' ),
			'initials'  => (string) ( $bundle['initials'] ?? '' ),
			'isSelf'    => (bool) $is_self,
			'posts'     => (int) ( $posts['recent'] ?? 0 ),
			'postsPrior'=> (int) ( $posts['prior'] ?? 0 ),
			'trend'     => (string) ( $posts['trend'] ?? 'flat' ),
			'focus'     => (int) ( $score['avg'] ?? 0 ),
			'focusSample' => (int) ( $score['sample'] ?? 0 ),
			'discover'  => (int) ( $disc['avg'] ?? 0 ),
			'discoverSample' => (int) ( $disc['sample'] ?? 0 ),
			'clicks'    => $web,
			'categories'=> array_slice( (array) ( $bundle['categories'] ?? [] ), 0, 5 ),
			'weakSpots' => array_slice( (array) ( $disc['weak_spots'] ?? [] ), 0, 5 ),
			'days'      => (int) $days,
		];
	}
}

if ( ! function_exists( 'newsai_author_perf_registry_slim_article' ) ) {
	function newsai_author_perf_registry_slim_article( $a ) {
		if ( ! is_array( $a ) ) {
			return null;
		}
		return [
			'title'    => (string) ( $a['title'] ?? '' ),
			'editUrl'  => ! empty( $a['edit_url'] ) ? (string) $a['edit_url'] : ( ! empty( $a['editUrl'] ) ? (string) $a['editUrl'] : '' ),
			'viewUrl'  => ! empty( $a['view_url'] ) ? (string) $a['view_url'] : ( ! empty( $a['viewUrl'] ) ? (string) $a['viewUrl'] : '' ),
			'focus'    => (int) ( $a['score'] ?? 0 ),
			'discover' => (int) ( $a['discover'] ?? 0 ),
			'gscClicks'=> (int) ( $a['gsc_clicks_total'] ?? 0 ),
			'ago'      => (string) ( $a['ago'] ?? '' ),
		];
	}
}

if ( ! function_exists( 'newsai_author_perf_registry_gsc_channel' ) ) {
	function newsai_author_perf_registry_gsc_channel( $ch ) {
		if ( ! is_array( $ch ) ) {
			return null;
		}
		return [
			'clicks'      => (int) ( $ch['clicks'] ?? 0 ),
			'impressions' => (int) ( $ch['impressions'] ?? 0 ),
			'ctr'         => isset( $ch['ctr'] ) ? round( (float) $ch['ctr'] * 100, 1 ) : 0,
		];
	}
}

if ( ! function_exists( 'newsai_author_perf_registry_expanded' ) ) {
	function newsai_author_perf_registry_expanded( $user_id, $days = 30 ) {
		$user_id = (int) $user_id;
		$days    = in_array( (int) $days, [ 7, 30, 90 ], true ) ? (int) $days : 30;
		if ( ! function_exists( 'newsai_pro_author_performance' ) ) {
			return null;
		}
		$bundle = newsai_pro_author_performance( $user_id, $days );
		if ( empty( $bundle ) ) {
			return null;
		}
		$score = isset( $bundle['score'] ) && is_array( $bundle['score'] ) ? $bundle['score'] : [];
		$disc  = isset( $bundle['discover_readiness'] ) && is_array( $bundle['discover_readiness'] ) ? $bundle['discover_readiness'] : [];
		$weak  = [];
		foreach ( (array) ( $disc['weak_spots'] ?? [] ) as $spot ) {
			if ( ! is_array( $spot ) || empty( $spot['label'] ) ) {
				continue;
			}
			$weak[] = [
				'id'    => (string) ( $spot['id'] ?? '' ),
				'label' => (string) $spot['label'],
				'pct'   => isset( $spot['pct'] ) ? (int) $spot['pct'] : null,
			];
		}
		$articles = [];
		foreach ( (array) ( $bundle['articles'] ?? [] ) as $a ) {
			$row = newsai_author_perf_registry_slim_article( $a );
			if ( $row ) {
				$articles[] = $row;
			}
		}
		$topGsc = [];
		foreach ( (array) ( $bundle['articles_top_gsc'] ?? [] ) as $a ) {
			$row = newsai_author_perf_registry_slim_article( $a );
			if ( $row ) {
				$topGsc[] = $row;
			}
		}
		return [
			'userId'     => $user_id,
			'focus'      => (int) ( $score['avg'] ?? 0 ),
			'focusSample'=> (int) ( $score['sample'] ?? 0 ),
			'discover'   => (int) ( $disc['avg'] ?? 0 ),
			'discoverSample' => (int) ( $disc['sample'] ?? 0 ),
			'categories' => array_values( (array) ( $bundle['categories'] ?? [] ) ),
			'gsc'        => [
				'web'        => newsai_author_perf_registry_gsc_channel( $bundle['web'] ?? null ),
				'discover'   => newsai_author_perf_registry_gsc_channel( $bundle['discover'] ?? null ),
				'googleNews' => newsai_author_perf_registry_gsc_channel( $bundle['gnews'] ?? null ),
			],
			'articles'   => $articles,
			'topGsc'     => $topGsc,
			'weakSpots'  => $weak,
			'gscReady'   => function_exists( 'newsai_gsc_data_available' ) && newsai_gsc_data_available(),
		];
	}
}

if ( ! function_exists( 'newsai_author_perf_can_access' ) ) {
	/**
	 * Whether the current user may open Author Performance (React + classic).
	 *
	 * @return bool
	 */
	function newsai_author_perf_can_access() {
		if ( ! function_exists( 'newsai_is_pro' ) || ! newsai_is_pro() ) {
			return false;
		}
		return current_user_can( 'edit_others_posts' );
	}
}

if ( ! function_exists( 'newsai_author_perf_registry_payload' ) ) {
	function newsai_author_perf_registry_payload( $days = 30 ) {
		$days   = in_array( (int) $days, [ 7, 30, 90 ], true ) ? (int) $days : 30;
		$is_pro = function_exists( 'newsai_is_pro' ) && newsai_is_pro();
		$can    = current_user_can( 'edit_others_posts' );

		if ( ! $is_pro || ! $can ) {
			return [
				'allowed'       => false,
				'isPro'         => $is_pro,
				'canEditOthers' => $can,
				'denyReason'    => ! $is_pro ? 'pro' : 'capability',
				'i18n'          => newsai_author_perf_registry_i18n(),
				'urls'          => [
					'classic' => admin_url( 'admin.php?page=newsai-settings&tab=perf&ui=classic' ),
				],
			];
		}

		try {
			$authors = [];
			$me_id   = (int) get_current_user_id();

			if ( function_exists( 'newsai_pro_desk_writer_user_ids' ) ) {
				foreach ( newsai_pro_desk_writer_user_ids() as $uid ) {
					if ( ! function_exists( 'newsai_pro_author_performance' ) ) {
						break;
					}
					$bundle = newsai_pro_author_performance( (int) $uid, $days );
					$row    = newsai_author_perf_registry_author_row( $bundle, $days, (int) $uid === $me_id );
					if ( $row ) {
						$authors[] = $row;
					}
				}
			}

			usort(
				$authors,
				static function ( $a, $b ) {
					$cmp = (int) ( $b['posts'] ?? 0 ) <=> (int) ( $a['posts'] ?? 0 );
					return $cmp !== 0 ? $cmp : strcmp( (string) ( $a['name'] ?? '' ), (string) ( $b['name'] ?? '' ) );
				}
			);

			$ai_ready = function_exists( 'newsai_ai_is_active' ) && newsai_ai_is_active();

			return [
				'allowed'       => true,
				'isPro'         => true,
				'canEditOthers' => true,
				'days'          => $days,
				'gscReady'      => function_exists( 'newsai_gsc_data_available' ) && newsai_gsc_data_available(),
				'aiDeskReady'   => $ai_ready,
				'perfNonce'     => wp_create_nonce( 'newsai_pro_author_perf' ),
				'authors'       => $authors,
				'urls'          => [
					'classic' => admin_url( 'admin.php?page=newsai-settings&tab=perf&ui=classic' ),
				],
				'i18n'          => newsai_author_perf_registry_i18n(),
			];
		} catch ( \Throwable $e ) {
			return [
				'allowed'       => false,
				'isPro'         => $is_pro,
				'canEditOthers' => $can,
				'denyReason'    => 'error',
				'error'         => $e->getMessage(),
				'i18n'          => newsai_author_perf_registry_i18n(),
				'urls'          => [
					'classic' => admin_url( 'admin.php?page=newsai-settings&tab=perf&ui=classic' ),
				],
			];
		}
	}
}
