<?php
namespace App\Apollo\StructureParser;

/**
 * This class can process the file content and generate a list of transactions.
 *
 * @author Lucian Sirbu
 */
class Processor extends \App\Galileo\StructureParser\Processor {
    /**
     * {@inheritdoc}
     *
     * @see \App\Utils\BaseParser\Structure\StructureParser\Processor::buildTransactionObj()
     */
    protected function buildTransactionObj(?\App\Utils\BaseParser\Structure\StructureParser\Processor $processor = null, $transactionType = null, $transactionIndexes = null, $classType = 'Transaction') {
        if ('Transaction' == $classType) {
            return new \App\Apollo\StructureParser\Structures\Transaction($processor, $transactionType, $transactionIndexes);
        }

        throw new \Exception('Unknown class type used');
    }

    /**
	 * this function is overwritten for Galileo
	 */
	protected function triggerPlugins(array $transactions)
	{
        // save the original components
		foreach ($transactions as $tr) {
			if ($tr->price) {
                $paxPrice = $tr->price;

				$paxPrice->originalPriceArr['supplier'] = 				$paxPrice->supplier;
				$paxPrice->originalPriceArr['supplierCurrency'] = 		$paxPrice->supplierCurrency;

				$paxPrice->originalPriceArr['tax'] = 					$paxPrice->tax->getAmount();
				$paxPrice->originalPriceArr['taxCurrency'] = 			$paxPrice->tax->getCurrency();

				$paxPrice->originalPriceArr['commission'] = 			$paxPrice->commission + $paxPrice->commissionVAT;
				$paxPrice->originalPriceArr['commissionCurrency'] = 	$paxPrice->commissionCurrency;
				$paxPrice->originalPriceArr['commissionComponents'] = 	array_map(function($c) {
					return [
						'IOSource' =>		'raw',			// technically we could add stuff from plugins in here when overriding amounts in IO, it's specific to IO
						'category' => 		$c->category,
						'source' => 		$c->source,
						'amount' => 		$c->amount,
						'VAT' => 			$c->VAT,
						'currency' => 		$c->currency,
						'code' => 			$c->code,
					];
				}, $paxPrice->components->getComponentsByCategory('commission'));

			}
		}

		\Engine\Plugins\Manager::getInstance()->executeEvent('Apollo-getTransactions', ['this'=>$this, 'transactions'=>$transactions]);
	}

    protected function getTransactionFromRefundRaw(array $transactions, $transactionIndexes)
	{
        $transaction = $this->buildTransactionObj($this, "refund", []);
        $transaction->setMessagesCollector(new \App\MessagesCollector());
        $structureHandled = true;
        $transactions[] = $transaction->getData();

        return [$structureHandled, $transactions, ];
    }
}
