<?php


namespace Shop\Application\Shopping\PrepareProviderOrderDataForReport;


use Propel\Runtime\Map\TableMap;
use Shop\Application\Catalog\CatalogService;
use Shop\Application\Office\OfficeService;
use Shop\Application\Shopping\CreateFileFromOrderItems\CreateFileFromOrderItemsCommand;
use Shop\Application\Shopping\CreateFileFromOrderItems\ResultLink;
use Shop\Config\Main;
use spaceonfire\CommandBus\CommandBus;

class PrepareProviderOrderDataForReportHandler
{
    protected $mainConf;
    protected $officeService;
    protected $commandBus;

    /**
     * PrepareProviderOrderDataForReportHandler constructor.
     * @param Main $main
     * @param CommandBus $commandBus
     * @param OfficeService $officeService
     */
    public function __construct(Main $main,
                                CommandBus $commandBus,
                                OfficeService $officeService)
    {
        $this->mainConf = $main;
        $this->officeService = $officeService;
        $this->commandBus = $commandBus;
    }

    /**
     * @param PrepareProviderOrderDataForReportCommand $command
     */
    public function handle(PrepareProviderOrderDataForReportCommand $command): void
    {

        $order = $command->getResult();

        $stockContractor = $order->getCustomer();

        /**
         * @var Currency $currency
         */
        $currency = $order->getOrderItems()->getFirst()->getCurrency();

        $currencyDisplay = $currency->getHtmlSign();


        $logoPath = $this->officeService->getStockLogoPath(
            $stockContractor->getStockIfContractor(
                $this->mainConf->getDefaultContractorGroup()
            )
        );

        $data = [
            'order_code' => $order->getOrderCode(),
            'stock_logo_path' => !$logoPath ? null : getenv('BASE_URL') . $logoPath,
            'order' => $order->toArray(TableMap::TYPE_FIELDNAME),
            'order_items' => $order->getOrderItems()->toArray(null, false, TableMap::TYPE_FIELDNAME),
            'stock' => $stockContractor->toArray(TableMap::TYPE_FIELDNAME),
            'payment' => $order->getPayment()->toArray(TableMap::TYPE_FIELDNAME),
            'sum' => $order->getSumm(),
            'order_finalSum' => $order->getOrderFinalSumm(),
            'discountSum' => $order->getDiscountSumm(),
            'discount_percent' => $order->getDiscountPercent(),
            'currency' => $currencyDisplay,
            'provider'  => $order->getContractor()->getName()
        ];

        $result = new ResultLink();

        $this->commandBus->handle(new CreateFileFromOrderItemsCommand(
            $data['order_items'],
            'provider_order_' .$order->getOrderCode(),
            $result
            ));

        $data['attach'] = (array)$result->getFileLink();

        $command->getResult()->setData($data);
    }
}