<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Amount_Tax' ) ) {

    class Pricely_Amount_Tax {

        private static $instance;

        public static function get_instance(): self {

            if ( !self::$instance ) {

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

            return self::$instance;
        }

        public function calculate( $amount_data ) {

            $amount_data[ 'totals' ] = $this->get_default_items_taxes( $amount_data[ 'totals' ] );

            return $this->get_default_total_taxes( $amount_data );
        }

        private function get_default_items_taxes( $items_total ) {

            $keys = array_keys( $items_total );

            foreach ( $keys as $key ) {

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

                    $items_total[ $key ][ 'taxes' ] = array();
                }

                if ( !isset( $items_total[ $key ][ 'total_tax' ] ) ) {

                    $items_total[ $key ][ 'total_tax' ] = array_sum( $items_total[ $key ][ 'taxes' ] );
                }
            }

            return $items_total;
        }

        private function get_default_total_taxes( $amount_data ) {

            if ( !isset( $amount_data[ 'taxes' ] ) ) {

                $amount_data[ 'taxes' ] = array();
            }

            if ( !isset( $amount_data[ 'total_tax' ] ) ) {

                $amount_data[ 'total_tax' ] = array_sum( $amount_data[ 'taxes' ] );
            }


            return $amount_data;
        }

    }

}