<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}

if ( !class_exists( 'Reon' ) ) {

    return;
}

if ( !class_exists( 'Pricely_Admin_Locale_Product_Promotions' ) ) {

    require_once 'volumetric-price-table.php';
    require_once 'label.php';

    class Pricely_Admin_Locale_Product_Promotions {

        private static $instance;
        private $ui_options_key;
        private $volumetric_price_table;
        private $label;

        public static function get_instance(): self {

            if ( is_null( self::$instance ) ) {

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

            return self::$instance;
        }

        public function __construct() {

            $this->ui_options_key = 'product_promotions';

            $this->volumetric_price_table = Pricely_Admin_Locale_Product_Promotion_Volumetric_Price_Table::get_instance();
            $this->label = Pricely_Admin_Locale_Product_Promotion_Label::get_instance();
        }

        public function get_strings( $strings, $options ) {

            foreach ( $this->get_options( $options, $this->ui_options_key, array() ) as $setting ) {

                if ( !isset( $setting[ 'setting_id' ] ) ) {

                    continue;
                }

                if ( !isset( $setting[ 'promotions' ] ) ) {

                    continue;
                }

                if ( !is_array( $setting[ 'promotions' ] ) ) {

                    continue;
                }

                $setting_id = $setting[ 'setting_id' ];

                $strings = $this->get_promotions_strings( $strings, $setting[ 'promotions' ], $setting_id );
            }

            return $strings;
        }

        private function get_promotions_strings( $strings, $promotions, $setting_id ) {

            foreach ( $promotions as $promotion ) {

                $promotion[ 'setting_id' ] = $setting_id;

                $strings = $this->get_promotion_strings( $strings, $promotion );
            }

            return $strings;
        }

        private function get_promotion_strings( $strings, $promotion ) {

            if ( !isset( $promotion[ 'promotion_type' ] ) ) {

                return $strings;
            }

            $promotion_type = $promotion[ 'promotion_type' ];

            if ( $this->volumetric_price_table->can_process_string( $promotion_type ) ) {

                return $this->volumetric_price_table->process_strings( $strings, $promotion );
            }

            if ( $this->label->can_process_string( $promotion_type ) ) {

                return $this->label->process_strings( $strings, $promotion );
            }

            return apply_filters( 'pricely_get-product-promotion-locale-strings', $strings, $promotion );
        }

        private function get_options( $options, $option_key, $default ) {

            if ( isset( $options[ $option_key ] ) ) {

                return $options[ $option_key ];
            }

            return $default;
        }

    }

}

