<?php

namespace KupShop\ReturnsBundle\Page;

use KupShop\ContentBundle\Entity\Placeholder;
use KupShop\ContentBundle\Page\BasePage;
use KupShop\ReturnsBundle\Entity\ReturnEntity;
use KupShop\ReturnsBundle\Util\ReturnsUtil;

abstract class AbstractReturnDeliveryPage extends BasePage
{
    protected $returnDeliveryClass;

    protected ?ReturnEntity $returnEntity = null;

    /**
     * @required
     */
    public ReturnsUtil $returnsUtil;

    public function setReturnEntity(?ReturnEntity $returnEntity): void
    {
        $this->returnEntity = $returnEntity;
    }

    public function getReturn(): ?ReturnEntity
    {
        if ($this->returnEntity) {
            return $this->returnEntity;
        }

        if ($this->view && method_exists($this->view, 'getReturn')) {
            $this->returnEntity = $this->view->getReturn();
        } elseif (getAdminUser()) {
            $idReturn = sqlQueryBuilder()->select('r.id')->from('returns', 'r')
                ->innerJoin('r', 'return_delivery', 'rd', "r.id_return_delivery = rd.id AND rd.type = '{$this->returnDeliveryClass}'")
                ->setMaxResults(1)
                ->orderBy('r.date_created', 'DESC')
                ->execute()->fetchOne();

            $this->returnEntity = $idReturn ? $this->returnsUtil->getReturn($idReturn) : null;
        }

        return $this->returnEntity;
    }

    protected function getCustomData()
    {
        $return = $this->getReturn();

        return $return?->getCustomData() ?? [];
    }

    protected function getReturnDeliveryLabel(): array
    {
        $returnDeliveryLabel = $this->getCustomData()['returnDeliveryLabel'] ?? [];
        $idReturnDelivery = $this->getReturn()?->getIdReturnDelivery();
        if ($returnDeliveryLabel[$idReturnDelivery] ?? null) {
            $returnDeliveryLabel = $returnDeliveryLabel[$idReturnDelivery];
        }

        return (array) $returnDeliveryLabel;
    }

    public function getPlaceholders(): array
    {
        return [
            new Placeholder('KOD_VRATKY', 'Kód vratky', fn () => $this->getReturn()?->getCode() ?? '-'),
        ];
    }
}
