<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}

if ( !class_exists( 'Pricely_Session' ) ) {

    class Pricely_Session {

        private static $instance = null;
        private $session_key;
        private $session_data;

        public static function get_instance(): self {

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

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

            return self::$instance;
        }

        public function __construct() {

            $this->session_key = 'pricely';
            $this->session_data = false;
        }

        public function get( $key, $default = false ) {

            $data = $this->load();

            if ( isset( $data[ $key ] ) ) {

                return $data[ $key ];
            }

            return $default;
        }

        public function set( $key, $value ) {

            $data = $this->load();

            $data[ $key ] = $value;

            $this->session_data = $data;
        }

        public function unset( $key ) {

            $data = $this->load();

            if ( isset( $data[ $key ] ) ) {

                unset( $data[ $key ] );
            }
        }

        public function save() {

            if ( defined( 'PRICELY_VIRTUAL_CART' ) && true === PRICELY_VIRTUAL_CART ) {

                return;
            }

            $data = $this->load();

            $this->set_session( $this->session_key, $data );
        }

        private function load() {

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

                return $this->session_data;
            }

            $this->session_data = $this->get_session( $this->session_key, array() );

            return $this->session_data;
        }

        private function get_session( $key, $default = false ) {

            if ( is_null( WC()->session ) ) {

                return $default;
            }

            return WC()->session->get( $key, $default );
        }

        private function set_session( $key, $value ) {

            if ( is_null( WC()->session ) ) {

                return;
            }

            WC()->session->set( $key, $value );
        }

    }

}
