<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Product_Promotion_Price_At_Checkout' ) ) {

    class Pricely_Product_Promotion_Price_At_Checkout {

        private static $instance;

        public static function get_instance(): self {

            if ( !self::$instance ) {

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

            return self::$instance;
        }

        public function calculate( $price_args, $product ) {

            $price = false;

            if ( 'fixed_price_item' === $price_args[ 'pricing_type' ] ) {

                $price = $this->get_fixed_price( $price_args );
            }

            if ( 'per_price' == $price_args[ 'pricing_type' ] ) {

                $price = $this->get_per_price( $price_args, $product );
            }

            if ( false === $price ) {

                $price = apply_filters( 'pricely_product-promotions_calculate-checkout-price', $price, $price_args, $product );
            }

            return $price;
        }

        private function get_fixed_price( $price_args ) {

            $amount = false;

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

                $amount = ( float ) $price_args[ 'amount' ];
            }

            return $amount;
        }

        private function get_per_price( $price_args, $product ) {

            $amount = 0;

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

                $amount = ( float ) $price_args[ 'amount' ];
            }

            $based_on = $this->get_per_arg( $price_args );

            $per_amount = $this->get_based_on_amount( $based_on, $product );

            if ( !$per_amount ) {

                return 0;
            }

            $per_price = ($amount / 100) * $per_amount;

            return $per_price;
        }

        private function get_per_arg( $price_args ) {

            $based_on = 'regular_price';

            if ( isset( $price_args[ 'per_based_on' ] ) && '' != $price_args[ 'per_based_on' ] ) {

                $based_on = $price_args[ 'per_based_on' ];
            }

            return $based_on;
        }

        private function get_based_on_amount( $based_on, $product ) {

            if ( 'regular_price' == $based_on ) {

                return $product[ 'source_prices' ][ 'regular_price' ];
            }

            $filter_key = 'product-promotions_get-' . $based_on . '-based-on-amount';

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

                return apply_filters( 'pricely_' . $filter_key, 0, $product );
            }

            return 0;
        }

    }

}

