<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Source_Prices' ) ) {

    class Pricely_Source_Prices {

        private $data_key;
        private $prices_list;

        public function __construct() {

            $this->data_key = 'source_prices';
            $this->prices_list = array();
        }

        public function clear_cache() {

            $this->prices_list = array();
        }

        public function get_cache( $data, $context ) {

            $data[ $this->data_key ] = $this->get_prices_list();

            return $data;
        }

        public function get_product_cache( $data ) {

            if ( !isset( $data[ 'wc' ][ 'product' ][ 'key' ] ) ) {

                $data[ $this->data_key ] = $this->get_default_prices();

                return $data;
            }

            $item_key = $data[ 'wc' ][ 'product' ][ 'key' ];

            $prices_list = $this->get_prices_list();

            if ( !isset( $prices_list[ $item_key ] ) ) {

                $data[ $this->data_key ] = $this->get_default_prices();

                return $data;
            }

            $data[ $this->data_key ] = $prices_list[ $item_key ];

            return $data;
        }

        public function process_product_data( $data ) {

            $data[ $this->data_key ] = $this->get_prices( $data );

            $this->set_prices_list( $data );

            return $data;
        }

        public function process_data( $data, $context ) {

            $data[ $this->data_key ] = $this->get_prices_list();

            return $data;
        }

        private function get_prices( $data ) {

            if ( !isset( $data[ 'wc' ][ 'product' ] ) ) {

                return $this->get_default_prices();
            }

            $product = $data[ 'wc' ][ 'product' ];

            $prices = array(
                'regular_price' => $product[ 'regular_price' ],
                'sale_price' => $product[ 'sale_price' ],
            );

            return $prices;
        }

        private function get_default_prices() {

            return array();
        }

        private function set_prices_list( $data ) {

            if ( !isset( $data[ 'wc' ][ 'product' ][ 'key' ] ) ) {

                return;
            }

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

                return;
            }

            $prices = $data[ $this->data_key ];

            $key = $data[ 'wc' ][ 'product' ][ 'key' ];

            $this->prices_list[ $key ] = $prices;
        }

        private function get_prices_list() {

            return $this->prices_list;
        }

    }

}

