<?php

namespace KupShop\ElninoBundle\View;

use KupShop\CatalogBundle\ProductList\ProductCollection;
use KupShop\ElninoBundle\Old\FilterParams;
use KupShop\ElninoBundle\Util\ElninoMultiFetch;

class CategoryView extends \KupShop\CatalogBundle\View\CategoryView
{
    public const RESULT_PRODUCT = 'product';
    public const RESULT_MODEL = 'model';

    protected $campaignResult = [];

    protected function prepareProductList()
    {
        parent::prepareProductList();
        $this->productList->addResultModifiers(function (ProductCollection $productCollection) {
            ElninoMultiFetch::fetchAdditionalData($productCollection);

            $categoryFlags = explode(',', $this->getCategory()['flags'] ?? '');
            // pokud ma sekce flag "Vyloha", tak fetchneme dalsi potrebna data
            if (in_array('TT', $categoryFlags)) {
                ElninoMultiFetch::fetchModelData($productCollection);
                ElninoMultiFetch::fetchSerieData($productCollection);
                ElninoMultiFetch::fetchProductTextParameters($productCollection);
            }
        });
    }

    public function getOrderFields($order_by)
    {
        switch ($order_by) {
            case 9:
                $order = 'SUM(p.pieces_sold2)';

                // hack: aby templaty věděly
                $this->category['bestseller'] = 'nejprodávanější';

                break;

            case 5:
                $order = 'SUM(p.pieces_sold)';
                break;

            case 10:
                $order = 'MAX((p.display_discount * (1 - (p.discount / 100))) + p.discount)';
                break;

            default:
                $order = parent::getOrderFields($order_by);
        }

        return $order;
    }

    public function getOrderFieldPrice()
    {
        $category = $this->getCategory()['list_models'];

        $this->productList->andSpec(function (\Query\QueryBuilder $qb) use ($category) {
            $qb->joinVatsOnProducts();
            if ($category == 'Y') {
                $qb->addSelect('COALESCE(MIN(IF(FIND_IN_SET("O", p.campaign), NULL, p.price)*(1+v.vat/100)*(1-p.discount/100)), p.price) as order_column');
            }
        });

        if ($category == 'Y') {
            return 'order_column';
        } else {
            return 'p.price*(1+v.vat/100)*(1-p.discount/100)';
        }
    }

    public function getTitleParams()
    {
        $title = parent::getTitleParams();

        if (!empty($this->category['plural'])
            && ($this->categoryId != 0 || (empty($title['producer']) && empty($title['campaign'])))
        ) {
            $title['category'] = $this->category['plural'];
        }

        if (!empty($this->category['bestseller'])) {
            $title['bestseller'] = $this->category['bestseller'];
        }

        return $title;
    }

    protected function prepareFilterParams()
    {
        parent::prepareFilterParams();

        if (!empty($this->campaign) && !empty($this->campaignResult)) {
            if (isset($this->campaignResult[$this->campaign])) {
                switch ($this->campaignResult[$this->campaign]) {
                    case self::RESULT_PRODUCT:
                        $this->category['list_models'] = 'N';
                        $this->filterParams->setResultEntity(FilterParams::ENTITY_PRODUCT);
                        break;
                    case self::RESULT_MODEL:
                        $this->filterParams->setResultEntity(FilterParams::ENTITY_MODEL);
                        break;
                }
            }
        }
    }

    public function setCampaignResult($campaigns)
    {
        $this->campaignResult = $campaigns;
    }

    protected function defaultOrderStart($productAlias, $query)
    {
        $query = parent::defaultOrderStart($productAlias, $query);

        if (\Settings::getDefault()->prod_subtract_from_store) {
            $query['order_start'] = "IF({$productAlias}.in_store > 0, COALESCE(MAX(psp.position) - ".POSITION_STANDARD.', p.position, '.POSITION_STANDARD.'), COALESCE(MAX(psp.position) - '.POSITION_STANDARD.', p.position, '.POSITION_STANDARD.') + 10000)';
        } else {
            $query['order_start'] = 'COALESCE(MAX(psp.position) - '.POSITION_STANDARD.', p.position, '.POSITION_STANDARD.')';
        }

        return $query;
    }
}
