<?php

namespace CouponsPlus\App\Coupon;

use function WC;

class CartContentFingerprint
{
    /**
     * Generates a fingerprint of the current cart state.
     * Includes product IDs, quantities, line subtotals, and applied coupons.
     *
     * @return string MD5 hash of the cart state
     */
    public static function generate(): string
    {
        $cart = WC()->cart;

        if (!$cart) {
            return '';
        }

        $items = [];

        foreach ($cart->get_cart() as $cartItemKey => $cartItem) {
            $lineSubtotal = $cartItem['line_subtotal'] ?? null;

            if ($lineSubtotal === null) {
                $product = $cartItem['data'] ?? null;
                $price = $product ? (float) $product->get_price() : 0.0;
                $lineSubtotal = $price * (int) $cartItem['quantity'];
            }

            $items[] = [
                'product_id' => (int) $cartItem['product_id'],
                'variation_id' => (int) ($cartItem['variation_id'] ?? 0),
                'quantity' => (int) $cartItem['quantity'],
                'line_subtotal' => (float) $lineSubtotal,
            ];
        }

        $data = [
            'items' => $items,
            //'coupons' => $cart->get_applied_coupons(),
        ];

        return md5(serialize($data));
    }
}

