<?php

namespace App\OfferProfileRules;

class OfferDetails_Discount implements OfferDetailsInterface
{

	/**
	 * The source of the bulk discount: 'servicePrice', 'supplier', 'commission', 'serviceFee', 'servicePrice+serviceFee', 'commission+serviceFee'.
	 * @var String
	 */
	public $percentSource;

	/**
	 * Discount percent - [0-100]
	 * @var Float
	 */
	public $percent;

	/**
	 * Discount absolute value
	 * @var Float
	 */
	public $value;

	/**
	 * Discount currency (associated to discount value).
	 * @var String
	 */
	public $currency;


	/**
	 *
	 * {@inheritDoc}
	 * @see \App\OfferProfileRules\OfferDetailsInterface::check()
	 */
	public function check(\App\MessagesCollector $msgs)
	{
		$return = true;

		// check discount bulk source
		if (!in_array($this->percentSource, ['servicePrice', 'supplier', 'commission', 'serviceFee', 'servicePrice+serviceFee', 'commission+serviceFee'])) {
			$msgs->addError('Discount bulk source is not valid - it must be set as: `servicePrice`, `supplier`, `commission`, `serviceFee`, `servicePrice+serviceFee`, `commission+serviceFee`.');
			$return = false;
		}

		$value = (string)$this->value;
		$percent = (string)$this->percent;

		// DISCOUNT CHECK -------------------------------------------------------------------------

		// check value and percent
		if (!strlen($percent) and !strlen($value)) {
			$msgs->addError('You must set the discount percent or value.');
			$return = false;
		}
		if (strlen($value) and strlen($percent)) {
			$msgs->addWarning('The discount absolute value and the percent cannot be both set at the same time.');
			$return = false;
		}

		// check percent
		if (strlen($percent) and (!is_numeric($percent) or $percent<0)) {
			$msgs->addError('The discount percent must be a positive value.');
			$return = false;
		}

		// check value and currency
		if (strlen($value)) {
			if (!is_numeric($value) or $value<0) {
				$msgs->addError('Discount absolute value cannot be negative.');
				$return = false;
			}
			if (!\App\Config\Currencies::getInstance()->check($this->currency)) {
				$msgs->addError('Discount currency is not valid.');
				$return = false;
			}
		}

		return $return;

	}

	/**
	 * (non-PHPdoc)
	 * @see \App\OfferProfileRules\OfferDetailsInterface::getDescription()
	 */
	public function getDescription($fullDescription=true)
	{

		$_LANG = \App\Loader_Lang::getInstance()->getAll();

		$return = '';

		if ($this->percent!==null and $fullDescription) {
			$return .= $this->percent.'% - '.$_LANG['OfferProfileRules']['discount']['percentSource'][$this->percentSource];
		}
		elseif ($this->percent!==null and !$fullDescription) {
			$return .= $this->percent.'%';
		}
		elseif ($this->value) {
			$return .= \App\Utils\PriceFormat::format($this->value, $this->currency);
		}

		return $return;
	}

}

