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

class BundlePress_FBT_Handler
{
    public static function get_price($product_id, $bundle_id, $cart_item, $cart = null)
    {
        $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'] !== 'fbt') {
            return $base_price;
        }

        $discount_type  = $bundle['settings']['discount_type'] ?? '';
        $discount_value = (float)($bundle['settings']['discount_value'] ?? 0);

        if ($discount_type === 'percentage') {
            return $base_price * (1 - ($discount_value / 100));
        } elseif ($discount_type === 'fixed') {
            // Find the total price of all items in this bundle group in the cart
            $total_bundle_price = 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) {
                        $inner_product = wc_get_product($inner_item['product_id']);
                        if ($inner_product) {
                            $total_bundle_price += (float) $inner_product->get_price() * $inner_item['quantity'];
                        }
                    }
                }
            }

            // Fallback if not found in cart loop
            if ($total_bundle_price == 0) {
                $total_bundle_price = $base_price * $cart_item['quantity'];
            }

            // Calculate the item's weight in the total bundle price
            $weight = $total_bundle_price > 0 ? ($base_price / $total_bundle_price) : 0;
            
            // Apply that proportional weight to the total discount
            $prorated_discount = $discount_value * $weight;

            return max(0, $base_price - $prorated_discount);
        }

        return $base_price;
    }
}
