<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Amount_Adjustments' ) ) {

    require_once (dirname( __FILE__ ) . '/amount-adjustments-add.php');

    class Pricely_Amount_Adjustments {

        private static $instance;
        private $amount_adjustment_add;

        public static function get_instance(): self {

            if ( !self::$instance ) {

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

            return self::$instance;
        }

        public function __construct() {

            $this->amount_adjustment_add = Pricely_Amount_Adjustment_Add::get_instance();
        }

        public function process_amount( $amounts, $amount_data ) {

            return $this->adjust( $amounts, $amount_data );
        }

        private function adjust( $amounts, $amount_data ) {

            $adjustment_type = 'add';

            if ( isset( $amount_data[ 'adjustment_type' ] ) ) {

                $adjustment_type = $amount_data[ 'adjustment_type' ];
            }

            if ( $this->amount_adjustment_add->can_process_amount( $adjustment_type ) ) {

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

            return $this->process_total( $amounts );
        }

        private function process_total( $amounts ) {

            $total = 0;
            $taxes = array();
            $total_tax = 0;

            foreach ( $amounts[ 'totals' ] as $item_totals ) {

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

                $taxes = $this->merge_taxes( $taxes, $item_totals[ 'taxes' ] );
                $total_tax += $item_totals[ 'total_tax' ];
            }

            $amounts[ 'total' ] = $total;
            $amounts[ 'taxes' ] = $taxes;
            $amounts[ 'total_tax' ] = $total_tax;

            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;
        }

    }

}
