<?php

namespace KupShop\ReclamationsBundle\View;

use KupShop\ReclamationsBundle\Util\ReclamationsUtil;
use KupShop\ReturnsBundle\View\ReturnsReclamationsView;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ReclamationView extends ReturnsReclamationsView
{
    protected static $type = 'reclamations';

    protected $template = 'reclamations/reclamation.tpl';
    protected string $smartyFallback = 'account';
    protected string $entrypoint = 'account';

    private $reclamationId;
    private $reclamations;

    private $reclamation;
    private $requestStack;

    public function __construct(ReclamationsUtil $reclamationsUtil, RequestStack $requestStack)
    {
        $this->reclamations = $reclamationsUtil;
        $this->requestStack = $requestStack;
    }

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

        $dbcfg = \Settings::getDefault();

        $reclamation = $this->getReclamation();
        if (!$reclamation) {
            throw new NotFoundHttpException('Reclamation not found');
        }

        $vars['reclamation'] = $reclamation;
        $vars['text'] = !empty($dbcfg->reclamations['descr']) ? replacePlaceholders($dbcfg->reclamations['descr'], [
            'KOD_REKLAMACE' => $vars['reclamation']['code'],
            'ODKAZ_PDF' => path('kupshop_reclamations_reclamations_reclamationattachment', ['id' => $reclamation->getId()]),
            'PACKAGE_LABEL' => $this->reclamations->getAuthCode($reclamation->getId()),
        ]) : '';

        return $vars;
    }

    public function getReclamation()
    {
        if (!$this->reclamation) {
            $cf = $this->requestStack->getMainRequest()->get('cf');
            if (!($this->reclamation = $this->reclamations->getReclamation($this->reclamationId, $cf != $this->reclamations->getSecurityCode($this->reclamationId)))) {
                throw new NotFoundHttpException('Reclamation not found');
            }
        }

        return $this->reclamation;
    }

    public function setReclamationId(int $reclamationId)
    {
        $this->reclamationId = $reclamationId;

        return $this;
    }

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

    public function getTitle()
    {
        return translate('reclamation_title', 'reclamations').': '.$this->getReclamation()->getCode();
    }

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

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