<?php

use KupShop\AdminBundle\AdminList\BaseList;
use KupShop\AdminBundle\Query\Invert;
use KupShop\KupShopBundle\Query\JsonOperator;
use KupShop\KupShopBundle\Util\Price\Price;
use KupShop\KupShopBundle\Util\Price\PriceCalculator;
use Query\Operator;

class DeliveryList extends BaseList
{
    protected $tableDef = [
        'id' => 'id',
        'fields' => [
            'Doprava' => ['field' => 'delivery'],
            'Platba' => ['field' => 'payment'],
            'Cena s DPH' => ['field' => 'price', 'render' => 'renderPriceWithVat', 'class' => 'right'],
            'DPH' => ['field' => 'vat', 'render' => 'renderVat'],
            'Nezapočítat od' => ['field' => 'price_dont_countin_from', 'render' => 'renderPrice', 'class' => 'right'],
            'Zobrazit' => ['field' => 'figure', 'render' => 'renderBoolean'],
        ],
    ];

    private $priceUtil;

    public function __construct()
    {
        $this->priceUtil = \KupShop\KupShopBundle\Util\Compat\ServiceContainer::getService(\KupShop\KupShopBundle\Util\Price\PriceUtil::class);
    }

    public function renderVat($values, $column)
    {
        return getVat($values['vat']).'%';
    }

    public function renderPriceWithVat($values, $column)
    {
        if ($values['calc_price']) {
            $deliveryTypePrice = new Price(
                toDecimal($values['calc_price']),
                $this->priceUtil->getCurrencyById($values['currency']),
                getVat($values['vat'])
            );
        } else {
            $deliveryPrice = new Price(
                toDecimal($values['delivery_price']),
                $this->priceUtil->getCurrencyById($values['delivery_price_currency']),
                getAdminVat()['value']
            );
            $paymentPrice = new Price(
                toDecimal($values['payment_price']),
                $this->priceUtil->getCurrencyById($values['payment_price_currency']),
                getAdminVat()['value']
            );

            $deliveryTypePrice = PriceCalculator::add($deliveryPrice, $paymentPrice);
        }

        $price = PriceCalculator::convert($deliveryTypePrice, $this->priceUtil->getCurrencyById($values['currency']));

        $value = printPrice($price->getPriceWithVat(), ['currency' => $price->getCurrency()]);

        if ($values['calc_price']) {
            return \KupShop\KupShopBundle\Util\HtmlBuilder\HTML::create('abbr')
                ->attr('title', 'Cena je předefinovaná u způsobu doručení')
                ->text($value);
        } else {
            return $value;
        }
    }

    public function getQuery()
    {
        $qb = sqlQueryBuilder()
            ->select('dt.id',
                'COALESCE(dt.price, dtp.price + dtd.price) as price',
                'dt.price as calc_price',
                'figure',
                'dt.currency',
                'vat',
                'COALESCE(dtp.name_admin, dtp.name) as payment',
                'COALESCE(dtd.name_admin, dtd.name) as delivery',
                'dtd.price as delivery_price',
                'dtd.currency as delivery_price_currency',
                'dtp.price as payment_price',
                'dtp.currency as payment_price_currency',
                'dt.price_dont_countin_from',
                'dtd.position * 1000 + dtp.position as list_order')
            ->from('delivery_type', 'dt')
            ->leftJoin('dt', 'delivery_type_delivery', 'dtd', 'dt.id_delivery = dtd.id')
            ->leftJoin('dt', 'delivery_type_payment', 'dtp', 'dt.id_payment = dtp.id')
            ->orderBy('dtd.position, dtp.position');

        $payments = getVal('payment');
        if ($payments) {
            $qb->andWhere(Invert::checkInvert(Operator::inStringArray($payments, 'dtp.id'), getVal('payment_invert')));
        }

        $delivery = getVal('delivery');
        if ($delivery) {
            $qb->andWhere(Invert::checkInvert(Operator::inStringArray($delivery, 'dtd.id'), getVal('delivery_invert')));
        }

        $figure = getVal('figure');
        if ($figure) {
            $qb->andWhere(Operator::equals(['figure' => $figure]));
        }

        $country = getVal('country');
        if ($country) {
            $opDel = array_map(function ($value) {
                return JsonOperator::search('dtd.data', $value, 'one', '$.restrictions.countries');
            }, $country);
            $opPay = array_map(function ($value) {
                return JsonOperator::search('dtp.data', $value, 'one', '$.restrictions.countries');
            }, $country);
            $arrayMerge = array_merge($opDel, $opPay);
            $qb->andWhere(Invert::checkInvert(Operator::orX($arrayMerge), getVal('country_invert')));
        }

        return $qb;
    }
}
