<?php
/**
 * Plugin Name: Foliora Ritual Discount
 * Description: Progressive 10/15/20% cart discount for 2/3/4+ non-bundle items.
 * Version: 1.0.0
 *
 * @package Foliora
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Quantity of cart items that are not in the bundles category.
 *
 * @return int
 */
function foliora_ritual_eligible_qty() {
	if ( ! function_exists( 'WC' ) || ! WC()->cart ) {
		return 0;
	}

	$qty = 0;
	foreach ( WC()->cart->get_cart() as $item ) {
		$product = isset( $item['data'] ) ? $item['data'] : null;
		if ( ! $product instanceof WC_Product ) {
			continue;
		}

		$parent_id = $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id();
		if ( has_term( 'bundles', 'product_cat', $parent_id ) ) {
			continue;
		}

		$qty += isset( $item['quantity'] ) ? (int) $item['quantity'] : 0;
	}

	return $qty;
}

/**
 * Discount rate for a qualifying quantity.
 *
 * @param int $qty Eligible quantity.
 * @return float
 */
function foliora_ritual_rate( $qty ) {
	if ( $qty >= 4 ) {
		return 0.20;
	}
	if ( $qty >= 3 ) {
		return 0.15;
	}
	if ( $qty >= 2 ) {
		return 0.10;
	}
	return 0.0;
}

/**
 * Apply muted progressive fee.
 *
 * @param WC_Cart $cart Cart.
 */
function foliora_ritual_apply_fee( $cart ) {
	if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
		return;
	}

	$qty  = foliora_ritual_eligible_qty();
	$rate = foliora_ritual_rate( $qty );
	if ( $rate <= 0 ) {
		return;
	}

	$line = 0.0;
	foreach ( $cart->get_cart() as $item ) {
		$product = isset( $item['data'] ) ? $item['data'] : null;
		if ( ! $product instanceof WC_Product ) {
			continue;
		}
		$parent_id = $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id();
		if ( has_term( 'bundles', 'product_cat', $parent_id ) ) {
			continue;
		}
		$line += (float) $item['line_subtotal'];
	}

	$percent = (int) round( $rate * 100 );
	$label   = sprintf( 'Reading ritual (%d%% off)', $percent );
	$cart->add_fee( $label, -1 * $line * $rate, false );
}
add_action( 'woocommerce_cart_calculate_fees', 'foliora_ritual_apply_fee', 20 );

/**
 * Muted progress copy for drawer / cart.
 *
 * @return string
 */
function foliora_ritual_message() {
	return 'Add 2 reading essentials → 10% off · 3 → 15% · 4+ → 20%';
}
