<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Cache' ) ) {

    class Pricely_Cache {

        private static $instance = null;
        private $hash_key;
        private $prev_hash;

        public static function get_instance(): self {

            if ( null == self::$instance ) {

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

            return self::$instance;
        }

        private function __construct() {

            $this->hash_key = 'cache_hash';
            $this->prev_hash = false;
        }

        public function is_valid_data() {

            if ( $this->is_virtual_cart() ) {

                return false;
            }

            $stored_hash = $this->get_hash();

            $hash = $this->generate_hash();

            return ($stored_hash == $hash);
        }

        public function get_data( $key, $default ) {

            return Pricely_Session::get_instance()->get( $key, $default );
        }

        public function store_data( $key, $data ) {

            if ( $this->is_virtual_cart() ) {

                return;
            }

            Pricely_Session::get_instance()->set( $key, $data );
        }

        public function clear_data( $key ) {
            
            if ( $this->is_virtual_cart() ) {

                return;
            }

            Pricely_Session::get_instance()->unset( $key );

            $this->prev_hash = '';

            Pricely_Session::get_instance()->unset( $this->hash_key );
        }

        public function save() {
            
            if ( $this->is_virtual_cart() ) {

                return;
            }

            $hash = $this->generate_hash();
            $this->prev_hash = $hash;

            Pricely_Session::get_instance()->set( $this->hash_key, $hash );

            Pricely_Session::get_instance()->save();
        }

        public function get_hash() {

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

                return $this->prev_hash;
            }

            $this->prev_hash = Pricely_Session::get_instance()->get( $this->hash_key, '' );

            return $this->prev_hash;
        }

        public function generate_hash() {

            return Pricely_Cache_Params::get_instance()->generate_hash();
        }

        private function is_virtual_cart() {

            if ( !defined( 'PRICELY_VIRTUAL_CART' ) ) {

                return false;
            }

            if ( false === PRICELY_VIRTUAL_CART ) {

                return false;
            }

            return true;
        }

    }

}