<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_After_Product_Prices' ) ) {

    class Pricely_After_Product_Prices {

        private $items_in_cart_data_key;
        private $adjusted_prices_data_key;

        public function __construct() {

            $this->items_in_cart_data_key = 'items_in_cart';
            $this->adjusted_prices_data_key = 'adjusted_prices';
        }

        public function get_cache( $data, $context ) {

            return $this->process_data( $data, $context );
        }

        public function get_product_cache( $data ) {

            return $this->process_product_data( $data );
        }

        public function process_data( $data, $context ) {

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

                return $data;
            }

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

                return $data;
            }

            foreach ( $data[ $this->adjusted_prices_data_key ] as $item_key => $item_prices ) {

                if ( !isset( $item_prices[ 'sale_price' ] ) ) {

                    continue;
                }

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

                    continue;
                }

                $data[ $this->items_in_cart_data_key ][ $item_key ][ 'price' ] = $item_prices[ 'sale_price' ];
            }

            return $data;
        }

        public function process_product_data( $data ) {

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

                return $data;
            }

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

                return $data;
            }

            $adjusted_prices = $data[ $this->adjusted_prices_data_key ];

            if ( !isset( $adjusted_prices[ 'sale_price' ] ) ) {

                return $data;
            }

            $data[ $this->items_in_cart_data_key ][ 'price' ] = $adjusted_prices[ 'sale_price' ];

            return $data;
        }

    }

}

