<?php
/**
 * Adds WPSeo support for Essential Grid.
 *
 * @package   Essential_Grid
 * @author    ThemePunch <info@themepunch.com>
 * @link      https://www.essential-grid.com/
 * @copyright 2025 ThemePunch
 */

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

/**
 * WPML Class For Essential Grid.
 */
class Essential_Grid_Wpseo {

	/**
	 * Collection of processed grid images.
	 *
	 * @var array
	 */
	private $grid_images = array();

	/**
	 * Instance of this class.
	 *
	 * @var null|object
	 */
	protected static $instance = null;

	/**
	 * Return an instance of this class.
	 *
	 * @return object A single instance of this class.
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Set up hooks.
	 */
	private function __construct() {
		// Add esg images to yoast XML sitemap.
		add_filter( 'wpseo_sitemap_urlimages', array( $this, 'sitemap_urlimages' ), 10, 2 );
	}

	/**
	 * Scan post for essential grid shortcodes and process each shortcode to extract images.
	 *
	 * @param array $images  WPSeo images.
	 * @param int   $post_id current post ID.
	 * @return array
	 */
	public function sitemap_urlimages( $images, $post_id ) {
		if ( ! has_action( 'essgrid_get_media_html', array( $this, 'get_grid_images' ) ) ) {
			add_action( 'essgrid_get_media_html', array( $this, 'get_grid_images' ) );
		}

		$content = get_post_field( 'post_content', $post_id );
		if ( ! has_shortcode( $content, 'ess_grid' ) ) {
			return $images;
		}

		preg_match_all( '/' . get_shortcode_regex() . '/', $content, $matches, PREG_SET_ORDER );

		foreach ( $matches as $m ) {
			if ( 'ess_grid' !== $m[2] ) {
				continue;
			}

			$this->grid_images = array();
			Essential_Grid::register_shortcode( shortcode_parse_atts( $m[3] ) );
			$images = array_merge( $images, $this->grid_images );
		}

		return $images;
	}

	/**
	 * Add image to internal array along with its title / alt.
	 *
	 * @param string $img     image URL.
	 * @return void
	 */
	public function get_grid_images( $img ) {
		// Skip external URLs.
		if ( strpos( $img, get_bloginfo( 'url' ) ) !== 0 ) {
			return;
		}

		$add = array(
			'src'   => $img,
			'title' => '',
		);

		$media_id = attachment_url_to_postid( $img );
		if ( $media_id ) {
			$media_info   = esg_get_attachment_info( $media_id );
			$add['title'] = ! empty( $media_info['title'] ) ? $media_info['title'] : $media_info['alt'];
		}

		$this->grid_images[] = $add;
	}
}
