<?php
/**
 * Trait for parsing raw condition data values.
 *
 * Provides reusable methods for normalizing condition values,
 * including IDs, strings, and booleans.
 *
 * @package     EDD\Pro\Emails\ConditionalTags\Conditions\Traits
 * @copyright   Copyright (c) 2026, Sandhills Development, LLC
 * @license     https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       3.6.6
 */

namespace EDD\Pro\Emails\ConditionalTags\Conditions\Traits;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit; // @codeCoverageIgnore

/**
 * Trait ParseData
 *
 * @since 3.6.6
 */
trait ParseData {

	/**
	 * Parse comma-separated IDs into unique positive integers.
	 *
	 * @since 3.6.6
	 *
	 * @param mixed $raw_ids Raw IDs from the condition value.
	 * @return int[]
	 */
	protected function parse_ids( $raw_ids ) {
		if ( empty( $raw_ids ) ) {
			return array();
		}

		$parts = is_array( $raw_ids ) ? $raw_ids : explode( ',', trim( (string) $raw_ids ) );
		$ids   = array_map( 'absint', $parts );
		$ids   = array_filter( $ids );

		return array_values( array_unique( $ids ) );
	}

	/**
	 * Extract unique product IDs from order items.
	 *
	 * @since 3.6.6
	 *
	 * @param object $edd_object The EDD object.
	 * @return int[]
	 */
	protected function get_order_product_ids( $edd_object ) {
		if ( ! $edd_object instanceof \EDD\Orders\Order || empty( $edd_object->items ) ) {
			return array();
		}

		$ids = wp_list_pluck( $edd_object->items, 'product_id' );
		$ids = array_map( 'absint', $ids );
		$ids = array_filter( $ids );

		return array_values( array_unique( $ids ) );
	}

	/**
	 * Parse comma-separated values into unique, trimmed strings.
	 *
	 * @since 3.6.6
	 *
	 * @param string $raw_values Raw comma-separated values.
	 * @return string[]
	 */
	protected function parse_string_list( $raw_values ) {
		$raw_values = trim( (string) $raw_values );
		if ( '' === $raw_values ) {
			return array();
		}

		$values = array_map( 'trim', explode( ',', $raw_values ) );
		$values = array_filter( $values, 'strlen' );

		return array_values( array_unique( $values ) );
	}

	/**
	 * Parse a mixed value into boolean.
	 *
	 * @since 3.6.6
	 *
	 * @param mixed $value Raw input value.
	 * @return bool|null Null when value is not a recognized boolean.
	 */
	protected function parse_boolean( $value ) {
		if ( is_bool( $value ) ) {
			return $value;
		}

		$normalized = strtolower( trim( (string) $value ) );
		$map        = array(
			'1'     => true,
			'true'  => true,
			'yes'   => true,
			'on'    => true,
			'0'     => false,
			'false' => false,
			'no'    => false,
			'off'   => false,
		);

		if ( ! array_key_exists( $normalized, $map ) ) {
			return null;
		}

		return $map[ $normalized ];
	}
}
