<?php
namespace WPLens\Schema\Generators;

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

final class WebpageGenerator implements \WPLens\Schema\Generator {

	public function get_slug(): string  { return 'webpage'; }
	public function get_label(): string { return __( 'WebPage (every page)', 'lens-ai-visibility-monitor' ); }

	public function applies( ?\WP_Post $post = null ): bool {
		return $post instanceof \WP_Post;
	}

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

		$url   = get_permalink( $post );
		$home  = home_url( '/' );
		$title = wp_strip_all_tags( get_the_title( $post ) );

		$payload = array(
			'@type'        => 'WebPage',
			'@id'          => $url . '#webpage',
			'url'          => $url,
			'name'         => $title,
			'description'  => $this->description( $post ),
			'inLanguage'   => get_bloginfo( 'language' ),
			'isPartOf'     => array( '@id' => $home . '#website' ),
			'datePublished'=> mysql_to_rfc3339( $post->post_date_gmt ),
			'dateModified' => mysql_to_rfc3339( $post->post_modified_gmt ),
		);

		$image = $this->primary_image_url( $post );
		if ( $image ) {
			$payload['primaryImageOfPage'] = array(
				'@type' => 'ImageObject',
				'url'   => $image,
			);
		}

		return $payload;
	}

	private function description( \WP_Post $post ): string {
		$candidates = array(
			'_yoast_wpseo_metadesc',
			'rank_math_description',
			'_aioseo_description',
			'_genesis_description',
		);
		foreach ( $candidates as $k ) {
			$v = get_post_meta( $post->ID, $k, true );
			if ( is_string( $v ) && '' !== trim( $v ) ) {
				return $v;
			}
		}
		$excerpt = wp_strip_all_tags( (string) $post->post_excerpt );
		if ( '' !== $excerpt ) {
			return $excerpt;
		}
		return wp_trim_words( wp_strip_all_tags( (string) $post->post_content ), 30, '…' );
	}

	private function primary_image_url( \WP_Post $post ): string {
		$id = (int) get_post_thumbnail_id( $post->ID );
		if ( $id > 0 ) {
			$src = wp_get_attachment_image_url( $id, 'full' );
			if ( $src ) { return $src; }
		}
		// Fallback: first <img> in content.
		if ( preg_match( '#<img[^>]+src=["\']([^"\']+)["\']#i', (string) $post->post_content, $m ) ) {
			return $m[1];
		}
		return '';
	}
}

if ( ! function_exists( 'mysql_to_rfc3339' ) ) {
	function mysql_to_rfc3339( $mysql ) {
		$ts = mysql2date( 'U', $mysql, false );
		return $ts ? gmdate( 'c', $ts ) : '';
	}
}
