<?php

namespace KupShop\BonusProgramBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use KupShop\BonusProgramBundle\Utils\BonusComputer;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\Operator;

class GenerateOrdersBonusPoints extends Script
{
    protected static $name = 'Vygenerovat věrnostní body k objednávkám';
    protected static $defaultParameters = [
        'startDate' => '2020-01-01 00:00:00',
        'orderNOs' => ['A123', 'A124', 'A125'],
        'type' => 'update',
    ];

    protected function run(array $arguments)
    {
        /** @var BonusComputer $bonusComputer */
        $bonusComputer = ServiceContainer::getService(BonusComputer::class);

        $orders = sqlQueryBuilder()
            ->select('o.*')
            ->from('orders', 'o')
            ->leftJoin('o', 'bonus_points', 'bp', 'bp.id_order = o.id')
            ->where('o.id_user IS NOT NULL AND bp.id IS NULL AND o.status_storno = 0');

        if ($arguments['startDate'] ?? false) {
            $orders->andWhere('o.date_created >= :date')
                ->setParameter('date', $arguments['startDate']);
        }

        if ($arguments['orderNOs'] ?? false) {
            $orders->andWhere(
                Operator::inStringArray(array_values($arguments['orderNOs']), 'order_no')
            );
        }

        $this->log('Generating...');

        $count = 0;
        foreach ($orders->execute() as $o) {
            $order = new \Order();
            $order->createFromArray($o);

            if ($arguments['type'] == 'update') {
                $bonusComputer->updateBonusPoints($order);
            } else {
                // Add discount to order - enables calculating bonus points
                $bonusComputer->checkBonusPointsEarningDiscount($order);
                $bonusComputer->applyBonusPointsActions($order->getPurchaseState());
                $bonusComputer->createBonusPoints($order, '"'.$o['date_created'].'"');
            }

            $count++;
            $this->progress();
        }

        $this->log('Generated: '.$count);

        $this->log('Activating points...');
        $bonusComputer->activatePoints();
    }
}

return GenerateOrdersBonusPoints::class;
