<?php

namespace KupShop\KupShopBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Email\OrderMessageEmail;
use Query\Operator;

class SendOrderMessagesScript extends Script
{
    protected static $name = 'Poslat zprávu uživatelům hromadně na zadané objednávky (seznam kódů)';
    protected static $defaultParameters = [
        'order_message' => '',
        'orders_codes' => [],
    ];

    protected function run(array $arguments)
    {
        if (empty($order_message_name = $arguments['order_message'] ?? '')) {
            $this->log('Empty order_message!');

            return;
        }

        if (empty($orders_codes = $arguments['orders_codes'] ?? [])) {
            $this->log('Empty orders_codes!');

            return;
        }

        $order_message = sqlQueryBuilder()->select('e.name')->from('emails', 'e')
            ->where(Operator::equals(['e.type' => OrderMessageEmail::getType()]))
            ->andWhere(Operator::equals(['e.name' => $order_message_name]))
            ->execute()->fetchColumn();
        if (!$order_message) {
            $this->log("order_message {$order_message_name} doesn't exist!");

            return;
        }

        $count = 0;
        foreach ($orders_codes as $code) {
            try {
                $order = \Order::createFromDbOrderNo($code);
                $order->changeStatus($order->status, null, true, $order_message);
                $count++;
            } catch (\InvalidArgumentException $e) {
                $this->log($e->getMessage());
            }
        }

        $this->log("Odeslano {$count} zpráv.");
    }
}

return SendOrderMessagesScript::class;
