<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Checkout_Prices_Modes_Simple' ) ) {

    class Pricely_Checkout_Prices_Modes_Simple {

        private $prices_types;

        public function __construct() {

            $this->prices_types = Pricely_Checkout_Prices_Types::get_instance();
        }

        public function can_calculate( $pricing_mode ) {

            if ( 'simple' == $pricing_mode ) {

                return true;
            }

            return false;
        }

        public function calculate_prices( $prices, $prices_args ) {

            $pricing_args = $this->get_pricing_args( $prices_args );

            $items = $this->prepare_item_quantity( $this->get_items( $prices_args ) );

            $prices = $this->prices_types->calculate_prices( $prices, $pricing_args, $items );

            return $prices;
        }

        private function get_pricing_args( $prices_args ) {

            if ( !is_array( $prices_args[ 'simple_pricing' ] ) ) {

                return false;
            }

            $pricing_args = array(
                'pricing_id' => $prices_args[ 'pricing_id' ],
                'args' => $prices_args[ 'simple_pricing' ]
            );

            return $pricing_args;
        }

        private function get_items( $prices_args ) {

            $args = array(
                'context' => $prices_args[ 'context' ],
                'product_args' => array(),
                'group_by' => false,
                'sort_by' => false,
                'exclude_keys' => false
            );

            if ( isset( $prices_args[ 'product_args' ] ) ) {

                $args[ 'product_args' ] = $prices_args[ 'product_args' ];
            }

            return $this->prices_types->get_items( $args );
        }

        private function prepare_item_quantity( $items ) {

            if ( !is_array( $items ) ) {

                return $items;
            }

            $item_keys = array_keys( $items );

            foreach ( $item_keys as $item_key ) {

                $items[ $item_key ][ 'pricing_quantity' ] = $items[ $item_key ][ 'items_in_cart' ][ 'quantity' ];
            }

            return $items;
        }

    }

}
