<?php
/**
 * All in One SEO metadata adapter.
 *
 * @package SmartyPress_AI_Engine
 */

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

/**
 * Writes neutral SEO metadata to AIOSEO post meta.
 */
class SmartyPress_AI_Content_Generator_AIOSEO_Metadata_Adapter implements SmartyPress_AI_Content_Generator_SEO_Metadata_Adapter_Interface {

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

	/**
	 * Whether AIOSEO is active.
	 *
	 * @return bool
	 */
	public function is_available() {
		return defined( 'AIOSEO_VERSION' ) || function_exists( 'aioseo' ) || class_exists( '\AIOSEO\Plugin\AIOSEO' );
	}

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

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

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

		return $updated;
	}
}
