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

class BundlePress_BXGY_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();

        if (!empty($cart_item['_bxgy_free_gift'])) {
            return 0.0;
        }

        if (!empty($cart_item['_bxgy_offer_item'])) {
            return 0.0;
        }

        $bundle = BundlePress_DB::get_bundle_data($bundle_id);
        if (!$bundle || $bundle['type'] !== 'bxgy') {
            return $base_price;
        }

        $settings = $bundle['settings'];
        $offer_type      = $settings['offer_type'] ?? $settings['bxgy_offer_type'] ?? 'free_gift';
        $discount_type   = $settings['discount_type']   ?? $settings['bxgy_discount_type']   ?? 'percentage';
        $discount_amount = (float)($settings['discount_amount'] ?? $settings['bxgy_discount_amount'] ?? 0);

        // 2. Handle "Product Discount" type 
        // In this mode, we apply the discount to the items being purchased because "Offer Products" is hidden
        if ($offer_type === 'discount' && empty($cart_item['_bxgy_offer_item'])) {
            if ($discount_amount > 0) {
                if ($discount_type === 'percentage') {
                    return max(0, $base_price * (1 - $discount_amount / 100));
                } elseif ($discount_type === 'fixed') {
                    return max(0, $base_price - $discount_amount);
                }
            }
        }

        // 3. Handle specific offer items (the ones added via "Get" side in editor)
        if (!empty($cart_item['_bxgy_offer_item'])) {
            // If we reached here and it's not a free gift, it might be a discounted offer item
            // (though for now you've hidden this flow for 'discount' type, we keep it for robustness)
            return 0.0; 
        }

        // Regular buy items for 'free_gift' type remain full price
        return $base_price;
    }
}
