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

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

/**
 * Writes neutral SEO metadata to Yoast post meta.
 */
class SmartyPress_AI_Content_Generator_Yoast_SEO_Metadata_Adapter implements SmartyPress_AI_Content_Generator_SEO_Metadata_Adapter_Interface {

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

	/**
	 * Whether Yoast SEO is active.
	 *
	 * @return bool
	 */
	public function is_available() {
		return defined( 'WPSEO_VERSION' ) || defined( 'WPSEO_FILE' ) || class_exists( 'WPSEO_Options' ) || function_exists( 'wpseo_init' );
	}

	/**
	 * Apply metadata to Yoast 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, '_yoast_wpseo_title', $metadata['seo_title'] );
			$updated[] = 'seo_title';
		}

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

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

		return $updated;
	}
}
