<?php
namespace App\Utils\BaseParser\Structure\StructureParser\Types;

/**
 * Base structure for the FOP data
 * @author Lucian Sirbu
 */
abstract class PriceFormOfPayment extends \App\Utils\BaseParser\Structure\StructureParser\Types\BaseAbstract
{
	public $components = 		[];

	/**
	 * Append a form of payment component
	 * @param \App\Utils\BaseParser\Structure\StructureParser\Types\PriceFormOfPaymentComponent $component
	 */
	public function append(\App\Utils\BaseParser\Structure\StructureParser\Types\PriceFormOfPaymentComponent $component)
	{
		$this->components[] = $component;
		return $this;
	}

	/**
	 * Get the a short human-readable notation for the forms of payments used in this transaction.
	 * Used mainly for compatibility with the old code or for displaying in the interface
	 * @return string
	 */
	public function getShortNotation()
	{
		$return = [];
		foreach ($this->components as $comp) {
			$return[] = $comp->type;
		}
		sort($return);
		$return = array_unique($return);
		return implode("+", $return);
	}

	/**
	 * Check if the form of payment contains a specific form of payment.
	 * Mainly used to check if it was paid with CC
	 * @param string $payment
	 * @return boolean
	 */
	public function isPaidWith($paymentType)
	{
		foreach ($this->components as $comp) {
			if ($comp->type==$paymentType) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Get all CC or cash payments
	 * ($index is optional. if requested returns the specified index, because PHP doesn't support f()[12] syntax)
	 * @return array
	 */
	public function getPaymentByType($paymentType, $index=null)
	{
		$return = [];
		foreach ($this->components as $comp) {
			if ($comp->type==$paymentType) {
				$return[] = $comp;
			}
		}

		if ($index===null) {
			return $return;
		}

		return $return[$index];
	}
}
