<?php

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class GlobalDiscounts extends Window
{
    protected $tableName = 'global_discounts';

    /** @var \KupShop\GlobalDiscountsBundle\Util\GlobalDiscounts */
    private $globalDiscounts;

    public function __construct()
    {
        $this->globalDiscounts = ServiceContainer::getService(\KupShop\GlobalDiscountsBundle\Util\GlobalDiscounts::class);
    }

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

        if (isset($vars['body']['data']['filter'])) {
            $vars['body']['data']['filter'] = json_decode($vars['body']['data']['filter'], true);
        }

        return $vars;
    }

    public function getData()
    {
        $data = parent::getData();

        if (getVal('Submit')) {
            $data['date_from'] = $this->prepareDateTime($data['date_from']);
            $data['date_to'] = $this->prepareDateTime($data['date_to']);
            $data['filter'] = json_encode(getVal('filter'));
        }

        return $data;
    }

    public function handleUpdate()
    {
        if ($this->getAction() != 'add') {
            $discount = $this->getDiscount();
            // deactivate discount before update
            // discount filter can be changed so we need to deactivate discounts that are using old filter
            if (($discount['active'] ?? false) == 1) {
                $this->globalDiscounts->deactivateDiscount($discount);
            }
        }

        $SQL = parent::handleUpdate();

        if ($SQL) {
            $this->globalDiscounts->activateDiscounts();
            clearCache('insert_products', true);
        }

        return $SQL;
    }

    public function handleDelete()
    {
        $discount = $this->getDiscount();
        // deactivate discount before delete
        if (($discount['active'] ?? false) == 1) {
            $this->globalDiscounts->deactivateDiscount($discount);
            clearCache('insert_products', true);
        }

        parent::handleDelete();
    }

    private function getDiscount()
    {
        $discount = $this->getObject();
        $discount['filter'] = json_decode($discount['filter'] ?? '', true);

        return $discount;
    }
}

return GlobalDiscounts::class;
