<?php
/**
 * Adds an "AEO" column to the Posts and Pages list tables.
 *
 * Shows the most recent scan score (colour-pilled) and a "Scan now" link
 * that opens the Scans page pre-populated.
 *
 * @package WPLens
 */

namespace WPLens\Admin;

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

final class PostsColumn {

	public function register(): void {
		foreach ( array( 'post', 'page' ) as $type ) {
			add_filter( "manage_{$type}_posts_columns",       array( $this, 'add_column' ) );
			add_action( "manage_{$type}_posts_custom_column", array( $this, 'render_column' ), 10, 2 );
			add_filter( "manage_edit-{$type}_sortable_columns", array( $this, 'sortable' ) );
		}
	}

	public function add_column( array $columns ): array {
		// Insert before "date" if it exists, else append.
		$new = array();
		foreach ( $columns as $key => $label ) {
			if ( 'date' === $key ) {
				$new['lens_aeo'] = __( 'AEO', 'lens-ai-visibility-monitor' );
			}
			$new[ $key ] = $label;
		}
		if ( ! isset( $new['lens_aeo'] ) ) {
			$new['lens_aeo'] = __( 'AEO', 'lens-ai-visibility-monitor' );
		}
		return $new;
	}

	public function sortable( array $columns ): array {
		$columns['lens_aeo'] = 'lens_aeo';
		return $columns;
	}

	public function render_column( string $column, int $post_id ): void {
		if ( 'lens_aeo' !== $column ) {
			return;
		}

		$repo = new \WPLens\Scans\ScanRepository();
		$row  = $repo->latest_for_post( $post_id );

		echo '<div class="lens-aeo-cell">';
		if ( $row && null !== $row['score'] ) {
			$score = (int) $row['score'];
			$cls   = $score >= 75 ? 's-high' : ( $score >= 50 ? 's-mid' : 's-low' );
			printf(
				'<span class="lens-score %s" title="%s">%s</span>',
				esc_attr( $cls ),
				esc_attr( sprintf( /* translators: %s — date */ __( 'Scanned %s', 'lens-ai-visibility-monitor' ), $row['created_at'] ) ),
				esc_html( (string) $score )
			);
		} else {
			echo '<span class="lens-pill" style="background:#f0f0f1;color:#646970;">—</span>';
		}
		printf(
			'<a class="lens-cta" href="%s">%s</a>',
			esc_url( add_query_arg( array( 'page' => 'lens-scans', 'post_id' => $post_id ), admin_url( 'admin.php' ) ) ),
			esc_html( $row ? __( 'Re-scan', 'lens-ai-visibility-monitor' ) : __( 'Scan now', 'lens-ai-visibility-monitor' ) )
		);
		echo '</div>';
	}
}
