<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Cart_Discounts_Cache' ) ) {

    class Pricely_Cart_Discounts_Cache {

        private static $instance;
        private $discounts;
        private $cache_key;

        public static function get_instance(): self {

            if ( !self::$instance ) {

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

            return self::$instance;
        }

        public function __construct() {

            $this->discounts = false;
            $this->cache_key = 'cart_discounts';
        }

        public function clear() {

            $this->discounts = false;
            Pricely_Cache::get_instance()->clear_data( $this->cache_key );
        }

        public function get() {

            if ( false !== $this->discounts ) {

                return $this->discounts;
            }

            if ( $this->is_virtual_cart() ) {

                return false;
            }
            
            if ( !$this->is_valid_data() ) {

                return false;
            }

            return Pricely_Cache::get_instance()->get_data( $this->cache_key, false );
        }

        public function set( $discounts ) {

            if ( is_array( $discounts ) ) {

                $this->discounts = $discounts;
            } else {

                $this->discounts = false;
            }
            
            if ( $this->is_virtual_cart() ) {

                return;
            }
            
            Pricely_Cache::get_instance()->store_data( $this->cache_key, $this->discounts );
        }
        
        private function is_valid_data() {

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

        private function is_virtual_cart() {

            if ( !defined( 'PRICELY_VIRTUAL_CART' ) ) {

                return false;
            }

            if ( false === PRICELY_VIRTUAL_CART ) {

                return false;
            }

            return true;
        }

    }

}
