<?php
/**
 * GSC traffic-drop alerts — replaces Content Decay Radar (Phase D).
 *
 * @package Newsroom_AI_Assistant
 */

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

if ( ! function_exists( 'newsai_gsc_traffic_drop_enabled' ) ) {
	function newsai_gsc_traffic_drop_enabled() {
		if ( ! function_exists( 'newsai_gsc_is_pro_active' ) || ! newsai_gsc_is_pro_active() ) {
			return false;
		}
		if ( ! function_exists( 'newsai_gsc_data_available' ) || ! newsai_gsc_data_available() ) {
			return false;
		}
		return get_option( 'newsai_gsc_traffic_drop_enabled', 'yes' ) === 'yes';
	}
}

if ( ! function_exists( 'newsai_gsc_traffic_drop_settings' ) ) {
	/**
	 * @return array{days:int,min_prev:int,min_loss:int,channel:string}
	 */
	function newsai_gsc_traffic_drop_settings() {
		$days = (int) get_option( 'newsai_gsc_traffic_drop_days', 28 );
		$days = max( 7, min( 90, $days ) );
		$min_prev = (int) get_option( 'newsai_gsc_traffic_drop_min_prev_clicks', 25 );
		$min_prev = max( 5, min( 500, $min_prev ) );
		$min_loss = (int) get_option( 'newsai_gsc_traffic_drop_min_loss', 15 );
		$min_loss = max( 5, min( 500, $min_loss ) );
		$channel  = (string) get_option( 'newsai_gsc_traffic_drop_channel', 'web' );
		if ( ! function_exists( 'newsai_gsc_sanitize_search_type' ) ) {
			$channel = 'web';
		} else {
			$channel = newsai_gsc_sanitize_search_type( $channel );
		}
		return [
			'days'     => $days,
			'min_prev' => $min_prev,
			'min_loss' => $min_loss,
			'channel'  => $channel,
		];
	}
}

if ( ! function_exists( 'newsai_gsc_traffic_drop_find' ) ) {
	/**
	 * Posts with meaningful GSC click loss vs the previous period.
	 *
	 * @return list<array{post_id:int,title:string,clicks:int,prev_clicks:int,delta_clicks:int,pct_drop:float,edit_url:string,view_url:string}>
	 */
	function newsai_gsc_traffic_drop_find( $days = null, $channel = null, $limit = 8 ) {
		if ( ! function_exists( 'newsai_gsc_data_available' ) || ! newsai_gsc_data_available() ) {
			return [];
		}
		$cfg     = newsai_gsc_traffic_drop_settings();
		$days    = $days === null ? $cfg['days'] : max( 7, min( 90, (int) $days ) );
		$channel = $channel === null ? $cfg['channel'] : ( function_exists( 'newsai_gsc_sanitize_search_type' ) ? newsai_gsc_sanitize_search_type( (string) $channel ) : 'web' );
		$limit   = max( 1, min( 15, (int) $limit ) );

		if ( ! function_exists( 'newsai_gsc_insights_period_bounds' ) ) {
			return [];
		}

		global $wpdb;
		$bounds = newsai_gsc_insights_period_bounds( $days );
		$table  = newsai_gsc_table_name();

		$sql = "
			SELECT p.ID AS post_id, p.post_title AS title,
				SUM(CASE WHEN g.data_date >= %s AND g.data_date <= %s THEN g.clicks ELSE 0 END) AS clicks,
				SUM(CASE WHEN g.data_date >= %s AND g.data_date <= %s THEN g.clicks ELSE 0 END) AS prev_clicks
			FROM {$table} g
			INNER JOIN {$wpdb->posts} p ON p.ID = g.post_id
			WHERE g.search_type = %s
				AND g.data_date >= %s AND g.data_date <= %s
				AND p.post_status = 'publish' AND p.post_type = 'post'
			GROUP BY p.ID, p.post_title
			HAVING prev_clicks >= %d AND (clicks - prev_clicks) <= -%d
			ORDER BY (clicks - prev_clicks) ASC
			LIMIT %d";

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
		$rows = $wpdb->get_results(
			$wpdb->prepare(
				$sql,
				$bounds['cur_start'],
				$bounds['cur_end'],
				$bounds['prev_start'],
				$bounds['prev_end'],
				$channel,
				$bounds['prev_start'],
				$bounds['cur_end'],
				$cfg['min_prev'],
				$cfg['min_loss'],
				$limit
			),
			ARRAY_A
		);

		$out = [];
		foreach ( (array) $rows as $r ) {
			$post_id = (int) ( $r['post_id'] ?? 0 );
			if ( $post_id < 1 ) {
				continue;
			}
			$clicks = (int) ( $r['clicks'] ?? 0 );
			$prev   = (int) ( $r['prev_clicks'] ?? 0 );
			$delta  = $clicks - $prev;
			$pct    = $prev > 0 ? round( ( abs( $delta ) / $prev ) * 100, 1 ) : 0.0;
			$out[]  = [
				'post_id'       => $post_id,
				'title'         => (string) ( $r['title'] ?? '' ),
				'clicks'        => $clicks,
				'prev_clicks'   => $prev,
				'delta_clicks'  => $delta,
				'pct_drop'      => $pct,
				'edit_url'      => get_edit_post_link( $post_id, 'raw' ) ?: '',
				'view_url'      => get_permalink( $post_id ) ?: '',
			];
		}
		return $out;
	}
}

