<?php

declare(strict_types=1);

namespace External\ZNZBundle\Resources\script;

use External\ZNZBundle\BonusProgram\Utils\PointEvaluator;
use KupShop\AdminBundle\Util\Script\Script;
use KupShop\BonusProgramBundle\Utils\BonusComputer;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\Operator;

class GenerateBonusPointsScript extends Script
{
    protected static $name = '[ZNZ] Vygenerovat body podle objednávek';
    protected static $defaultParameters = [
        'source' => null,
    ];

    protected function run(array $arguments)
    {
        $qb = sqlQueryBuilder()
            ->select('o.id, o.order_no, o.id_user, o.date_created, o.total_price')
            ->from('orders', 'o')
            ->leftJoin('o', 'bonus_points', 'bp', 'bp.id_order = o.id')
            ->andWhere(Operator::equals(['o.status_storno' => 0]))
            ->andWhere('o.id_user IS NOT NULL AND bp.id IS NULL');

        if ($arguments['source'] ?? null) {
            $qb->andWhere(Operator::equals(['o.source' => $arguments['source']]));
        }

        $pointValue = PointEvaluator::getPointValue();
        if (!$pointValue->isPositive()) {
            return;
        }

        $bonusComputer = ServiceContainer::getService(BonusComputer::class);

        foreach ($qb->execute() as $item) {
            $totalPrice = toDecimal($item['total_price']);
            if (!$totalPrice->isPositive()) {
                continue;
            }

            $points = $totalPrice->div($pointValue, 2)->floor();

            sqlQueryBuilder()
                ->insert('bonus_points')
                ->directValues(
                    [
                        'id_user' => $item['id_user'],
                        'id_order' => $item['id'],
                        'date_created' => $item['date_created'],
                        'note' => 'Body za objednávku číslo '.$item['order_no'],
                        'status' => 'active',
                        'points' => $points->asInteger(),
                    ]
                )->execute();
        }

        $bonusComputer->deleteExpiredPoints();
    }
}

return GenerateBonusPointsScript::class;
