<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Checkout_Prices_Types' ) ) {

    require_once (dirname( __FILE__ ) . '/checkout-price-types-prices.php');

    class Pricely_Checkout_Prices_Types {

        private static $instance;
        private $pricing_type_prices;

        public static function get_instance(): self {

            if ( !self::$instance ) {

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

            return self::$instance;
        }

        public function __construct() {

            $this->pricing_type_prices = new Pricely_Checkout_Prices_Types_Prices();
        }

        public function calculate_prices( $prices, $pricing_args, $items ) {

            if ( !isset( $pricing_args[ 'args' ][ 'pricing_type' ] ) ) {

                return $prices;
            }

            $pricing_type = $pricing_args[ 'args' ][ 'pricing_type' ];

            if ( $this->pricing_type_prices->can_calculate( $pricing_type ) ) {

                return $this->pricing_type_prices->calculate_prices( $prices, $this->prepare_pricing_args( $pricing_args ), $items );
            }

            $filter_key = 'checkout-pricing_calculate-' . $pricing_type . '-type-prices';

            if ( has_filter( 'pricely_' . $filter_key ) ) {

                return apply_filters( 'pricely_' . $filter_key, $prices, $this->prepare_pricing_args( $pricing_args ), $items );
            }

            return $prices;
        }

        public function get_items( $args ) {

            return Pricely_Checkout_Prices_Modes::get_instance()->get_items( $args );
        }

        private function prepare_pricing_args( $in_pricing_args ) {

            $pricing_args = array(
                'pricing_id' => $in_pricing_args[ 'pricing_id' ]
            );

            foreach ( $in_pricing_args[ 'args' ] as $arg_key => $arg_value ) {

                if ( 'pricing_id' == $arg_key ) {

                    continue;
                }

                $pricing_args[ $arg_key ] = $arg_value;
            }

            return $pricing_args;
        }

    }

}

