<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Amount_Adjustment_Add' ) ) {


    class Pricely_Amount_Adjustment_Add {

        private static $instance;

        public static function get_instance(): self {

            if ( !self::$instance ) {

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

            return self::$instance;
        }

        public function can_process_amount( $adjustment_type ) {

            $adjustment_types = array(
                'add',
            );

            return ( in_array( $adjustment_type, $adjustment_types ) );
        }

        public function process_amount( $amounts, $amount_data ) {

            $adjustment_type = $amount_data[ 'adjustment_type' ];

            if ( 'add' == $adjustment_type ) {

                $amounts = $this->adjust_add( $amounts, $amount_data );
            }

            return $amounts;
        }

        private function adjust_add( $amounts, $amount_data ) {

            $amount_totals = $amounts[ 'totals' ];

            foreach ( $amount_data[ 'totals' ] as $key => $item_totals ) {

                if ( !isset( $amount_totals[ $key ] ) ) {

                    $amount_totals[ $key ] = $this->get_default_item_totals();
                }

                $amount_totals[ $key ][ 'total' ] += $item_totals[ 'total' ];

                $amount_totals[ $key ][ 'taxes' ] = $this->merge_taxes( $amount_totals[ $key ][ 'taxes' ], $item_totals[ 'taxes' ] );

                $amount_totals[ $key ][ 'total_tax' ] += $item_totals[ 'total_tax' ];
            }

            $amounts[ 'totals' ] = $amount_totals;

            return $amounts;
        }

        private function merge_taxes( $taxes, $new_taxes ) {

            foreach ( $new_taxes as $key => $new_tax ) {

                if ( !isset( $taxes[ $key ] ) ) {

                    $taxes[ $key ] = 0;
                }

                $taxes[ $key ] += $new_tax;
            }

            return $taxes;
        }

        private function get_default_item_totals() {

            return array(
                'total' => 0,
                'taxes' => array(),
                'total_tax' => 0
            );
        }

    }

}
