<?php

namespace KupShop\ElninoBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;

class CheckPaidOrders extends Script
{
    protected static $name = 'Opravit zaplacené objednávky s chybným stavem zaplacení';

    protected static $defaultParameters = [
        'dryRun' => true,
        'dateFrom' => '2021-05-21',
        'limit' => 1000,
    ];

    protected function run(array $arguments)
    {
        $this->log('Starting...');

        $qb = sqlQueryBuilder()->select('o.id, o.order_no')
            ->from('orders', 'o')
            ->innerJoin('o', 'order_payments', 'op', 'op.id_order=o.id AND op.status = 0')
            ->where('o.status_payed = 0 AND o.date_updated >= :dateFrom')
            ->setParameter('dateFrom', $arguments['dateFrom'])
            ->setMaxResults($arguments['limit']);

        $counter = 0;
        foreach ($qb->execute() as $row) {
            $counter++;
            $this->log("Objednávka: {$row['order_no']} [{$row['id']}], ");
            if (!$arguments['dryRun']) {
                $order = new \Order();
                $order->createFromDB($row['id']);
                $order->updatePayments();
            }
        }

        if ($arguments['dryRun']) {
            $this->log("Celkem nalezeno {$counter} objednávek.");
        } else {
            $this->log("Hotovo. Opraveno {$counter} objednávek.");
        }
    }
}

return CheckPaidOrders::class;
