<?php
/**
 * ProductVisibilityChecker for PromoTimeWidget.
 *
 * Determines whether the PromoTimeWidget should be shown
 * based on selected and excluded product targeting settings.
 *
 * @package Ilabs\Firevert\Modules\PromoTimeWidget\Services\Helper
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Modules\PromoTimeWidget\Services\Helper;

/**
 * Class ProductVisibilityChecker
 */
final class ProductVisibilityChecker {

	/**
	 * Current product ID.
	 *
	 * @var int
	 */
	private int $product_id;

	/**
	 * Targeting settings array.
	 *
	 * @var array<string, mixed>
	 */
	private array $settings;

	/**
	 * Constructor.
	 *
	 * @param int   $product_id Product ID.
	 * @param array $settings   Targeting settings.
	 */
	public function __construct( int $product_id, array $settings ) {
		$this->product_id = $product_id;
		$this->settings   = $settings;
	}

	/**
	 * Determines whether widget should be displayed for current product.
	 *
	 * @return bool True if widget should be displayed.
	 */
	public function should_display(): bool {
		$excluded_products   = $this->settings['firevert_promo_time_widget_excluded_products'] ?? array();
		$excluded_categories = $this->settings['firevert_promo_time_widget_excluded_categories'] ?? array();

		if ( in_array( (string) $this->product_id, $excluded_products, true ) ) {
			return false;
		}

		$categories = wp_get_post_terms(
			$this->product_id,
			'product_cat',
			array( 'fields' => 'ids' )
		);

		if ( array_intersect( $excluded_categories, $categories ) ) {
			return false;
		}

		if ( ! empty( $this->settings['firevert_promo_time_widget_all_products'] ) ) {
			return true;
		}

		$selected_products = $this->settings['firevert_promo_time_widget_selected_products'] ?? array();
		$target_categories = $this->settings['firevert_promo_time_widget_product_categories'] ?? array();

		if ( in_array( (string) $this->product_id, $selected_products, true ) ) {
			return true;
		}

		if ( array_intersect( $target_categories, $categories ) ) {
			return true;
		}

		return false;
	}
}
