<?php

namespace console\commands;

use domain\Order\Order\OrderModule;
use domain\Order\OrderStatus\OrderStatus;
use domain\Producer\Producer\ProducerModule;
use domain\User\User\UserModule;
use yii\console\Controller;

class InitOrderStatusHistoryController extends Controller
{
    // ./yii init-order-status-history/index
    public function actionIndex()
    {
        ini_set('memory_limit', '-1');

        /*
            Remettre à zéro :
            -----------------
            DELETE FROM `order_status_history`;
            UPDATE `order` SET `order`.order_status_alias = NULL;
        */

        $producerModule = ProducerModule::getInstance();
        $orderModule = OrderModule::getInstance();

        $userSystem = UserModule::getInstance()->getRepository()->findOneUserSystem();

        foreach($producerModule->getRepository()->findProducers() as $producer) {
            \Yii::$app->logic->setProducerContext($producer);

            $ordersArray = $orderModule->getRepository()->findOrdersWithOrderStatusAliasNull();
            echo ($ordersArray ? count($ordersArray) : '0').' : '.$producer->name."\n";

            while ($ordersArray && count($ordersArray)) {
                foreach ($ordersArray as $order) {
                    $orderModule->getManager()->changeOrderStatus(
                        $order,
                        OrderStatus::ALIAS_ORDERED,
                        $userSystem,
                        new \DateTime($order->date)
                    );
                    if($order->date_update) {
                        $orderModule->getManager()->changeOrderStatus(
                            $order,
                            OrderStatus::ALIAS_UPDATED,
                            $userSystem,
                            new \DateTime($order->date_update)
                        );
                    }
                    if($order->date_delete) {
                        $orderModule->getManager()->changeOrderStatus(
                            $order,
                            OrderStatus::ALIAS_DELETED,
                            $userSystem,
                            new \DateTime($order->date_delete)
                        );
                    }

                    echo 'Order #'.$order->id."\n";
                }
                $ordersArray = $orderModule->getRepository()->findOrdersWithOrderStatusAliasNull();
            }
        }
    }
}