<?php
/**
 * Image Sitemap
 *
 * Extracts image URLs for the sitemap.
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\Sitemap;

/**
 * Extracts internal images for a post
 */
class Images {

	/**
	 * Get image URLs for a post.
	 *
	 * @param int $post_id Post ID.
	 * @return array
	 */
	public static function get_for_post( $post_id ) {
		$post_id = (int) $post_id;
		if ( $post_id <= 0 ) {
			return array();
		}

		$urls = array();

		// Featured image.
		$thumbnail_id = get_post_thumbnail_id( $post_id );
		if ( $thumbnail_id ) {
			$url = self::get_attachment_url( $thumbnail_id );
			if ( $url ) {
				$urls[] = $url;
			}
		}

		// Content attachments.
		$content = get_post_field( 'post_content', $post_id );
		$media   = get_attached_media( 'image', $post_id );
		foreach ( $media as $attachment ) {
			if ( strpos( $content, 'wp-image-' . $attachment->ID ) !== false || strpos( $content, $attachment->guid ) !== false ) {
				$url = self::get_attachment_url( $attachment->ID );
				if ( $url && ! in_array( $url, $urls, true ) ) {
					$urls[] = $url;
				}
			}
		}

		// Parse gallery blocks.
		if ( has_block( 'gallery', $content ) ) {
			$blocks = parse_blocks( $content );
			foreach ( $blocks as $block ) {
				if ( 'core/gallery' !== $block['blockName'] ) {
					continue;
				}
				if ( ! empty( $block['attrs']['ids'] ) && is_array( $block['attrs']['ids'] ) ) {
					foreach ( $block['attrs']['ids'] as $image_id ) {
						$url = self::get_attachment_url( $image_id );
						if ( $url && ! in_array( $url, $urls, true ) ) {
							$urls[] = $url;
						}
					}
				}
			}
		}

		$urls = apply_filters( 'seovaultseo_sitemap_image_urls', $urls, $post_id );

		return array_values( array_filter( $urls ) );
	}

	/**
	 * Get attachment URL, skipping external/noindexed attachments.
	 *
	 * @param int $attachment_id Attachment ID.
	 * @return string|false
	 */
	private static function get_attachment_url( $attachment_id ) {
		$attachment_id = (int) $attachment_id;
		if ( $attachment_id <= 0 ) {
			return false;
		}

		$attachment = get_post( $attachment_id );
		if ( ! $attachment || 'attachment' !== $attachment->post_type ) {
			return false;
		}

		$noindex = get_post_meta( $attachment_id, '_seovault_robots_noindex', true );
		if ( '1' === $noindex ) {
			return false;
		}

		$url = wp_get_attachment_url( $attachment_id );
		if ( empty( $url ) ) {
			return false;
		}

		$site_url = home_url();
		if ( 0 !== strpos( $url, $site_url ) ) {
			return false;
		}

		return $url;
	}
}
