<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Pipeline_Cart_Discounts' ) ) {

    class Pricely_Pipeline_Cart_Discounts {

        private static $instance;
        private $cart_discounts_key;
        private $context;

        public static function get_instance(): self {

            if ( !self::$instance ) {

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

            return self::$instance;
        }

        public function __construct() {

            $this->cart_discounts_key = 'cart_discounts';
            $this->context = 'cart_discounts';
        }

        public function get_data() {

            $pipeline = Pricely_Pipeline::get_instance();

            $cache_data = $pipeline->get_cache( $this->context );

            if ( isset( $cache_data[ $this->cart_discounts_key ] ) ) {

                return $cache_data[ $this->cart_discounts_key ];
            }

            if ( $this->is_cache_valid() ) {

                return false;
            }

            $this->init_pipeline_data();

            $data = $pipeline->get_data( $this->context );


            if ( isset( $data[ $this->cart_discounts_key ] ) ) {

                return $data[ $this->cart_discounts_key ];
            }

            return false;
        }

        private function init_pipeline_data() {

            foreach ( WC()->cart->get_cart_contents() as $cart_item ) {

                    $this->init_pipeline_product_data( $cart_item[ 'product_id' ], $cart_item[ 'variation_id' ], $cart_item[ 'data' ] );              
            }
        }

        private function init_pipeline_product_data( $product_id, $variation_id, $product ) {

            $pipeline = Pricely_Pipeline::get_instance();

            if ( $variation_id > 0 ) {

                $parent = Pricely_Product::get_instance()->get_product( $product_id );

                $pipeline->get_product_data( $parent, $product, $this->context );
            } else {

                $pipeline->get_product_data( $product, null, $this->context );
            }
        }

        private function is_cache_valid() {

            return Pricely_Cache::get_instance()->is_valid_data();
        }

    }

}