<?php

namespace KupShop\OrderingBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use Query\Operator;

class ChangeStatusScript extends Script
{
    protected static $name = 'Nastavit stav (+ datum vyřízení) objednávkám';

    protected static $defaultParameters = [
        'display' => true,
        'orderIds' => ['123', '456'],
        'status' => '2',
        'sendMail' => false,
        // o kolik dní nastavit date_handle oproti date_created
        'dateHandleDaysAdd' => '',
    ];

    public function run(array $arguments)
    {
        // Select
        $SqlQuery = sqlQueryBuilder()->select('*')
            ->from('orders')
            ->where(Operator::inIntArray($arguments['orderIds'], 'id'))
            ->andWhere(Operator::not(Operator::equals(['status' => $arguments['status']])))
            ->execute();

        $result = $SqlQuery->fetchAllAssociative();
        foreach ($result as $record) {
            echo "{$record['order_no']}, <br>";

            if ($arguments['display']) {
                continue;
            }

            $order = new \Order();
            $order->createFromDB($record['id']);
            $order->changeStatus($arguments['status'], null, $arguments['sendMail']);
            if (!empty($arguments['dateHandleDays'])) {
                sqlQuery('UPDATE `orders` SET `date_handle`=DATE_ADD(`date_created` , INTERVAL :dateHandleDaysAdd DAY) WHERE id=:id', ['id' => $record['id'], 'dateHandleDaysAdd' => $arguments['dateHandleDaysAdd']]);
            }
        }
    }
}

return ChangeStatusScript::class;
