<?php

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

if ( !class_exists( 'Pricely_Product_Prices_Type_Sale' ) ) {

    class Pricely_Product_Prices_Type_Sale {

        public function get_prices( $prices, $prices_args, $data ) {

            if ( 'fixed_price' == $prices_args[ 'sale_adj' ][ 'adj_type' ] ) {

                return $this->get_fixed_price( $prices, $prices_args );
            }

            if ( 'per_discount' == $prices_args[ 'sale_adj' ][ 'adj_type' ] ) {

                return $this->get_per_discount_price( $prices, $prices_args, $data );
            }

            return $prices;
        }

        private function get_fixed_price( $prices, $prices_args ) {

            $amount = $prices_args[ 'sale_adj' ][ 'amount' ];

            if ( !is_numeric( $amount ) ) {

                $prices[ 'sale_price' ] = 0;

                return $prices;
            }

            $prices[ 'sale_price' ] = ( float ) $amount;

            return $prices;
        }

        private function get_per_discount_price( $prices, $prices_args, $data ) {

            $amount = $prices_args[ 'sale_adj' ][ 'amount' ];

            if ( !is_numeric( $amount ) ) {

                $amount = 0;
            }

            $product_prices_pypes = Pricely_Product_Prices_Types::get_instance();

            $per_based_on = $this->get_per_based_on( $prices_args );

            $per_amount = $product_prices_pypes->get_based_on_amount( $per_based_on, $data );

            if ( !$per_amount ) {

                $prices[ 'sale_price' ] = 0;

                return $prices;
            }

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

            $discount_based_on = $this->get_discount_based_on( $prices_args );

            $from_amount = $product_prices_pypes->get_based_on_amount( $discount_based_on, $data );

            if ( !$from_amount ) {

                $prices[ 'sale_price' ] = 0;

                return $prices;
            }

            $prices[ 'sale_price' ] = $from_amount - $discount_amount;

            return $prices;
        }

        private function get_per_based_on( $prices_args ) {

            $based_on = 'regular_price';

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

                $based_on = $prices_args[ 'sale_adj' ][ 'per_based_on' ];
            }

            return $based_on;
        }

        private function get_discount_based_on( $prices_args ) {

            $based_on = 'regular_price';

            if ( isset( $prices_args[ 'sale_adj' ][ 'discount_based_on' ] ) && '' != $prices_args[ 'sale_adj' ][ 'discount_based_on' ] ) {

                $based_on = $prices_args[ 'sale_adj' ][ 'discount_based_on' ];
            }

            return $based_on;
        }

    }

}
