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

class BundlePress_Fixed_Handler
{
    public static function get_price($product_id, $bundle_id, $cart_item, $cart = null)
    {
        $product = $cart_item['data'];
        $base_price = (float) $product->get_price();

        // If this is a child item in a fixed bundle, it should be $0 because the parent bundle product carries the price
        if (isset($cart_item['_bundlepress_parent'])) {
            return 0;
        }
        
        // If this is the bundle product itself, apply the discount if configured
        $bundle = BundlePress_DB::get_bundle_data($bundle_id);
        if (!$bundle || $bundle['type'] !== 'fixed') {
            return $base_price;
        }

        // The 'price' from get_bundle_data is the regular_price from fixed_settings
        $configured_price = isset($bundle['price']) ? (float)$bundle['price'] : $base_price;
        $sale_price       = isset($bundle['sale_price']) ? (float)$bundle['sale_price'] : null;

        if ($sale_price !== null && $sale_price >= 0) {
            return $sale_price;
        }

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

        if ($discount_type === 'percentage') {
            return $configured_price * (1 - ($discount_value / 100));
        } elseif ($discount_type === 'fixed') {
            return max(0, $configured_price - $discount_value);
        }

        return $configured_price;
    }
}
