<?php

namespace KupShop\ReturnsBundle\View;

use KupShop\ReturnsBundle\Query\Returns;
use KupShop\ReturnsBundle\Util\ReturnsUtil;

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

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

    private $returns;

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

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

        $vars['returns'] = $this->getReturns();
        $vars['accepted_statuses'] = $this->returns->getAcceptedStatuses();
        $vars['handle_statuses'] = $this->returns->getHandleStatuses();

        return $vars;
    }

    private function getReturns()
    {
        $returns = sqlQueryBuilder()->select('r.*, o.order_no')
            ->from('returns', 'r')
            ->andWhere(Returns::joinOrders())
            ->andWhere($this->returns->getOrdersSpec())
            ->orderBy('r.id', 'DESC')
            ->groupBy('r.id');

        $statuses = $this->returns->getStatuses();

        $result = [];
        foreach ($returns->execute() as $return) {
            $return['status_name'] = $statuses[$return['status']];
            $return['items'] = $this->returns->getReturnItems((int) $return['id']);
            $result[] = $return;
        }

        return $result;
    }

    public function getBreadcrumbs()
    {
        return getReturnNavigation(-1, 'RETURN');
    }

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