<?php

namespace KupShop\PohodaBundle\Admin\Actions;

use KupShop\AdminBundle\Admin\Actions\AbstractAction;
use KupShop\AdminBundle\Admin\Actions\ActionResult;
use KupShop\AdminBundle\Admin\Actions\IAction;
use KupShop\AdminBundle\Util\ActivityLog;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\OrderingBundle\Util\Order\OrderInfo;
use KupShop\PohodaBundle\Exceptions\PohodaException;
use KupShop\PohodaBundle\Utils\Exporters\InvoiceFromOrderExporter;
use KupShop\PohodaBundle\Utils\Exporters\OrdersDeleter;
use KupShop\PohodaBundle\Utils\Exporters\OrdersExporter;
use Query\Operator;

class OrderUpdateAction extends AbstractAction implements IAction
{
    /**
     * @var OrdersDeleter
     */
    protected $ordersDeleter;

    /**
     * @var OrdersExporter
     */
    protected $ordersExporter;

    public function getTypes(): array
    {
        return ['orders'];
    }

    public function getName(): string
    {
        return 'POHODA: Přenahrát objednávku';
    }

    public function execute(&$data, array $config, string $type): ActionResult
    {
        try {
            $objectData = $this->getWindow()->getObjectData();
            $this->ordersDeleter->setIDs([$this->getId()]);
            $this->ordersDeleter->processData();

            $results = $this->ordersDeleter->getResults();

            if (!($results[$this->getId()]['result'] ?? false) && ($results[$this->getId()]['errno'] != '115')) {
                $error = $results[$this->getId()]['error'] ?? 'neznámý důvod';

                return new ActionResult(false, "{$results[$this->getId()]['errno']}: Objednávku se nepodařilo smazat - {$error}");
            }

            if (findModule(\Modules::POHODA, \Modules::SUB_GENERATE_INVOICES)) {
                sqlQueryBuilder()
                    ->delete('orders_pohoda_invoices')
                    ->andWhere(Operator::equals(['id_order' => $this->getId()]))
                    ->execute();
            }

            $this->ordersExporter->setIDs([$this->getId()]);
            $this->ordersExporter->pohodaConnector->skipSaveLastSyncTime(true);
            $this->ordersExporter->processData();

            addActivityLog(ActivityLog::SEVERITY_NOTICE, ActivityLog::TYPE_CHANGE, "Pohoda: ruční přenahraní obj id {$this->getId()}");

            if ($objectData['source'] == OrderInfo::ORDER_SOURCE_RETURNS && findModule(\Modules::POHODA,
                \Modules::SUB_CREATE_CORRECTIVE_INVOICE_FROM_RETURNS)) {
                // Automaticky nastavi typ dopropis uvnitr xslt na zaklade order SOURCE == vratka
                $invoiceFromOrderExporter = ServiceContainer::getService(InvoiceFromOrderExporter::class);
                $invoiceFromOrderExporter->setIDs([$this->getId()]);
                $invoiceFromOrderExporter->processData();
                addActivityLog(ActivityLog::SEVERITY_NOTICE,
                    ActivityLog::TYPE_CHANGE,
                    "Pohoda: Ruční vygenerování faktury k obj ID:{$this->getId()}");
            }
        } catch (PohodaException $e) {
            return new ActionResult(false, $e->getMessage());
        }

        return new ActionResult(true, 'Objednávka přenahrána.');
    }

    /**
     * @required
     */
    public function setOrdersDeleter(OrdersDeleter $ordersDeleter): void
    {
        $this->ordersDeleter = $ordersDeleter;
    }

    /**
     * @required
     */
    public function setOrdersExporter(OrdersExporter $ordersExporter): void
    {
        $this->ordersExporter = $ordersExporter;
    }

    public function getPriority(): int
    {
        return 1;
    }

    public function showInMassEdit()
    {
        return true;
    }

    public function isEnabled()
    {
        return findModule(\Modules::POHODA, \Modules::SUB_ORDER_REUPLOAD);
    }

    /**
     *  Pokud akci chcete v nějakých stavech dialogu třeba nezobrazit.
     *
     * @return false
     */
    public function isVisible()
    {
        return $this->dialogData['pohoda_id'];
    }
}
