<?php
/**
 * War-room live desk feed (AJAX polling + optional SSE).
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! function_exists( 'newsai_warroom_snapshot' ) ) {
	/**
	 * Compact live metrics for war-room panel.
	 *
	 * @param int $days Window.
	 * @return array<string, mixed>
	 */
	function newsai_warroom_snapshot( $days = 30 ) {
		global $wpdb;

		$days = in_array( (int) $days, [ 7, 30, 90 ], true ) ? (int) $days : 30;
		$since = function_exists( 'newsai_sql_datetime_days_ago' )
			? newsai_sql_datetime_days_ago( $days, true )
			: gmdate( 'Y-m-d H:i:s', strtotime( '-' . $days . ' days' ) );

		$post_count = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'post' AND post_status = 'publish' AND post_date_gmt > %s",
				$since
			)
		);

		$gsc_clicks = 0;
		if ( function_exists( 'newsai_gsc_data_available' ) && newsai_gsc_data_available()
			&& function_exists( 'newsai_gsc_insights_period_bounds' )
			&& function_exists( 'newsai_chief_gsc_total_clicks' ) ) {
			$bounds     = newsai_gsc_insights_period_bounds( $days );
			$gsc_clicks = (int) newsai_chief_gsc_total_clicks( $bounds['cur_start'], $bounds['cur_end'] );
		}

		$table       = $wpdb->prefix . 'newsai_alerts';
		$tasks_open  = 0;
		$tasks_over  = 0;
		$has_table   = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) ) );
		if ( $has_table ) {
			$cols = $wpdb->get_col( "DESC {$table}", 0 );
			$has_status = is_array( $cols ) && in_array( 'status', $cols, true );
			if ( $has_status ) {
				$tasks_open = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE status != 'done'" );
			} else {
				$tasks_open = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" );
			}
			$now_time = (int) strtotime( gmdate( 'Y-m-d' ) );
			$open_rows = $wpdb->get_results( $has_status ? "SELECT * FROM {$table} WHERE status != 'done' LIMIT 200" : "SELECT * FROM {$table} LIMIT 200" );
			foreach ( (array) $open_rows as $r ) {
				if ( function_exists( 'newsai_task_kanban_bucket' ) ) {
					if ( newsai_task_kanban_bucket( $r, $has_status, $now_time ) === 'overdue' ) {
						$tasks_over++;
					}
				}
			}
		}

		$recent = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT ID, post_title, post_date_gmt FROM {$wpdb->posts}
				 WHERE post_type = 'post' AND post_status = 'publish'
				 ORDER BY post_date_gmt DESC LIMIT %d",
				5
			)
		);
		$recent_out = [];
		foreach ( (array) $recent as $p ) {
			$recent_out[] = [
				'id'    => (int) $p->ID,
				'title' => sanitize_text_field( (string) $p->post_title ),
				'url'   => get_permalink( $p->ID ),
				'when'  => mysql2date( 'M j, H:i', $p->post_date_gmt, true ),
			];
		}

		return [
			'ts'              => gmdate( 'c' ),
			'days'            => $days,
			'published'       => $post_count,
			'gsc_clicks'      => $gsc_clicks,
			'tasks_open'      => $tasks_open,
			'tasks_overdue'   => $tasks_over,
			'recent_articles' => $recent_out,
		];
	}
}

