<?php

namespace Waypoint\Agent\Integrations;

use Waypoint\Agent\Base\Thing;

class Rank_Math_Og_Fallback extends Thing {

	public function attach_hooks(): void {
		add_action( 'rank_math/opengraph/facebook/add_images', [ $this, 'maybe_add_default_image' ], 20 );
	}

	public function maybe_add_default_image( $image ): void {
		if ( ! is_front_page() || ! is_object( $image ) || ! method_exists( $image, 'add_image_by_id' ) ) {
			return;
		}

		$titles   = get_option( 'rank-math-options-titles', [] );
		$front_id = (int) get_option( 'page_on_front' );

		// Respect an explicit homepage-specific Rank Math social image.
		if ( ! empty( $titles['homepage_facebook_image_id'] ) ) {
			return;
		}

		// Respect an explicit page-level social image or featured image on the static homepage.
		if ( $front_id ) {
			$rm_fb_image_id = get_post_meta( $front_id, 'rank_math_facebook_image_id', true );
			if ( ! empty( $rm_fb_image_id ) || has_post_thumbnail( $front_id ) ) {
				return;
			}
		}

		$default_id = ! empty( $titles['open_graph_image_id'] ) ? (int) $titles['open_graph_image_id'] : 0;

		if ( $default_id ) {
			$image->add_image_by_id( $default_id );
		}
	}
}
