<?php

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

class AIEO_SEO_Admin_Columns {

	
	private static $cache = array();

	
	private static function post_types() {
		return array_keys( AIEO_SEO_Score::public_post_types() );
	}

	public static function register() {
		if ( ! class_exists( 'AIEO_SEO_Score' ) || ! AIEO_SEO_Score::enabled() ) {
			return;
		}
		add_filter( 'the_posts', array( __CLASS__, 'prime' ), 10, 2 );
		
		
		add_action( 'admin_init', static function () {
			foreach ( self::post_types() as $pt ) {
				add_filter( "manage_{$pt}_posts_columns", array( __CLASS__, 'add_column' ) );
				add_action( "manage_{$pt}_posts_custom_column", array( __CLASS__, 'render_column' ), 10, 2 );
			}
		} );
	}

	public static function add_column( $cols ) {
		$cols['aieo_seo'] = __( 'SEO', 'ai-eshop-optimizer' );
		return $cols;
	}

	
	public static function prime( $posts, $query ) {
		if ( ! is_admin() || empty( $posts ) || ! is_object( $query ) || ! $query->is_main_query() ) {
			return $posts;
		}
		$types = self::post_types();
		$ids   = array();
		foreach ( $posts as $p ) {
			if ( is_object( $p ) && isset( $p->ID ) && in_array( (string) $p->post_type, $types, true ) ) {
				$ids[] = (int) $p->ID;
			}
		}
		if ( empty( $ids ) || empty( $types ) ) {
			return $posts;
		}
		global $wpdb;
		$t       = $wpdb->prefix . 'aieo_seo_scores';
		$in      = implode( ',', array_map( 'intval', $ids ) );
		$type_in = "'" . implode( "','", array_map( 'esc_sql', $types ) ) . "'";
		
		$rows = $wpdb->get_results( "SELECT object_id, score, fix_count, is_pillar FROM `{$t}` WHERE object_type IN ({$type_in}) AND object_id IN ({$in})", ARRAY_A );
		foreach ( (array) $rows as $r ) {
			self::$cache[ (int) $r['object_id'] ] = $r;
		}
		return $posts;
	}

	public static function render_column( $col, $post_id ) {
		if ( 'aieo_seo' !== $col ) {
			return;
		}
		$post_id = (int) $post_id;
		if ( ! isset( self::$cache[ $post_id ] ) ) {
			echo '<span style="color:#cbd5e1;">&mdash;</span>';
			return;
		}
		$r      = self::$cache[ $post_id ];
		$score  = (int) $r['score'];
		$fix    = (int) ( $r['fix_count'] ?? 0 );
		$color  = $score >= 80 ? '#15803d' : ( $score >= 50 ? '#b45309' : '#b91c1c' );
		$out    = '<strong style="color:' . esc_attr( $color ) . ';">' . $score . '</strong>';
		if ( $fix > 0 ) {
			$out .= ' <span style="color:#94a3b8;font-size:11px;">(' . $fix . ')</span>';
		}
		if ( ! empty( $r['is_pillar'] ) ) {
			$out .= ' <span title="' . esc_attr__( 'Pillar', 'ai-eshop-optimizer' ) . '" style="color:#7c3aed;">&#9733;</span>';
		}
		echo $out; 
	}
}
