<?php

namespace KupShop\ReturnsBundle\View;

use KupShop\ContentBundle\Page\BasePage;
use KupShop\KupShopBundle\Exception\RedirectException;
use KupShop\ReturnsBundle\Deliveries\Utils\ReturnDeliveries;
use KupShop\ReturnsBundle\Entity\ReturnEntity;
use KupShop\ReturnsBundle\Util\ReturnsUtil;
use Query\Operator;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ReturnView extends ReturnsReclamationsView
{
    protected static $type = 'returns';

    protected $template = 'returns/return.tpl';
    protected string $smartyFallback = 'account';
    protected string $entrypoint = 'account';

    private $returnId;

    private $returnCf;

    private $returns;

    private ?ReturnEntity $returnEntity = null;

    /**
     * @required
     */
    public ReturnDeliveries $returnDeliveries;

    public function __construct(ReturnsUtil $returns)
    {
        $this->returns = $returns;
    }

    public function getBodyVariables()
    {
        $vars = parent::getBodyVariables();

        $dbcfg = \Settings::getDefault();

        $return = $this->getReturn();
        if (!$return) {
            if ($this->returnCf) {
                throw new RedirectException(path('kupshop_returns_returns_createreturnslogin'));
            } else {
                throw new NotFoundHttpException('Return not found');
            }
        }

        if ($idOrder = $return->getIdOrder()) {
            $returnOrder = new \Order();
            $returnOrder->createFromDB($idOrder);
            $payment = $returnOrder->getDeliveryType()->getPayment();
            if ($payment) {
                $payment->setOrder($returnOrder);

                $vars['returnOrderPayment'] = $payment;
            }
        }

        $vars['return'] = $return;
        $vars['returnDeliveriesData'] = $this->returns->getReturnDeliveriesData($return->getId());

        if ($return->getIdReturnDelivery()) {
            $returnDelivery = $this->returnDeliveries->getReturnDeliveryEntity($return->getIdReturnDelivery());

            if ($returnDelivery?->getClass()->retrieveDataFromBalikobot() && empty($return->getCustomData()['returnDeliveryLabel'])) {
                $vars['labelGenerationFailed'] = true;
            }
        }

        $vars['text'] = !empty($dbcfg->returns['descr']) ? replacePlaceholders($dbcfg->returns['descr'], [
            'KOD_VRATKY' => $vars['return']['code'],
        ]) : '';
        if ($return->getIdReturnDelivery()) {
            $vars['returnDeliverySystemPage'] = $this->getReturnDeliverySystemPage($return)->getType();
        }

        if ($return->getIdReplacementDeliveryType()) {
            $return->setReplacementDeliveryType(\DeliveryType::getAll(true)[$return->getIdReplacementDeliveryType()]);
        }

        return $vars;
    }

    protected function getReturnDeliverySystemPage(ReturnEntity $returnEntity): BasePage
    {
        $returnDeliveryEntity = $this->returnDeliveries->getReturnDeliveryEntity($returnEntity->getIdReturnDelivery());

        return $returnDeliveryEntity->getClass()->getPage();
    }

    public function updateBankAccountNumber($number)
    {
        if (!empty($number)) {
            sqlQueryBuilder()->update('returns')
                ->directValues(['bank_account' => $number])
                ->where(Operator::equals(['id' => $this->returnId]))
                ->execute();
        }

        throw new RedirectException(
            path('kupshop_returns_returns_return', ['id' => $this->returnId])
        );
    }

    public function getReturn()
    {
        if (!$this->returnEntity) {
            $this->returnEntity = $this->returns->getReturn($this->returnId, $this->returnCf != $this->returns->getSecurityCode($this->returnId)) ?: null;
        }

        return $this->returnEntity;
    }

    public function setReturnId(int $returnId)
    {
        $this->returnId = $returnId;

        return $this;
    }

    public function setReturnCf($returnCf)
    {
        $this->returnCf = $returnCf;

        return $this;
    }

    public function getBreadcrumbs()
    {
        return getReturnNavigation(-1, 'RETURN', [$this->getTitle()]);
    }

    public function getTitle()
    {
        return translate('return_title', 'returns');
    }

    public function getWpjToolbar()
    {
        $arr = [
            'url' => getAdminUrl('Returns', ['ID' => $this->returnId]),
            'title' => 'Upravit vratku',
        ];

        return array_merge(parent::getWpjToolbar(), $arr);
    }

    public function getOrder()
    {
        $return = $this->getReturn();
        if ($idOrder = $return->getIdOrder()) {
            $returnOrder = new \Order();
            $returnOrder->createFromDB($idOrder);

            return $returnOrder;
        } else {
            throw new NotFoundHttpException('Return not found');
        }
    }
}
