<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\WooCommerce;

use APD\Domain\Pricing\PricingEngine;
use APD\Support\PricingSnapshot;
use WC_Cart;

defined('ABSPATH') || exit;

class PriceIntegration
{
    public function boot(WC_Cart $cart) : void
    {
        if (is_admin() && ! defined('DOING_AJAX')) {
            return;
        }

        if (! $cart || ! method_exists($cart, 'get_cart')) {
            return;
        }

        $engine = new PricingEngine();

        foreach ($cart->get_cart() as $cartItemKey => $cartItem) {
            if (empty($cartItem['apd']) || ! is_array($cartItem['apd'])) {
                continue;
            }

            $configId = absint($cartItem['apd']['config_id'] ?? 0);
            $designJson = (string) ($cartItem['apd']['design_json'] ?? '');
            if ($configId <= 0 || $designJson === '') {
                continue;
            }

            $productRefId = absint($cartItem['variation_id'] ?? 0) ?: absint($cartItem['product_id'] ?? 0);
            $product = $productRefId > 0 ? wc_get_product($productRefId) : null;
            if (! $product) {
                continue;
            }

            $basePrice = (float) $product->get_price('edit');
            $result = PricingSnapshot::normalize($engine->calculate([
                'basePrice' => $basePrice,
                'configId' => $configId,
                'designJson' => $designJson,
            ]), $basePrice);

            $adjustment = (float) ($result['adjustment_total'] ?? 0);
            $finalPrice = (float) ($result['final_price'] ?? ($basePrice + $adjustment));

            if (isset($cart->cart_contents[$cartItemKey]['data']) && is_object($cart->cart_contents[$cartItemKey]['data'])) {
                $cart->cart_contents[$cartItemKey]['data']->set_price($finalPrice);
            }

            $cart->cart_contents[$cartItemKey]['apd']['payload_version'] = (int) ($result['payload_version'] ?? PricingSnapshot::VERSION);
            $cart->cart_contents[$cartItemKey]['apd']['pricing_payload'] = $result;
            $cart->cart_contents[$cartItemKey]['apd']['price_base'] = (float) ($result['base_price'] ?? $basePrice);
            $cart->cart_contents[$cartItemKey]['apd']['price_adjustment'] = $adjustment;
            $cart->cart_contents[$cartItemKey]['apd']['price_total'] = $finalPrice;
            $cart->cart_contents[$cartItemKey]['apd']['price_breakdown'] = $result;
        }
    }
}
