<?php

/**
 * Created by PhpStorm.
 * User: ondra
 * Date: 22.11.17
 * Time: 13:14.
 */

namespace KupShop\QuantityDiscountBundle\Admin\Tabs;

use KupShop\AdminBundle\Admin\WindowTab;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\QuantityDiscountBundle\Util\QuantityDiscountUtil;
use Query\Operator;

class quantityDiscountWindowTab extends WindowTab
{
    protected $title = 'flapQuantityDiscount';

    protected $template = 'quantityDiscount.tpl';

    public static function getTypes()
    {
        return [
            'products' => 1,
        ];
    }

    public function getVars($smarty_tpl_vars)
    {
        $ID = $this->getID();

        $quantityDiscountUtil = ServiceContainer::getService(QuantityDiscountUtil::class);

        $groups = $quantityDiscountUtil->getGroups();

        $discounts = [];
        foreach ($groups as $groupId => $group) {
            $discounts[$groupId] = [];
        }

        $qb = sqlQueryBuilder()
            ->select('*')
            ->from('products_quantity_discounts')
            ->where(Operator::equals(['id_product' => $ID]))
            ->orderBy('pieces, id_variation', 'ASC');

        foreach ($qb->execute() as $discount) {
            $discounts[$discount['id_group'] ?? 0][$discount['id']] = $discount;
        }

        $data['groups'] = $groups;
        $data['discounts'] = $discounts;
        $data['discounts_types'] = $quantityDiscountUtil->getDiscountTypes();

        $data['variations'] = sqlFetchAll(
            sqlQueryBuilder()
                ->select('id, title')
                ->from('products_variations')
                ->where(Operator::equals(['id_product' => $ID]))
                ->execute(),
            ['id' => 'title']
        );

        return $data;
    }

    public function handleUpdate()
    {
        parent::handleUpdate();

        $ID = $this->getID();

        $data = $this->getData();

        foreach ($data as $group => $discounts) {
            [$_, $groupId] = explode('-', $group);
            foreach ($discounts as $key => $discount) {
                if ($key == 0 || ($key < 0 && ($discount['delete'] ?? false) == 'on')) {
                    continue;
                }

                // delete
                if (($discount['delete'] ?? false) == 'on' && $key > 0) {
                    sqlQueryBuilder()
                        ->delete('products_quantity_discounts')
                        ->where(Operator::equals(['id' => $key]))
                        ->execute();
                    continue;
                }

                $variationId = empty($discount['variation']) ? null : $discount['variation'];

                $discountValue = toDecimal($this->preparePrice($discount['discount']));
                if ($discount['discount_type'] !== QuantityDiscountUtil::DISCOUNT_TYPE_PERC && $discount['with_vat']) {
                    $discountValue = $discountValue->div(toDecimal(1)->add(toDecimal($discount['vat'])->div(toDecimal(100))));
                }

                // update
                if ($key > 0) {
                    sqlQueryBuilder()
                        ->update('products_quantity_discounts')
                        ->directValues(
                            [
                                'id_variation' => $variationId,
                                'pieces' => $discount['pieces'],
                                'discount' => $discountValue,
                                'discount_type' => $discount['discount_type'],
                            ]
                        )
                        ->where(Operator::equals(['id' => $key]))
                        ->execute();
                } else {
                    sqlQueryBuilder()
                        ->insert('products_quantity_discounts')
                        ->directValues(
                            [
                                'id_group' => $groupId == 0 ? null : $groupId,
                                'id_product' => $ID,
                                'id_variation' => $variationId,
                                'pieces' => $discount['pieces'],
                                'discount' => $discountValue,
                                'discount_type' => $discount['discount_type'],
                            ]
                        )
                        ->execute();
                }
            }
        }
    }
}