if ( ! function_exists( 'newsai_warroom_render_panel' ) ) {
	/**
	 * @param int  $days   Window.
	 * @param bool $is_pro Pro active.
	 */
	function newsai_warroom_render_panel( $days = 30, $is_pro = false ) {
		if ( ! current_user_can( 'edit_others_posts' ) ) {
			return;
		}
		$days = in_array( (int) $days, [ 7, 30, 90 ], true ) ? (int) $days : 30;
		$snap = newsai_warroom_snapshot( $days );
		$live = $is_pro && ! ( function_exists( 'newsai_lite_mode_skips_admin_live_polling' ) && newsai_lite_mode_skips_admin_live_polling() );
		?>
		<div class="nros-war-room" id="nros-war-room" data-days="<?php echo (int) $days; ?>" data-live="<?php echo $live ? '1' : '0'; ?>">
			<div class="nros-war-room__head">
				<div>
					<h3><?php echo esc_html__( 'War room', 'newsroom-ai-assistant' ); ?></h3>
					<p class="nros-war-room__sub"><?php echo esc_html__( 'Desk pulse — publishes, GSC clicks, open tasks. Refreshes every 30s via AJAX.', 'newsroom-ai-assistant' ); ?></p>
				</div>
				<div class="nros-war-room__status">
					<span class="nros-war-room__dot" aria-hidden="true"></span>
					<span id="nros-war-room-status"><?php echo esc_html__( 'Ready', 'newsroom-ai-assistant' ); ?></span>
				</div>
			</div>
			<div class="nros-war-room__grid" id="nros-war-room-grid">
				<?php echo newsai_warroom_render_snapshot_html( $snap ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			</div>
		</div>
		<?php
	}
}

if ( ! function_exists( 'newsai_warroom_render_compact' ) ) {
	/**
	 * Compact war-room card for Chief Insights v2 sidebar.
	 *
	 * @param int  $days
	 * @param bool $is_pro
	 */
	function newsai_warroom_render_compact( $days = 30, $is_pro = false ) {
		if ( ! current_user_can( 'edit_others_posts' ) ) {
			return;
		}
		$days = in_array( (int) $days, [ 7, 30, 90 ], true ) ? (int) $days : 30;
		$snap = newsai_warroom_snapshot( $days );
		$live = $is_pro && ! ( function_exists( 'newsai_lite_mode_skips_admin_live_polling' ) && newsai_lite_mode_skips_admin_live_polling() );
		?>
		<div class="nros-war-room nros-war-room--compact" id="nros-war-room" data-days="<?php echo (int) $days; ?>" data-live="<?php echo $live ? '1' : '0'; ?>">
			<p class="nros-insights-table-hint" style="margin:0 0 8px;"><?php echo esc_html__( 'Live desk pulse: open tasks, overdue items, and the latest publishes.', 'newsroom-ai-assistant' ); ?></p>
			<div class="nros-war-room__head">
				<h3><?php echo esc_html__( 'War room', 'newsroom-ai-assistant' ); ?></h3>
				<div class="nros-war-room__status">
					<span class="nros-war-room__dot<?php echo $live ? ' is-live' : ''; ?>" aria-hidden="true"></span>
					<span id="nros-war-room-status"><?php echo $live ? esc_html__( 'Live', 'newsroom-ai-assistant' ) : esc_html__( 'Ready', 'newsroom-ai-assistant' ); ?></span>
				</div>
			</div>
			<div class="nros-war-room__compact-stats">
				<span><strong data-metric="tasks_open"><?php echo esc_html( number_format_i18n( (int) ( $snap['tasks_open'] ?? 0 ) ) ); ?></strong> <?php echo esc_html__( 'open tasks', 'newsroom-ai-assistant' ); ?></span>
				<span class="nros-war-room__compact-sep">·</span>
				<span class="<?php echo (int) ( $snap['tasks_overdue'] ?? 0 ) > 0 ? 'is-warn' : ''; ?>"><strong data-metric="tasks_overdue"><?php echo esc_html( number_format_i18n( (int) ( $snap['tasks_overdue'] ?? 0 ) ) ); ?></strong> <?php echo esc_html__( 'overdue', 'newsroom-ai-assistant' ); ?></span>
			</div>
			<div id="nros-war-room-grid" class="nros-war-room__compact-feed">
				<strong><?php echo esc_html__( 'Latest publishes', 'newsroom-ai-assistant' ); ?></strong>
				<ul class="nros-war-room__list">
					<?php
					$recent = isset( $snap['recent_articles'] ) && is_array( $snap['recent_articles'] ) ? $snap['recent_articles'] : [];
					if ( empty( $recent ) ) {
						echo '<li class="nros-war-room__empty">' . esc_html__( 'No recent posts.', 'newsroom-ai-assistant' ) . '</li>';
					} else {
						foreach ( array_slice( $recent, 0, 3 ) as $art ) {
							echo '<li><a href="' . esc_url( (string) ( $art['url'] ?? '#' ) ) . '" target="_blank" rel="noopener noreferrer">' . esc_html( (string) ( $art['title'] ?? '' ) ) . '</a> <span>' . esc_html( (string) ( $art['when'] ?? '' ) ) . '</span></li>';
						}
					}
					?>
				</ul>
			</div>
		</div>
		<?php
	}
}

if ( ! function_exists( 'newsai_warroom_render_snapshot_html' ) ) {
	/**
	 * @param array $snap Snapshot payload.
	 * @return string
	 */
	function newsai_warroom_render_snapshot_html( array $snap ) {
		ob_start();
		?>
		<div class="nros-war-room__kpi">
			<div class="nros-war-room__kpi-val" data-metric="published"><?php echo esc_html( number_format_i18n( (int) ( $snap['published'] ?? 0 ) ) ); ?></div>
			<div class="nros-war-room__kpi-lbl"><?php echo esc_html__( 'Published', 'newsroom-ai-assistant' ); ?></div>
		</div>
		<div class="nros-war-room__kpi">
			<div class="nros-war-room__kpi-val" data-metric="gsc_clicks"><?php echo esc_html( number_format_i18n( (int) ( $snap['gsc_clicks'] ?? 0 ) ) ); ?></div>
			<div class="nros-war-room__kpi-lbl"><?php echo esc_html__( 'GSC clicks', 'newsroom-ai-assistant' ); ?></div>
		</div>
		<div class="nros-war-room__kpi">
			<div class="nros-war-room__kpi-val" data-metric="tasks_open"><?php echo esc_html( number_format_i18n( (int) ( $snap['tasks_open'] ?? 0 ) ) ); ?></div>
			<div class="nros-war-room__kpi-lbl"><?php echo esc_html__( 'Open tasks', 'newsroom-ai-assistant' ); ?></div>
		</div>
		<div class="nros-war-room__kpi">
			<div class="nros-war-room__kpi-val is-warn" data-metric="tasks_overdue"><?php echo esc_html( number_format_i18n( (int) ( $snap['tasks_overdue'] ?? 0 ) ) ); ?></div>
			<div class="nros-war-room__kpi-lbl"><?php echo esc_html__( 'Overdue', 'newsroom-ai-assistant' ); ?></div>
		</div>
		<div class="nros-war-room__feed">
			<strong><?php echo esc_html__( 'Latest publishes', 'newsroom-ai-assistant' ); ?></strong>
			<ul class="nros-war-room__list">
				<?php
				$recent = isset( $snap['recent_articles'] ) && is_array( $snap['recent_articles'] ) ? $snap['recent_articles'] : [];
				if ( empty( $recent ) ) {
					echo '<li class="nros-war-room__empty">' . esc_html__( 'No recent posts.', 'newsroom-ai-assistant' ) . '</li>';
				} else {
					foreach ( $recent as $art ) {
						echo '<li><a href="' . esc_url( (string) ( $art['url'] ?? '#' ) ) . '" target="_blank" rel="noopener noreferrer">' . esc_html( (string) ( $art['title'] ?? '' ) ) . '</a> <span>' . esc_html( (string) ( $art['when'] ?? '' ) ) . '</span></li>';
					}
				}
				?>
			</ul>
		</div>
		<?php
		return (string) ob_get_clean();
	}
}

if ( ! function_exists( 'newsai_ajax_warroom_snapshot' ) ) {
	function newsai_ajax_warroom_snapshot() {
		check_ajax_referer( 'newsai_ajax_nonce', 'nonce' );
		if ( ! current_user_can( 'edit_others_posts' ) ) {
			wp_send_json_error( [ 'message' => 'forbidden' ], 403 );
		}
		$days = isset( $_REQUEST['days'] ) ? (int) $_REQUEST['days'] : 30;
		$snap = newsai_warroom_snapshot( $days );
		wp_send_json_success(
			[
				'snapshot' => $snap,
				'html'     => newsai_warroom_render_snapshot_html( $snap ),
			]
		);
	}
}
add_action( 'wp_ajax_newsai_warroom_snapshot', 'newsai_ajax_warroom_snapshot' );

if ( ! function_exists( 'newsai_warroom_stream' ) ) {
	/**
	 * SSE stream — 6 ticks × 30s then client reconnects.
	 */
	function newsai_warroom_stream() {
		if ( ! is_user_logged_in() || ! current_user_can( 'edit_others_posts' ) ) {
			status_header( 403 );
			exit;
		}
		$nonce = isset( $_GET['nonce'] ) ? sanitize_text_field( wp_unslash( (string) $_GET['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'newsai_ajax_nonce' ) ) {
			status_header( 403 );
			exit;
		}
		if ( function_exists( 'newsai_is_pro' ) && ! newsai_is_pro() ) {
			status_header( 403 );
			exit;
		}

		$days = isset( $_GET['days'] ) ? (int) $_GET['days'] : 30;
		if ( function_exists( 'session_write_close' ) ) {
			session_write_close();
		}
		nocache_headers();
		header( 'Content-Type: text/event-stream; charset=utf-8' );
		header( 'Cache-Control: no-cache, no-store, must-revalidate' );
		header( 'X-Accel-Buffering: no' );

		@set_time_limit( 200 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged

		for ( $i = 0; $i < 6; $i++ ) {
			$snap = newsai_warroom_snapshot( $days );
			echo 'event: snapshot' . "\n";
			echo 'data: ' . wp_json_encode( $snap, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ) . "\n\n";
			if ( function_exists( 'ob_flush' ) ) {
				@ob_flush(); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
			}
			flush();
			if ( connection_aborted() ) {
				exit;
			}
			sleep( 30 );
		}
		echo "event: reconnect\n";
		echo "data: {}\n\n";
		exit;
	}
}
add_action( 'wp_ajax_newsai_warroom_stream', 'newsai_warroom_stream' );
