<?php

namespace Discountify\Core\Frontend;

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

use Discountify\Core\Frontend\Rules;
use Discountify\Utils\Singleton;

/**
 * Calculator Class
 *
 * @since 1.0.0
 */
class Calculator extends Rules {

	use Singleton;

	/**
	 * Calculate discount type
	 */
	public function discount_settings() {
		$settings = \Discountify\Utils\Helper::get_settings();

		return $settings;
	}

	/**
	 * Calculate discount type
	 */
	public function discount_rules() {
		return (array) \Discountify\Utils\Helper::get_all_rules();
	}

	/**
	 * Calculator to calculate discount price from original price
	 *
	 * @param $type
	 * @param $original_value
	 * @param $value
	 * @return float|int
	 */
	public function calculate_discount( $type, $original_value, $value ) {
		$discount = 0;
		if ( $value < 0 || empty( $original_value ) ) {
			return $discount;
		}
		$original_value = floatval( $original_value );
		$value          = floatval( $value );

		switch ( $type ) {
			case 'fixed_price':
				$discount_value = floatval( $value );
				if ( $discount_value > $original_value ) {
					$discount_value = $original_value;
				}
				$discount = $original_value - $discount_value;
				break;
			case 'percentage':
				if ( ! empty( $value ) ) {
					if ( $value > 100 ) {
						$value = 100;
					}
					$discount = $original_value * ( $value / 100 );
				}
				break;
			default:
			case 'flat':
				$discount = floatval( $value );
				if ( $discount > $original_value ) {
					$discount = $original_value;
				}
				break;
		}

		return $discount;
	}

	/**
	 * Discount price
	 */
	public function apply_discount( $original_value, $discount ) {
		return $original_value - $discount;
	}
}
