<?php
namespace WPLens\Schema\Generators;

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

final class ArticleGenerator implements \WPLens\Schema\Generator {

	public function get_slug(): string  { return 'article'; }
	public function get_label(): string { return __( 'Article / BlogPosting (posts)', 'lens-ai-visibility-monitor' ); }

	public function applies( ?\WP_Post $post = null ): bool {
		if ( ! $post instanceof \WP_Post ) { return false; }
		// Only for posts (and custom post types that look post-like).
		return in_array( $post->post_type, array( 'post' ), true );
	}

	public function generate( ?\WP_Post $post = null ): ?array {
		if ( ! $post ) { return null; }

		$url    = get_permalink( $post );
		$home   = home_url( '/' );
		$author = get_userdata( (int) $post->post_author );

		$payload = array(
			'@type'            => 'BlogPosting',
			'@id'              => $url . '#article',
			'mainEntityOfPage' => array( '@id' => $url . '#webpage' ),
			'headline'         => wp_strip_all_tags( get_the_title( $post ) ),
			'datePublished'    => $this->rfc3339( $post->post_date_gmt ),
			'dateModified'     => $this->rfc3339( $post->post_modified_gmt ),
			'inLanguage'       => get_bloginfo( 'language' ),
			'isPartOf'         => array( '@id' => $home . '#website' ),
			'publisher'        => array( '@id' => $home . '#organization' ),
			'wordCount'        => (int) str_word_count( wp_strip_all_tags( (string) $post->post_content ) ),
		);

		if ( $author ) {
			$payload['author'] = array(
				'@type' => 'Person',
				'name'  => $author->display_name,
				'url'   => get_author_posts_url( $author->ID ),
			);
		}

		$image_id = (int) get_post_thumbnail_id( $post->ID );
		if ( $image_id > 0 ) {
			$src = wp_get_attachment_image_url( $image_id, 'full' );
			if ( $src ) {
				$payload['image'] = $src;
			}
		}

		$categories = get_the_category( $post->ID );
		if ( $categories ) {
			$payload['articleSection'] = wp_list_pluck( $categories, 'name' );
		}

		$tags = get_the_tags( $post->ID );
		if ( $tags ) {
			$payload['keywords'] = wp_list_pluck( $tags, 'name' );
		}

		return $payload;
	}

	private function rfc3339( string $mysql ): string {
		$ts = mysql2date( 'U', $mysql, false );
		return $ts ? gmdate( 'c', (int) $ts ) : '';
	}
}