if ( ! function_exists( 'newsai_gsc_traffic_drop_render_panel' ) ) {
	function newsai_gsc_traffic_drop_render_panel( $days = null ) {
		if ( ! newsai_gsc_traffic_drop_enabled() ) {
			return;
		}
		$cfg   = newsai_gsc_traffic_drop_settings();
		$days  = $days === null ? $cfg['days'] : (int) $days;
		$items = newsai_gsc_traffic_drop_find( $days, $cfg['channel'], 6 );
		$ch_labels = [
			'web'        => __( 'Web', 'newsroom-ai-assistant' ),
			'discover'   => __( 'Discover', 'newsroom-ai-assistant' ),
			'googleNews' => __( 'Google News', 'newsroom-ai-assistant' ),
		];
		$ch_label = $ch_labels[ $cfg['channel'] ] ?? $cfg['channel'];
		?>
		<div class="nros-insights-block" style="margin-bottom:20px;">
			<h3><?php echo esc_html__( 'GSC traffic drops — refresh candidates', 'newsroom-ai-assistant' ); ?></h3>
			<p class="nros-insights-table-hint">
				<?php
				echo esc_html(
					sprintf(
						/* translators: 1: channel, 2: comparison days */
						__( '%1$s clicks vs previous %2$d-day window (from synced GSC data).', 'newsroom-ai-assistant' ),
						$ch_label,
						$days
					)
				);
				?>
			</p>
			<?php if ( empty( $items ) ) : ?>
				<p class="description"><?php echo esc_html__( 'No significant click drops in this window — or run GSC Sync to refresh post-level data.', 'newsroom-ai-assistant' ); ?></p>
			<?php else : ?>
				<table class="widefat striped nros-insights-table">
					<thead>
						<tr>
							<th><?php echo esc_html__( 'Article', 'newsroom-ai-assistant' ); ?></th>
							<th><?php echo esc_html__( 'Prev → now', 'newsroom-ai-assistant' ); ?></th>
							<th><?php echo esc_html__( 'Change', 'newsroom-ai-assistant' ); ?></th>
						</tr>
					</thead>
					<tbody>
					<?php foreach ( $items as $item ) : ?>
						<tr>
							<td>
								<?php if ( ! empty( $item['edit_url'] ) ) : ?>
									<a href="<?php echo esc_url( (string) $item['edit_url'] ); ?>"><strong><?php echo esc_html( (string) ( $item['title'] ?? '' ) ); ?></strong></a>
								<?php else : ?>
									<strong><?php echo esc_html( (string) ( $item['title'] ?? '' ) ); ?></strong>
								<?php endif; ?>
							</td>
							<td><?php echo esc_html( number_format_i18n( (int) ( $item['prev_clicks'] ?? 0 ) ) . ' → ' . number_format_i18n( (int) ( $item['clicks'] ?? 0 ) ) ); ?></td>
							<td><span class="nros-chief-delta--down"><?php echo esc_html( number_format_i18n( (int) ( $item['delta_clicks'] ?? 0 ) ) ); ?> (<?php echo esc_html( number_format_i18n( (float) ( $item['pct_drop'] ?? 0 ), 1 ) ); ?>%)</span></td>
						</tr>
					<?php endforeach; ?>
					</tbody>
				</table>
			<?php endif; ?>
		</div>
		<?php
	}
}

if ( ! function_exists( 'newsai_weekly_report_traffic_drop_section' ) ) {
	/**
	 * @return array{enabled:bool,items:list<array<string,mixed>>,days:int}
	 */
	function newsai_weekly_report_traffic_drop_section() {
		if ( ! newsai_gsc_traffic_drop_enabled() ) {
			return [ 'enabled' => false, 'items' => [], 'days' => 28 ];
		}
		$cfg   = newsai_gsc_traffic_drop_settings();
		$items = newsai_gsc_traffic_drop_find( $cfg['days'], $cfg['channel'], 5 );
		return [
			'enabled' => ! empty( $items ),
			'items'   => $items,
			'days'    => $cfg['days'],
		];
	}
}
