<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Amount_Type_Order' ) ) {

    class Pricely_Amount_Type_Order {

        public function can_calculate( $amount_type ) {

            $amount_types = array(
                'fixed_amount',
                'per_amount',
            );

            return in_array( $amount_type, $amount_types );
        }

        public function calculate_amount( $amount_data, $data, $amount_args ) {

            $amount_type = $amount_args[ 'amount_type' ];

            if ( 'fixed_amount' == $amount_type ) {

                return $this->calculate_fixed_amount( $amount_data, $amount_args );
            }

            if ( 'per_amount' == $amount_type ) {

                return $this->calculate_per_amount( $amount_data, $data, $amount_args );
            }

            return $amount_data;
        }

        private function calculate_fixed_amount( $amount_data, $amount_args ) {

            $amount = 0;

            if ( is_numeric( $amount_args[ 'amount' ] ) ) {

                $amount = $amount_args[ 'amount' ];
            }

            $amount_data[ 'total' ] = $amount;

            return $amount_data;
        }

        private function calculate_per_amount( $amount_data, $data, $amount_args ) {

            $amount = 0;

            if ( is_numeric( $amount_args[ 'amount' ] ) ) {

                $amount = $amount_args[ 'amount' ];
            }

            if ( $amount <= 0 ) {

                $amount_data[ 'total' ] = 0;

                return $amount_data;
            }

            $items = $this->get_items( $amount_args );

            $cart_total = $this->get_cart_total( $amount_args, $data, $items );

            $total = $this->round( ($amount / 100) * $cart_total );

            $amount_data[ 'total' ] = $total;

            return $amount_data;
        }

        private function get_items( $amount_args ) {

            $amount_types = Pricely_Amount_Types::get_instance();

            $args = array(
                'context' => $amount_args[ 'context' ]
            );

            $items = $amount_types->get_items( $args );

            if ( is_array( $items ) ) {

                return $items;
            }

            return array();
        }

        private function get_cart_total( $amount_args, $data, $items ) {

            if ( !isset( $amount_args[ 'based_on' ] ) ) {

                return 0;
            }

            $based_on = $amount_args[ 'based_on' ];
            $context = $amount_args[ 'context' ];

            return Pricely_Cart_Totals_Util::get_instance()->get_total( $based_on, $context, $data, $items );
        }

        private function round( $total ) {

            return $this->totals_util->round( $total );
        }

    }

}