<?php

namespace CouponsPlus\App\Coupon;

use WC_Coupon;
use CouponsPlus\Original\Environment\Env;

class IncompatibleCartItemState
{
    /*protected static IncompatibleCartItemState $instance;



    public static function getInstance(): IncompatibleCartItemState
    {
        if (static::$instance === null) {
            static::$instance = new static();
        }

        return static::$instance;
    }*/

    protected static function buildCartState(): array
    {
        $cartItems = WC()->cart->get_cart();

        // Extract only product IDs and quantities
        $cartState = [];
        foreach ($cartItems as $cartItem) {
            $productId = $cartItem['variation_id'] ?: $cartItem['product_id'];
            $quantity = $cartItem['quantity'];

            // Use product ID as key and sum quantities if same product appears multiple times
            if (isset($cartState[$productId])) {
                $cartState[$productId] += $quantity;
            } else {
                $cartState[$productId] = $quantity;
            }
        }

        // Sort by product ID for consistent comparison
        ksort($cartState);

        return $cartState;
    }

    public static function save(WC_Coupon $coupon, string $key = '')
    {
        if (static::hasForCoupon($coupon)) {
            return;
        }

        $cartState = static::buildCartState();

        // Get existing states
        /** @var array $allStates */
        $allStates = self::getFromCartState();

        // Ensure we have an array
        if (!is_array($allStates)) {
            $allStates = [];
        }

        // Add new state
        $allStates[] = [
            'CODE' => $coupon->get_code(),
            'STATE' => $cartState,
            'KEY' => $key
        ];

        // Store in session
        WC()->session->set(self::getKey(), $allStates);
    }

    public static function hasForCoupon(WC_Coupon $coupon): bool
    {
        $allStates = self::getFromCartState();

        if (empty($allStates)) {
            return false;
        }

        $currentState = static::buildCartState();
        $couponCode = $coupon->get_code();

        // Check if any saved state matches the current state for this coupon
        foreach ($allStates as $savedEntry) {
            if ($savedEntry['CODE'] === $couponCode && $savedEntry['STATE'] === $currentState) {
                return true;
            }
        }

        return false;
    }

    public static function removeByKey(WC_Coupon $coupon, string $key): void
    {
        $allStates = self::getFromCartState();

        if (empty($allStates) || !is_array($allStates)) {
            return;
        }

        $couponCode = $coupon->get_code();

        // Filter out the state matching both coupon code and key
        $filteredStates = array_values(array_filter($allStates, function($entry) use ($couponCode, $key) {
            return !($entry['CODE'] === $couponCode && $entry['KEY'] === $key);
        }));

        // Store updated states
        WC()->session->set(self::getKey(), $filteredStates);
    }

    /**
     * @return array|string
     */
    public static function getFromCartState()
    {
        return WC()->session->get(self::getKey(), []);
    }

    /**
     * @return string
     */
    public static function getKey(): string
    {
        return Env::getWithPrefix('incompatible_cart_state');
    }

    public static function reset()
    {
        WC()->session->set(self::getKey(), null);
    }

}