<?php

/**
 * Created by PhpStorm.
 * User: ondra
 * Date: 2.1.18
 * Time: 12:22.
 */

namespace KupShop\OrderingBundle\Util\Order;

use KupShop\OrderingBundle\Entity\Order\OrderItem;
use Query\Operator;

class OrderItemInfo
{
    public const TYPE_DELIVERY = 'delivery';

    public const TYPE_RETURN_DELIVERY = 'return_delivery';
    public const TYPE_DISCOUNT = 'discount';
    public const TYPE_GIFT = 'gift';
    public const TYPE_PRODUCT = 'product';
    public const TYPE_COUPON = 'coupon';
    public const TYPE_CHARGE = 'orders_charge';
    public const TYPE_RETURN = 'return';
    public const TYPE_TEXT = 'text';
    public const TYPE_ROUNDING = 'rounding';

    public const VAT_HIGH = 'high';
    public const VAT_LOW = 'low';
    public const VAT_LOW2 = 'low2';
    public const VAT_NONE = 'none';

    protected ?array $vats;

    public function getItemType($item)
    {
        if ($item_type = ($item['note']['item_type'] ?? false)) {
            return $item_type;
        }

        if ($item['id_product'] === null) {
            if ($item['total_price']['value_with_vat']->isPositive()) {
                return self::TYPE_DELIVERY;
            } elseif ($item['total_price']['value_with_vat']->isNegative()) {
                return self::TYPE_DISCOUNT;
            }
        }

        return self::TYPE_PRODUCT;
    }

    private function getOrderIdFromItem($item)
    {
        $order = sqlQueryBuilder()
            ->select('o.id')
            ->from('order_items', 'oi')
            ->leftJoin('oi', 'orders', 'o', 'oi.id_order = o.id')
            ->where(Operator::equals(['oi.id' => $item['id']]))
            ->execute()->fetch();

        if ($order) {
            return $order['id'];
        }

        return null;
    }

    public function setCustomDataItem(OrderItem|array $item, string $key, $value)
    {
        $data = $this->getCustomData($item);

        $data[$key] = $value;

        $this->setCustomData($item, $data);
    }

    public function getCustomDataItem(OrderItem|array $item, string $key, $default = null)
    {
        $data = $this->getCustomData($item) ?? [];

        return array_key_exists($key, $data) ? $data[$key] : $default;
    }

    public function getCustomData(OrderItem|array $item)
    {
        $data = sqlQueryBuilder()
            ->select('note')
            ->from('order_items', 'oi')
            ->where(Operator::equals(['oi.id' => $item['id']]))
            ->execute()->fetchColumn();

        return json_decode($data, true);
    }

    public function setCustomData(OrderItem|array $item, array $data)
    {
        sqlQueryBuilder()
            ->update('order_items')
            ->directValues([
                'note' => json_encode($data),
            ])
            ->where(Operator::equals(['id' => $item['id']]))
            ->execute();
    }

    public function getVatRateType($itemVat, $delivery_country = 'CZ', $oss = false)
    {
        if (empty($this->vats[$delivery_country])) {
            $vatsSQL = sqlQueryBuilder()
                ->select('*')
                ->from('vats');
            if (findModule(\Modules::OSS_VATS)) {
                if ($oss || $delivery_country != 'CZ') {
                    $vatsSQL->where(\Query\Operator::equals(['id_country' => $delivery_country]));
                } else {
                    $vatsSQL->andWhere('automanaged=0');
                }
            }
            foreach ($vatsSQL->execute() as $vat) {
                $data = json_decode($vat['data'] ?? '', true);
                $this->vats[$delivery_country][$vat['vat']] = $data['level'] ?? 'high';
            }
        }

        return $this->vats[$delivery_country][$itemVat] ?? static::VAT_HIGH;
    }
}
