<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Checkout_Prices_Data' ) ) {

    class Pricely_Checkout_Prices_Data {

        public function process_data( $prices_data ) {

            if ( !is_array( $prices_data ) || !count( $prices_data ) ) {

                return false;
            }

            $result = array(
                'auto_add_items' => false,
                'items' => false,
                'coupons' => false,
                'tooltips' => false,
            );


            //process items prices
            $item_prices = $this->process_item_prices( $prices_data );

            if ( !$item_prices ) {

                return $result;
            }

            $result[ 'items' ] = $item_prices;


            //process tooltips
            $tooltips = $this->process_tooltips( $prices_data );

            if ( $tooltips ) {

                $result[ 'tooltips' ] = $tooltips;
            }

            return $result;
        }

        private function process_item_prices( $prices_data ) {

            $item_prices = array();

            foreach ( $prices_data as $item_prices_data ) {

                $item_prices = $this->get_item_prices( $item_prices, $item_prices_data[ 'items' ], $item_prices_data[ 'pricing_id' ], $item_prices_data[ 'coupon' ] );
            }

            if ( count( $item_prices ) ) {

                return $item_prices;
            }

            return false;
        }

        private function get_item_prices( $item_prices, $items, $pricing_id, $coupon ) {

            foreach ( $items as $key => $item ) {

                $item_prices[ $key ] = $this->arange_item_values( $item, $pricing_id );

                $item_prices[ $key ][ 'coupon' ] = false;

                if ( $coupon ) {

                    $item_prices[ $key ][ 'coupon' ] = $coupon[ 'id' ];
                }
            }

            return $item_prices;
        }

        private function arange_item_values( $in_item, $pricing_id ) {

            $item = array(
                'pricing_id' => $pricing_id,
            );

            foreach ( $in_item as $key => $value ) {

                if ( 'pricing_id' == $key ) {

                    continue;
                }

                $item[ $key ] = $value;
            }

            return $item;
        }

        private function process_tooltips( $prices_data ) {

            $tooltips = array();

            foreach ( $prices_data as $price_data ) {

                if ( !isset( $price_data[ 'items' ] ) ) {

                    continue;
                }

                if ( !count( $price_data[ 'items' ] ) ) {

                    continue;
                }

                $pricing_id = $price_data[ 'pricing_id' ];

                $tooltips[ $pricing_id ] = $price_data[ 'tooltip' ];
            }

            if ( count( $tooltips ) ) {

                return $tooltips;
            }

            return false;
        }

    }

}
