<?php
defined('ABSPATH') || exit;

class BundlePress_MixMatch_Handler
{
    public static function get_price($product_id, $bundle_id, $cart_item, $cart = null)
    {
        // Get a fresh product instance to find the stable "active" price.
        // This avoids double-discounting if this hook runs multiple times.
        $fresh_product = wc_get_product($product_id);
        if (!$fresh_product) {
            return (float) $cart_item['data']->get_regular_price();
        }

        $base_price = (float) $fresh_product->get_price();
        
        $bundle = BundlePress_DB::get_bundle_data($bundle_id);
        if (!$bundle || $bundle['type'] !== 'mixmatch') {
            return $base_price;
        }

        $tiers = $bundle['settings']['tiers'] ?? [];
        $allow_multi_qty = true; // Default to true or check settings if added to DB

        // Calculate total quantity of ALL items belonging to this bundle in the cart
        $total_bundle_qty = 0;
        $parent_key = isset($cart_item['_bundlepress_parent']) ? $cart_item['_bundlepress_parent'] : '';
        $item_key   = isset($cart_item['key']) ? $cart_item['key'] : '';

        if ($cart) {
            foreach ($cart->get_cart() as $inner_key => $inner_item) {
                $inner_bundle_id = 0;
                if (isset($inner_item['_bundlepress_bundle'])) {
                    $inner_bundle_id = absint($inner_item['_bundlepress_bundle']);
                } elseif (isset($inner_item['_bundlepress_parent'])) {
                    if ($inner_item['_bundlepress_parent'] === $parent_key || $inner_key === $parent_key || $inner_item['_bundlepress_parent'] === $item_key) {
                        $inner_bundle_id = $bundle_id;
                    }
                }

                if ($inner_bundle_id === (int) $bundle_id) {
                    $total_bundle_qty += $inner_item['quantity'];
                }
            }
        }

        // Fallback to current item quantity if cart search returned nothing
        if ($total_bundle_qty === 0) {
            $total_bundle_qty = (int) $cart_item['quantity']; 
        }

        // Find highest applicable tier based on TOTAL bundle quantity
        $best_discount = 0;
        foreach ($tiers as $tier) {
            $min_qty = isset($tier['min_qty']) ? absint($tier['min_qty']) : 1;
            $discount = isset($tier['discount']) ? (float) $tier['discount'] : 0;
            if ($total_bundle_qty >= $min_qty) {
                $best_discount = max($best_discount, $discount);
            }
        }

        if ($best_discount > 0) {
            return $base_price * (1 - ($best_discount / 100));
        }

        return $base_price;
    }
}
