<?php

namespace KupShop\ContentBundle\View;

use KupShop\ComponentsBundle\Twig\DataProvider\OrderDataProvider;
use KupShop\ComponentsBundle\View\ComponentsViewInterface;
use KupShop\ComponentsBundle\View\ComponentsViewTrait;
use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\KupShopBundle\Views\Traits\RequestTrait;
use KupShop\KupShopBundle\Views\View;
use KupShop\OrderingBundle\OrdersList;
use Query\Filter;
use Query\Operator;
use Query\Order;
use Symfony\Component\HttpFoundation\Request;

class OrdersView extends View implements ComponentsViewInterface
{
    use RequestTrait;
    use ComponentsViewTrait;

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

    /** @var OrdersList */
    protected $ordersList;

    protected $title;

    private array $filter;

    public function __construct(OrdersList $ordersList,
        protected ?OrderDataProvider $orderDataProvider = null,
    ) {
        $this->ordersList = $ordersList;
    }

    public function getResponse(?Request $request = null)
    {
        if (!findModule('orders')) {
            redirection('MODUL_NOT_FOUND');
        }

        if (!Contexts::get(UserContext::class)->isActive()) {
            redirection('LOGIN');
        }

        return parent::getResponse($request);
    }

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

        $vars['pager'] = $this->ordersList->createPager();

        $this->ordersList->andSpec($vars['pager']->getSpec());

        $status = $this->request->get('status');

        if ($status !== null && ($status >= 0 && $status <= 2)) {
            $this->ordersList->andSpec(Order::byStatus([$status]));
        }

        // Filter:
        // Vyhledat produkt
        if (!empty($this->filter['product'])) {
            $additionalFields = [
                ['field' => 'oi.descr', 'match' => 'both'],
            ];
            $products = sqlQueryBuilder()->select('oi.id')
                ->from('order_items', 'oi')->where('oi.id_order = o.id')
                ->join('oi', 'products', 'p', 'p.id = oi.id_product')
                ->joinVariationsOnProducts()
                ->andWhere(Filter::search($this->filter['product'], $additionalFields));
            $this->ordersList->andSpec(Operator::exists($products));
        }
        // Vyhledat objednávku
        if (!empty($this->filter['order'])) {
            $order = sqlQueryBuilder()->select('id, order_no')->from('orders')
                ->andWhere(Operator::equals(['id' => $this->filter['order'], 'order_no' => $this->filter['order']], 'OR'))
                ->execute()->fetchAssociative();
            if ($order) {
                $this->ordersList->andSpec(Operator::equals(['o.id' => $order['id']]));
            }
            $this->filter['order'] = ($order ? $order['order_no'] : null);
        }
        $vars['filter'] = $this->filter ?? [];

        $vars['orders'] = $this->ordersList->getOrders();
        $vars['pager']->setTotal($this->ordersList->getNoItems());
        $vars['totalPrice'] = '';
        $vars['pageDivider'] = $this->ordersList->getdivide();

        if (findModule(\Modules::COMPONENTS)) {
            $this->orderDataProvider->addOrders(array_column($vars['orders'], 'orderObj'));
            $vars['orders'] = array_column($vars['orders'], 'id');

            return $vars;
        }

        return $vars;
    }

    public function getTitle()
    {
        return translate('title', 'orders');
    }

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

    public function getBreadcrumbsNew(): array
    {
        $breadcrumbs[] = ['link' => path('home'), 'text' => translate('getSections', 'functions')['home']];
        $breadcrumbs[] = ['link' => path('account'), 'text' => translate('title', 'account')];
        $breadcrumbs[] = ['text' => $this->getTitle()];

        return $breadcrumbs;
    }

    public function setFilter(array $filter): void
    {
        $this->filter = $filter;
    }
}
