<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Pipeline_Cart_Hash' ) ) {

    class Pricely_Pipeline_Cart_Hash {

        private static $instance;
        private $new_items_quantity;
        private $quantity_updated;

        public static function get_instance(): self {

            if ( !self::$instance ) {

                self::$instance = new self();
            }

            return self::$instance;
        }

        public function __construct() {

            $this->new_items_quantity = array();
            $this->quantity_updated = false;

            add_action( 'woocommerce_after_cart_item_quantity_update', array( $this, 'quantity_update' ), 99999, 4 );
            add_filter( 'woocommerce_cart_hash', array( $this, 'get_hash' ), 99999, 2 );
        }

        public function quantity_update( $cart_item_key, $quantity, $old_quantity, $cart ) {

            $this->new_items_quantity[ $cart_item_key ] = $quantity;

            $this->quantity_updated = true;
        }

        public function get_hash( $hash, $hash_data ) {

            if ( !$this->quantity_updated ) {

                return $this->get_cache_hash( $hash );
            }

            foreach ( $this->new_items_quantity as $cart_key => $quantity ) {

                if ( !isset( $hash_data[ $cart_key ][ 'quantity' ] ) ) {

                    continue;
                }

                $hash_data[ $cart_key ][ 'quantity' ] = $quantity;
            }

            $this->quantity_updated = false;

            return $this->get_cache_hash( md5( wp_json_encode( $hash_data ) ) );
        }

        private function get_cache_hash( $hash ) {

            return Pricely_Cache_Params::get_instance()->get_cart_hash( $hash );
        }

    }

    Pricely_Pipeline_Cart_Hash::get_instance();
}