<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Pipeline_Coupons_Internal' ) ) {

    class Pricely_Pipeline_Coupons_Internal {

        private static $instance;
        private $options;
        private $cart_discounts_prefix;

        public static function get_instance(): self {

            if ( !self::$instance ) {

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

            return self::$instance;
        }

        public function __construct() {

            $this->options = array();

            $this->cart_discounts_prefix = 'pricely-d';
        }

        public function get_coupon_codes() {

            return $this->get_cart_discounts_coupon_codes( array() );
        }

        private function get_cart_discounts_coupon_codes( $coupon_codes ) {

            if ( !$this->get_cart_discounts_enabled() ) {

                return $coupon_codes;
            }

            $default = array();

            $options = $this->get_options( 'cart_discounts', $default );


            foreach ( $options as $option ) {

                if ( 'no' == $option[ 'enable' ] ) {

                    continue;
                }

                $discount_id = $option[ 'discount_id' ];

                $coupon_code = $this->prepare_cart_discount_coupon_code( $option[ 'coupon_code' ], $discount_id );

                if ( in_array( $coupon_code, $coupon_codes ) ) {

                    continue;
                }

                $coupon_codes[] = $coupon_code;
            }

            return $coupon_codes;
        }

        private function get_cart_discounts_enabled() {

            $default = array( 'mode' => 'no' );

            $options = $this->get_options( 'cart_discounts_settings', $default );

            return ($options[ 'mode' ] !== 'no');
        }

        private function prepare_cart_discount_coupon_code( $coupon_code, $discount_id ) {

            if ( empty( $coupon_code ) ) {

                $coupon_code = $this->cart_discounts_prefix . $discount_id;
            }

            return $coupon_code;
        }

        private function get_options( $option_key, $default ) {


            if ( isset( $this->options[ $option_key ] ) ) {

                return $this->options[ $option_key ];
            }

            $this->options[ $option_key ] = Pricely::get_instance()->get_options( $option_key, $default );

            return $this->options[ $option_key ];
        }

    }

}