<?php

namespace KupShop\ReclamationsElninoBundle\View;

use KupShop\KupShopBundle\Views\BaseView;
use KupShop\ReclamationsElninoBundle\Query\Reclamations;
use KupShop\ReclamationsElninoBundle\Util\ReclamationsUtil;

class ReclamationsView extends \KupShop\ReclamationsBundle\View\ReclamationsView
{
    protected static $type = 'reclamations';

    protected $template = 'reclamations/reclamations.tpl';

    private $reclamations;

    public function __construct(ReclamationsUtil $reclamationsUtil)
    {
        parent::__construct($reclamationsUtil);
        $this->reclamations = $reclamationsUtil;
    }

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

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

        return $vars;
    }

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

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

        $result = [];
        foreach ($reclamations->execute() as $reclamation) {
            $reclamation['status_name'] = $statuses[$reclamation['status']];
            $reclamation['item'] = $this->reclamations->getReclamationItem($reclamation['id']);
            $result[] = $reclamation;
        }

        return $result;
    }
}
