<?php

declare(strict_types=1);

namespace External\ZNZBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;

class ResetPriceHistoryScript extends Script
{
    protected static $name = '[ZNZ] Resetovat historii cen';

    protected function run(array $arguments)
    {
        sqlQueryBuilder()
            ->update('products')
            ->set('price_for_discount', 'price')
            ->execute();

        sqlQueryBuilder()
            ->update('products_variations')
            ->set('price_for_discount', 'price')
            ->where('price IS NOT NULL')
            ->execute();

        if (findModule(\Modules::PRICELISTS)) {
            sqlQueryBuilder()
                ->update('pricelists_products', 'pp')
                ->join('pp', 'pricelists', 'p', 'p.id = pp.id_pricelist')
                ->set('pp.price_for_discount', 'pp.price')
                ->where('pp.price IS NOT NULL AND p.price_history = 1')
                ->execute();
        }

        sqlQueryBuilder()
            ->delete('price_history')
            ->execute();

        // initial price history
        sqlQuery('INSERT INTO price_history (id_product, price, last, date_change, up)
                    SELECT p.id, p.price, 1, DATE_SUB(NOW(), INTERVAL 1 DAY), 1 
                    FROM products p WHERE (p.price > 0) AND p.figure = "Y"');
        sqlQuery('INSERT INTO price_history (id_product, id_variation, price, last, date_change, up)
                    SELECT pv.id_product, pv.id, pv.price, 1, DATE_SUB(NOW(), INTERVAL 1 DAY), 1 
                    FROM products_variations pv
                        JOIN products p ON p.id = pv.id_product AND p.figure = "Y"
                    WHERE (pv.price > 0) AND pv.figure = "Y"');
    }
}

return ResetPriceHistoryScript::class;
