<?php
/**
 * AI readiness score.
 *
 * @package MicropediaAISearchOptimizer
 */

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

/** Score helper. */
class Micropedia_AI_Score {
	/** Init hooks. */
	public static function init() {
		add_filter( 'manage_posts_columns', array( __CLASS__, 'add_column' ) );
		add_action( 'manage_posts_custom_column', array( __CLASS__, 'render_column' ), 10, 2 );
	}

	/**
	 * Add admin column.
	 *
	 * @param array<string,string> $columns Columns.
	 * @return array<string,string>
	 */
	public static function add_column( $columns ) {
		if ( micropedia_ai_is_pro() && micropedia_ai_get_option( 'enable_ai_score', 0 ) ) {
			$columns['micropedia_ai_score'] = esc_html__( 'AI Score', 'micropedia-ai-search-optimizer' );
		}
		return $columns;
	}

	/**
	 * Render score column.
	 *
	 * @param string $column Column.
	 * @param int    $post_id Post ID.
	 */
	public static function render_column( $column, $post_id ) {
		if ( 'micropedia_ai_score' !== $column ) {
			return;
		}
		echo esc_html( (string) self::calculate_score( (int) $post_id ) );
	}

	/**
	 * Calculate score.
	 *
	 * @param int $post_id Post ID.
	 * @return int
	 */
	public static function calculate_score( $post_id ) {
		$post = get_post( $post_id );
		if ( ! $post ) {
			return 0;
		}
		$content = (string) $post->post_content;
		$score   = 0;
		$score  += preg_match( '/<h1[\s>]/i', $content ) || '' !== get_the_title( $post ) ? 20 : 0;
		$score  += preg_match_all( '/<h2[\s>]/i', $content ) >= 2 ? 20 : 0;
		$score  += str_word_count( wp_strip_all_tags( $content ) ) >= 300 ? 20 : 0;
		$score  += ! empty( $post->post_author ) ? 15 : 0;
		$score  += '0000-00-00 00:00:00' !== $post->post_modified_gmt ? 15 : 0;
		$score  += micropedia_ai_get_option( 'enable_schema', 1 ) ? 10 : 0;
		return min( 100, (int) $score );
	}
}
