<?php

namespace Objectiv\Plugins\Checkout\Model\Bumps;

class CategoriesBump extends BumpAbstract {
	public function is_displayable(): bool {
		if ( ! parent::is_displayable() ) {
			return false;
		}

		if ( ! $this->can_offer_product_be_added_to_the_cart() ) {
			cfw_debug_log( 'Order Bump Rule Failure: Offer Product cannot be added to the cart: ' . $this->get_id() );
			return false;
		}

		/**
		 * Filters whether to show a bump if the offer product is already in the cart
		 *
		 * @since 8.2.18
		 * @param bool $show_bump_if_offer_product_in_cart Whether to show a bump if the offer product is already in the cart
		 */
		if ( apply_filters( 'cfw_hide_bump_if_offer_product_in_cart', true ) && $this->quantity_of_product_in_cart( $this->offer_product ) ) {
			cfw_debug_log( 'Order Bump Rule Failure: Offer product is in the cart: ' . $this->get_id() );
			return false;
		}

		if ( $this->bump_is_in_cart() ) {
			cfw_debug_log( 'Order Bump Rule Failure: Bump is already in the cart: ' . $this->get_id() );
			return false;
		}

		$result = $this->cart_contains_normal_product_of_categories();

		if ( ! $result ) {
			cfw_debug_log( 'Order Bump Rule Failure: Cart does not contain any required product categories: ' . $this->get_id() );
		}

		return $result;
	}

	public function is_cart_bump_valid(): bool {
		/**
		 * Filters whether the bump is valid
		 *
		 * @param string $is_cart_bump_valid Whether the categories bump in the cart is still valid
		 * @since 7.5.0
		 */
		return apply_filters( 'cfw_is_cart_bump_valid', parent::is_cart_bump_valid() && $this->cart_contains_normal_product_of_categories(), $this );
	}

	protected function cart_contains_normal_product_of_categories(): bool {
		foreach ( $this->categories as $category ) {
			if ( $this->quantity_of_normal_cart_items_in_category( $category ) ) {
				return true;
			}
		}

		return false;
	}
}
