<?php
/**
 * SEO Meta Writer
 *
 * Utility class for writing SEO meta content to plugin-specific meta keys.
 *
 * @package AIPT\Api\BulkGenerator\SeoMeta\Core
 */

namespace AIPT\Api\BulkGenerator\SeoMeta\Core;

/**
 * Writes SEO meta content to the correct plugin-specific meta keys.
 *
 * Handles sanitization and validation for SEO plugin meta fields.
 * Supports writing individual fields or bulk operations.
 *
 * @since 2.4.0
 */
class SeoMetaWriter {

	/**
	 * Writes a single SEO meta field to a product.
	 *
	 * @param int    $product_id The WooCommerce product ID.
	 * @param string $meta_type  The meta type: 'title', 'description', or 'focus_keyword'.
	 * @param string $content    The content to write (will be sanitized).
	 * @param string $plugin_slug The SEO plugin slug (e.g., 'yoast', 'rankmath').
	 *
	 * @return bool True on success, false on failure.
	 *
	 * @example
	 * $writer = new SeoMetaWriter();
	 * $success = $writer->write(123, 'title', 'My Product Title', 'yoast');
	 */
	public function write( $product_id, $meta_type, $content, $plugin_slug ) {

		$product_id = absint( $product_id );
		if ( $product_id <= 0 ) {
			return false;
		}

		$meta_keys = SeoPluginDetector::get_meta_keys( $plugin_slug );
		if ( null === $meta_keys ) {
			return false;
		}

		$key_name = $meta_type . '_key';
		if ( ! isset( $meta_keys[ $key_name ] ) ) {
			return false;
		}

		$meta_key = $meta_keys[ $key_name ];

		if ( null === $meta_key ) {
			return false;
		}

		if ( ! is_scalar( $content ) ) {
			return false;
		}

	$sanitized_content = sanitize_text_field( trim( (string) $content ) );

		$current_value = \get_post_meta( $product_id, $meta_key, true );
		$current_value = ( false === $current_value ) ? '' : $current_value;

		$normalized_current   = sanitize_text_field( trim( (string) $current_value ) );
	$normalized_sanitized = $sanitized_content;
	if ( $normalized_current === $normalized_sanitized ) {
		return true; 
	}

	$result = \update_post_meta( $product_id, $meta_key, $sanitized_content );

		return false !== $result;
	}

	/**
	 * Writes multiple SEO meta fields to a product in bulk.
	 *
	 * @param int    $product_id The WooCommerce product ID.
	 * @param array  $data       Array of meta fields to write, e.g., ['title' => '...', 'description' => '...'].
	 * @param string $plugin_slug The SEO plugin slug (e.g., 'yoast', 'rankmath').
	 *
	 * @return array Array of results keyed by meta type, e.g., ['title' => true, 'description' => true].
	 *
	 * @example
	 * $writer = new SeoMetaWriter();
	 * $results = $writer->bulkWrite(123, [
	 *     'title' => 'My Product Title',
	 *     'description' => 'My product description',
	 *     'focus_keyword' => 'product keyword'
	 * ], 'yoast');
	 * 
	 */
	public function bulkWrite( $product_id, $data, $plugin_slug ) {
		$results = array();

		if ( ! is_array( $data ) ) {
			return $results;
		}

		foreach ( $data as $meta_type => $content ) {
			$results[ $meta_type ] = $this->write( $product_id, $meta_type, $content, $plugin_slug );
		}

		return $results;
	}

	/**
	 * Builds supported writer data from generated SEO meta fields.
	 *
	 * @param array  $source      Generated SEO meta data.
	 * @param string $plugin_slug The SEO plugin slug.
	 * @return array Writer-ready SEO meta data.
	 */
	public static function buildWriteData( array $source, string $plugin_slug ): array {
		$meta_keys = SeoPluginDetector::get_meta_keys( $plugin_slug );
		if ( ! is_array( $meta_keys ) ) {
			return array();
		}

		$write_data = array();
		$field_map  = array(
			'meta_title'       => array( 'writer_key' => 'title', 'meta_key' => 'title_key', 'allow_empty' => true ),
			'meta_description' => array( 'writer_key' => 'description', 'meta_key' => 'description_key', 'allow_empty' => true ),
			'focus_keyword'    => array( 'writer_key' => 'focus_keyword', 'meta_key' => 'focus_keyword_key', 'allow_empty' => false ),
		);

		foreach ( $field_map as $source_key => $field ) {
			if ( empty( $meta_keys[ $field['meta_key'] ] ) || ! isset( $source[ $source_key ] ) || ! is_string( $source[ $source_key ] ) ) {
				continue;
			}

			if ( ! $field['allow_empty'] && '' === trim( $source[ $source_key ] ) ) {
				continue;
			}

			$write_data[ $field['writer_key'] ] = $source[ $source_key ];
		}

		return $write_data;
	}
}
