<?php
/**
 * Costudio_Admin_Tables — Content Hub rendering + KPIs.
 *
 * Pure static helpers that build the unified Content Hub table rows,
 * priority badges and the KPI aggregates shared by initial page render
 * and AJAX refresh.
 *
 * Extracted from Costudio_Admin as part of Task 2 (PR 8 — Tables split).
 *
 * @package Contentosapp_Studio
 * @since   3.2.0
 */

defined( 'ABSPATH' ) || exit;
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Aggregate queries on plugin-owned table; $table = $wpdb->prefix . constant, all user values pass through $wpdb->prepare placeholders.

class Costudio_Admin_Tables {

	/**
	 * Content Hub KPIs (shared by initial page render and AJAX refresh).
	 *
	 * @return array<string, string|int>
	 */
	public static function get_content_hub_kpis(): array {
		global $wpdb;

		$table = $wpdb->prefix . Costudio_Production::TABLE;
		$base  = "keyword != '' AND is_external = 0";

		$articles_total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE {$base}" );

		$tz         = wp_timezone();
		$now        = new DateTimeImmutable( 'now', $tz );
		$start_this = $now->modify( 'first day of this month' )->setTime( 0, 0, 0 );
		$end_this   = $start_this->modify( '+1 month' );

		$pub_this = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$table} WHERE {$base} AND status = 'completed' AND wp_post_id IS NOT NULL AND wp_post_id > 0
				AND completed_at IS NOT NULL AND completed_at >= %s AND completed_at < %s",
				$start_this->format( 'Y-m-d H:i:s' ),
				$end_this->format( 'Y-m-d H:i:s' )
			)
		);

		$start_prev = $start_this->modify( '-1 month' );
		$pub_prev   = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$table} WHERE {$base} AND status = 'completed' AND wp_post_id IS NOT NULL AND wp_post_id > 0
				AND completed_at IS NOT NULL AND completed_at >= %s AND completed_at < %s",
				$start_prev->format( 'Y-m-d H:i:s' ),
				$start_this->format( 'Y-m-d H:i:s' )
			)
		);

		$pub_diff    = $pub_this - $pub_prev;
		$pub_trend   = $pub_diff > 0 ? 'up' : ( $pub_diff < 0 ? 'down' : 'neutral' );
		$hours_saved = (int) round( $articles_total * 3.7 );

		$month_counts = array();
		$m            = $start_this->modify( '-1 month' );
		for ( $i = 0; $i < 3; $i++ ) {
			$m_start = $m;
			$m_end   = $m_start->modify( '+1 month' );
			$month_counts[] = (int) $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COUNT(*) FROM {$table} WHERE {$base} AND created_at >= %s AND created_at < %s",
					$m_start->format( 'Y-m-d H:i:s' ),
					$m_end->format( 'Y-m-d H:i:s' )
				)
			);
			$m = $m_start->modify( '-1 month' );
		}

		$pace_avg = (int) round( array_sum( $month_counts ) / 3 );

		$curr_month_articles = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$table} WHERE {$base} AND created_at >= %s AND created_at < %s",
				$start_this->format( 'Y-m-d H:i:s' ),
				$end_this->format( 'Y-m-d H:i:s' )
			)
		);

		$pace_trend = $curr_month_articles > $pace_avg ? 'up' : ( $curr_month_articles < $pace_avg ? 'down' : 'neutral' );

		return array(
			'articles_total_raw'   => $articles_total,
			'articles_total_fmt'   => number_format_i18n( $articles_total, 0 ),
			'published_month'      => $pub_this,
			'published_month_fmt'  => number_format_i18n( $pub_this, 0 ),
			'pub_diff'             => $pub_diff,
			'pub_trend'            => $pub_trend,
			'hours_saved'          => $hours_saved,
			'hours_saved_fmt'      => number_format_i18n( $hours_saved, 0 ) . 'h',
			'pace_avg'             => $pace_avg,
			'pace_avg_fmt'         => (string) $pace_avg,
			'curr_month_articles'  => $curr_month_articles,
			'pace_trend'           => $pace_trend,
		);
	}

	/**
	 * Render a single unified Content Hub row.
	 *
	 * @param object               $row         Normalized row (source, id, status, etc.).
	 * @param array<string, array> $sites       Site configs keyed by site_key.
	 * @param array<int, string>   $agent_names Agent index → label.
	 * @return void Echoes the row HTML directly, each value escaped inline (escape late).
	 */
	public static function render_unified_row( object $row, array $sites, array $agent_names ): void {
		$is_plan    = $row->source === 'plan';
		$id         = (int) $row->id;
		$site_cfg   = $sites[ $row->site_key ] ?? array();
		$site_name  = costudio_site_display_name( $site_cfg, (string) $row->site_key );
		$st         = $row->status;

		$status_map = array(
			'planned'   => array( 'label' => __( 'Planned', 'contentosapp-studio' ),   'glyph' => '✎', 'class' => 'fos-status-pill--planned' ),
			'queued'    => array( 'label' => __( 'Queued', 'contentosapp-studio' ),    'glyph' => '⏱', 'class' => 'fos-status-pill--queued' ),
			'producing' => array( 'label' => __( 'Producing', 'contentosapp-studio' ), 'glyph' => '●', 'class' => 'fos-status-pill--producing' ),
			'published' => array( 'label' => __( 'Published', 'contentosapp-studio' ), 'glyph' => '✓', 'class' => 'fos-status-pill--published' ),
			'draft'     => array( 'label' => __( 'Draft', 'contentosapp-studio' ),     'glyph' => '✎', 'class' => 'fos-status-pill--draft' ),
			'error'     => array( 'label' => __( 'Failed', 'contentosapp-studio' ),    'glyph' => '✕', 'class' => 'fos-status-pill--error' ),
			'paused'    => array( 'label' => __( 'Paused', 'contentosapp-studio' ),    'glyph' => 'Ⅱ', 'class' => 'fos-status-pill--paused' ),
			'cancelled' => array( 'label' => __( 'Cancelled', 'contentosapp-studio' ), 'glyph' => '✕', 'class' => 'fos-status-pill--cancelled' ),
		);
		$sm   = $status_map[ $st ] ?? $status_map['planned'];
		$anim = $st === 'producing' ? 'animation:fos-pulse 1.4s infinite' : '';

		$agent_num = (int) $row->current_agent;
		$inputs    = json_decode( $row->inputs ?? '{}', true );
		$version   = $inputs['pipeline_v'] ?? 6;
		$max_agents = ( $version == 7 ) ? 7 : 6;
		$pct       = $agent_num > 0 ? (int) round( ( $agent_num / $max_agents ) * 100 ) : 0;
		$agent_lbl = $agent_names[ $agent_num ] ?? '';

		$updated_raw = ( $row->updated_at ?? '' ) ?: ( $row->created_at ?? '' );
		$updated_str = $updated_raw ? human_time_diff( strtotime( $updated_raw ) ) . ' ' . __( 'ago', 'contentosapp-studio' ) : '—';

		$display_date_raw = ( $is_plan && ! empty( $row->planned_date ) ) ? $row->planned_date : ( $row->created_at ?? '' );
		if ( $display_date_raw ) {
			try {
				$tz_now        = new \DateTimeImmutable( 'now', wp_timezone() );
				$today_ymd     = $tz_now->format( 'Y-m-d' );
				$yesterday_ymd = $tz_now->modify( '-1 day' )->format( 'Y-m-d' );
			} catch ( \Throwable $e ) {
				$today_ymd = $yesterday_ymd = '';
			}
			$raw_ymd = substr( (string) $display_date_raw, 0, 10 );
			if ( $raw_ymd === $today_ymd ) {
				$display_date_str = esc_html__( 'Today', 'contentosapp-studio' );
			} elseif ( $raw_ymd === $yesterday_ymd ) {
				$display_date_str = esc_html__( 'Yesterday', 'contentosapp-studio' );
			} else {
				$display_date_str = esc_html( mysql2date( 'd/m/Y', $display_date_raw ) );
			}
		} else {
			$display_date_str = '—';
		}

		$detail_url   = admin_url( 'admin.php?page=costudio-detalhe&id=' . $id );
		$producao_url = admin_url( 'admin.php?page=costudio-studio&tab=producao&plan_id=' . $id );

		?>
		<tr data-row-id="<?php echo esc_attr( (string) $id ); ?>" data-source="<?php echo esc_attr( $row->source ); ?>">
			<td class="fos-col-check">
				<input type="checkbox" class="fos-row-checkbox" value="<?php echo esc_attr( (string) $id ); ?>" aria-label="<?php esc_attr_e( 'Select row', 'contentosapp-studio' ); ?>">
			</td>
			<td>
				<div class="fos-central-cell-title" title="<?php echo esc_attr( $row->title ?: $row->keyword ); ?>"><?php echo esc_html( $row->title ?: $row->keyword ); ?></div>
				<?php if ( $row->keyword ) : ?>
					<div class="fos-central-cell-kw">🔑 <?php echo esc_html( $row->keyword ); ?></div>
				<?php endif; ?>
			</td>
			<td>
				<?php if ( $site_name ) : ?>
					<code class="fos-central-cell-site"><?php echo esc_html( $site_name ); ?></code>
				<?php else : ?>
					<span class="fos-central-cell-site--empty">—</span>
				<?php endif; ?>
			</td>
			<td><?php echo wp_kses_post( self::render_central_priority_badge( $row->priority ) ); ?></td>
			<td>
				<span class="fos-central-cell-date"><?php echo esc_html( $display_date_str ); ?></span>
			</td>
			<td>
				<span class="fos-status-pill <?php echo esc_attr( $sm['class'] ); ?>">
					<span<?php if ( $anim ) { echo ' style="' . esc_attr( $anim ) . '"'; } ?>><?php echo esc_html( $sm['glyph'] ); ?></span>
					<?php echo esc_html( $sm['label'] ); ?>
				</span>
			</td>
			<td>
				<div class="fos-central-actions">
					<?php if ( $is_plan ) : ?>
						<?php if ( 'planned' === $st ) : ?>
							<a href="<?php echo esc_url( $producao_url ); ?>" class="fos-btn fos-btn--sm" title="<?php esc_attr_e( 'Start production', 'contentosapp-studio' ); ?>"><span class="dashicons dashicons-performance"></span></a>
						<?php endif; ?>
						<button type="button" class="fos-btn fos-btn--sm fos-edit-plan-btn" data-id="<?php echo esc_attr( (string) $id ); ?>" title="<?php esc_attr_e( 'Edit idea', 'contentosapp-studio' ); ?>"><span class="dashicons dashicons-edit"></span></button>
						<button type="button" class="fos-btn fos-btn--sm fos-btn--danger-text fos-delete-plan-btn" data-id="<?php echo esc_attr( (string) $id ); ?>" title="<?php esc_attr_e( 'Delete idea', 'contentosapp-studio' ); ?>"><span class="dashicons dashicons-trash"></span></button>
					<?php else : ?>
						<a href="<?php echo esc_url( $detail_url ); ?>" class="fos-btn fos-btn--sm" title="<?php esc_attr_e( 'Open details', 'contentosapp-studio' ); ?>"><span class="dashicons dashicons-visibility"></span></a>
						<button type="button" class="fos-btn fos-btn--sm fos-btn--danger-text fos-delete-production-btn" data-id="<?php echo esc_attr( (string) $id ); ?>" title="<?php esc_attr_e( 'Delete production', 'contentosapp-studio' ); ?>"><span class="dashicons dashicons-trash"></span></button>
					<?php endif; ?>
				</div>
			</td>
		</tr>
		<?php
		// Row HTML is echoed inline above (escape late); nothing to return.
	}

	/**
	 * Priority badge rendering.
	 */
	public static function render_central_priority_badge( ?string $priority ): string {
		$p = $priority && in_array( $priority, array( 'high', 'medium', 'low' ), true ) ? $priority : '';
		$labels = array(
			'high'   => __( 'High', 'contentosapp-studio' ),
			'medium' => __( 'Medium', 'contentosapp-studio' ),
			'low'    => __( 'Low', 'contentosapp-studio' ),
		);
		if ( '' === $p ) {
			return '<span class="fos-central-priority fos-central-priority--empty">—</span>';
		}
		return sprintf(
			'<span class="fos-priority-badge fos-priority-badge--%1$s">%2$s</span>',
			esc_attr( $p ),
			esc_html( $labels[ $p ] ?? $p )
		);
	}
}
