<?php
/**
 * Post Helpers
 *
 * Standalone helper functions for post taxonomy and meta operations.
 * Extracted from AbstractPostAction for use by closure-based action handlers.
 *
 * @package Sequensy\Integrations\WordPress
 * @since 2.0.0
 */

declare(strict_types=1);

namespace Sequensy\Integrations\WordPress\Helpers;

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Class PostHelpers
 *
 * Static methods for post taxonomy and meta field operations.
 */
class PostHelpers {

	/**
	 * Set post categories and tags.
	 *
	 * @param int   $post_id Post ID.
	 * @param array $config  Action configuration.
	 * @return void
	 */
	public static function set_taxonomies( int $post_id, array $config ): void {
		// Set categories if provided.
		if ( ! empty( $config['post_category'] ) ) {
			$categories = $config['post_category'];

			// Convert comma-separated string to array (schema field is type: text).
			if ( is_string( $categories ) ) {
				$categories = array_filter( array_map( 'trim', explode( ',', $categories ) ) );
			}

			if ( is_array( $categories ) && ! empty( $categories ) ) {
				$category_ids = self::resolve_category_ids( $categories );

				if ( ! empty( $category_ids ) ) {
					wp_set_post_categories( $post_id, $category_ids );
				}
			}
		}

		// Set tags if provided.
		if ( ! empty( $config['tags_input'] ) ) {
			// wp_set_post_tags handles both IDs and names, and creates tags if needed.
			wp_set_post_tags( $post_id, $config['tags_input'] );
		}
	}

	/**
	 * Resolve category names or IDs to term IDs.
	 *
	 * @param array $categories Array of category names or IDs.
	 * @return array Array of category term IDs.
	 */
	public static function resolve_category_ids( array $categories ): array {
		$category_ids = array();

		foreach ( $categories as $category ) {
			if ( is_numeric( $category ) ) {
				// Category ID provided.
				$category_ids[] = absint( $category );
			} else {
				// Category name provided - get or create.
				$term = get_term_by( 'name', $category, 'category' );

				if ( $term ) {
					$category_ids[] = $term->term_id;
				} else {
					// Create new category.
					$new_cat = wp_create_category( sanitize_text_field( $category ) );
					if ( $new_cat && ! is_wp_error( $new_cat ) ) {
						$category_ids[] = $new_cat;
					}
				}
			}
		}

		return $category_ids;
	}

	/**
	 * Set post meta fields.
	 *
	 * @param int   $post_id Post ID.
	 * @param array $config  Action configuration.
	 * @return array Result with 'success' boolean and counts.
	 */
	public static function set_meta( int $post_id, array $config ): array {
		// Check if post_meta is provided and is an array.
		if ( empty( $config['post_meta'] ) || ! is_array( $config['post_meta'] ) ) {
			return array( 'success' => true );
		}

		$updated_count = 0;
		$failed_count  = 0;

		// Iterate over meta key-value pairs.
		foreach ( $config['post_meta'] as $meta_key => $meta_value ) {
			// Sanitize meta key.
			$meta_key = sanitize_key( $meta_key );

			// Sanitize meta value (use text field as default).
			$meta_value = sanitize_text_field( $meta_value );

			// Update post meta.
			update_post_meta( $post_id, $meta_key, $meta_value );

			// Note: update_post_meta returns false if the value is the same.
			// We don't consider this a failure.
			++$updated_count;
		}

		return array(
			'success'       => 0 === $failed_count,
			'updated_count' => $updated_count,
			'failed_count'  => $failed_count,
		);
	}
}
