<?php

use Query\Operator;

class Pricelist extends Window
{
    protected $nameField = 'name';

    protected $tableName = 'pricelists';

    /** @var \Doctrine\ORM\EntityManager */
    private $em;

    public function __construct()
    {
        $this->em = \KupShop\KupShopBundle\Util\Compat\ServiceContainer::getService('doctrine.orm.entity_manager');
    }

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

        $pageVars = getVal('body', $vars);

        $pageVars['currencies'] = $this->getCurrencies();

        $this->unserializeCustomData($pageVars['data']);

        $vars['body'] = $pageVars;

        return $vars;
    }

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

        if (!empty($data)) {
            if (findModule(Modules::PRICE_HISTORY)) {
                $data['price_history'] = ($data['price_history'] === 'Y' || $data['price_history'] == 1) ? 1 : 0;
            }

            $data['data'] = array_merge($this->getCustomData(), $data['data'] ?? []);

            $this->serializeCustomData($data);
        }

        return $data;
    }

    public function handleUpdate()
    {
        $currentPriceHistory = $this->getObject()['price_history'] ?? null;

        $result = parent::handleUpdate();

        if (findModule(Modules::PRICE_HISTORY) && $this->getID()) {
            $priceHistory = $this->getData()['price_history'] ?? false;
            // pokud se zmenila hodnota v poli price_history
            if ($currentPriceHistory != $priceHistory) {
                // historie cen byla zapnuta
                if ($priceHistory) {
                    // Insertnu prvotni historii
                    sqlQuery('
                INSERT INTO price_history (id_pricelist, id_product, id_variation, price, last, date_change, up)
                    SELECT
                        pp.id_pricelist,
                        pp.id_product,
                        pp.id_variation,
                        pp.price,
                        1,
                        DATE_SUB(NOW(), INTERVAL 1 DAY),
                        1
                    FROM pricelists_products pp
                    JOIN products p ON p.id = pp.id_product
                    WHERE (pp.price > 0) AND p.figure = "Y" AND pp.id_pricelist = :priceListId;
                ',
                        ['priceListId' => $this->getID()]);

                    // Nastavit CPS
                    sqlQueryBuilder()
                        ->update('pricelists_products', 'pp')
                        ->join('pp', 'products', 'p', 'p.id = pp.id_product')
                        ->leftJoin('pp', 'products_variations', 'pv', 'pv.id = pp.id_variation')
                        ->set('pp.price_for_discount', 'COALESCE(pp.price, pv.price, p.price)')
                        ->where(Operator::equals(['pp.id_pricelist' => $this->getID()]))
                        ->execute();
                } else { // historie cen u ceniku byla vypnuta
                    // Smazani CPS
                    sqlQueryBuilder()
                        ->update('pricelists_products')
                        ->directValues(['price_for_discount' => null])
                        ->where(Operator::equals(['id_pricelist' => $this->getID()]))
                        ->execute();

                    // Smazani historie
                    sqlQueryBuilder()
                        ->delete('price_history')
                        ->where(Operator::equals(['id_pricelist' => $this->getID()]))
                        ->execute();
                }
            }
        }

        return $result;
    }

    private function getCurrencies()
    {
        $repository = $this->em->getRepository(\KupShop\I18nBundle\Entity\Currency::class);

        return $repository->findAll();
    }

    public function handleGeneratePricelistToken(): void
    {
        $token = bin2hex(random_bytes(16));

        sqlQueryBuilder()
            ->update('pricelists')
            ->directValues(['token' => $token])
            ->where(Operator::equals(['id' => $this->getID()]))
            ->execute();

        $this->returnOK();
    }
}

$countries = new Pricelist();
$countries->run();
