<?php
/**
 * Rank Math SEO metadata adapter.
 *
 * @package SmartyPress_AI_Engine
 */

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

/**
 * Writes neutral SEO metadata to Rank Math post meta.
 */
class SmartyPress_AI_Content_Generator_Rank_Math_SEO_Metadata_Adapter implements SmartyPress_AI_Content_Generator_SEO_Metadata_Adapter_Interface {

	/**
	 * Adapter identifier.
	 *
	 * @return string
	 */
	public function get_name() {
		return 'rank_math';
	}

	/**
	 * Whether Rank Math is active.
	 *
	 * @return bool
	 */
	public function is_available() {
		return defined( 'RANK_MATH_FILE' ) || defined( 'RANK_MATH_VERSION' ) || function_exists( 'rank_math' );
	}

	/**
	 * Apply metadata to Rank Math fields.
	 *
	 * @param int   $post_id Post ID.
	 * @param array $metadata Neutral metadata package.
	 * @return array Updated fields.
	 */
	public function apply( $post_id, array $metadata ) {
		$updated = array();

		if ( '' !== $metadata['seo_title'] ) {
			update_post_meta( $post_id, 'rank_math_title', $metadata['seo_title'] );
			$updated[] = 'seo_title';
		}

		if ( '' !== $metadata['meta_description'] ) {
			update_post_meta( $post_id, 'rank_math_description', $metadata['meta_description'] );
			$updated[] = 'meta_description';
		}

		if ( ! empty( $metadata['focus_keywords'] ) ) {
			update_post_meta( $post_id, 'rank_math_focus_keyword', implode( ', ', $metadata['focus_keywords'] ) );
			$updated[] = 'focus_keywords';
		}

		return $updated;
	}
}
